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
177 $this->totalusers
= (int)$DB->count_records_sql($sqltotal, $params);
179 return $this->totalusers
;
183 * Returns the total number of enrolled users in the course.
185 * If a filter was specificed this will be the total number of users enrolled
186 * in this course by means of that instance.
188 * @global moodle_database $DB
191 public function get_total_other_users() {
193 if ($this->totalotherusers
=== null) {
194 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
195 $params['courseid'] = $this->course
->id
;
196 $sql = "SELECT COUNT(DISTINCT u.id)
197 FROM {role_assignments} ra
198 JOIN {user} u ON u.id = ra.userid
199 JOIN {context} ctx ON ra.contextid = ctx.id
201 SELECT ue.id, ue.userid
202 FROM {user_enrolments} ue
203 LEFT JOIN {enrol} e ON e.id=ue.enrolid
204 WHERE e.courseid = :courseid
205 ) ue ON ue.userid=u.id
206 WHERE ctx.id $ctxcondition AND
208 $this->totalotherusers
= (int)$DB->count_records_sql($sql, $params);
210 return $this->totalotherusers
;
214 * Gets all of the users enrolled in this course.
216 * If a filter was specified this will be the users who were enrolled
217 * in this course by means of that instance. If role or search filters were
218 * specified then these will also be applied.
220 * @global moodle_database $DB
221 * @param string $sort
222 * @param string $direction ASC or DESC
223 * @param int $page First page should be 0
224 * @param int $perpage Defaults to 25
227 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
229 if ($direction !== 'ASC') {
232 $key = md5("$sort-$direction-$page-$perpage");
233 if (!array_key_exists($key, $this->users
)) {
234 list($instancessql, $params, $filter) = $this->get_instance_sql();
235 list($filtersql, $moreparams) = $this->get_filter_sql();
236 $params +
= $moreparams;
237 $extrafields = get_extra_user_fields($this->get_context());
238 $extrafields[] = 'lastaccess';
239 $ufields = user_picture
::fields('u', $extrafields);
240 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
242 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
243 JOIN {enrol} e ON (e.id = ue.enrolid)
244 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)
245 LEFT JOIN {groups_members} gm ON u.id = gm.userid
247 if ($sort === 'firstname') {
248 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
249 } else if ($sort === 'lastname') {
250 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
251 } else if ($sort === 'email') {
252 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
253 } else if ($sort === 'lastseen') {
254 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $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 $sql .= " AND gm.groupid = :groupid";
292 $params['groupid'] = $this->groupfilter
;
296 if ($this->statusfilter
=== ENROL_USER_ACTIVE
) {
297 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
298 AND (ue.timeend = 0 OR ue.timeend > :now2)";
299 $now = round(time(), -2); // rounding helps caching in DB
300 $params +
= array('enabled' => ENROL_INSTANCE_ENABLED
,
301 'active' => ENROL_USER_ACTIVE
,
304 } else if ($this->statusfilter
=== ENROL_USER_SUSPENDED
) {
305 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
306 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
307 $now = round(time(), -2); // rounding helps caching in DB
308 $params +
= array('disabled' => ENROL_INSTANCE_DISABLED
,
309 'inactive' => ENROL_USER_SUSPENDED
,
314 return array($sql, $params);
318 * Gets and array of other users.
320 * Other users are users who have been assigned roles or inherited roles
321 * within this course but who have not been enrolled in the course
323 * @global moodle_database $DB
324 * @param string $sort
325 * @param string $direction
327 * @param int $perpage
330 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
332 if ($direction !== 'ASC') {
335 $key = md5("$sort-$direction-$page-$perpage");
336 if (!array_key_exists($key, $this->otherusers
)) {
337 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
338 $params['courseid'] = $this->course
->id
;
339 $params['cid'] = $this->course
->id
;
340 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
341 FROM {role_assignments} ra
342 JOIN {user} u ON u.id = ra.userid
343 JOIN {context} ctx ON ra.contextid = ctx.id
345 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
346 FROM {user_enrolments} ue
347 LEFT JOIN {enrol} e ON e.id=ue.enrolid
348 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
349 WHERE e.courseid = :courseid
350 ) ue ON ue.userid=u.id
351 WHERE ctx.id $ctxcondition AND
353 ORDER BY u.$sort $direction, ctx.depth DESC";
354 $this->otherusers
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
356 return $this->otherusers
[$key];
360 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
362 * @param string $search the search term, if any.
363 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
364 * @return array with three elements:
365 * string list of fields to SELECT,
366 * string contents of SQL WHERE clause,
367 * array query params. Note that the SQL snippets use named parameters.
369 protected function get_basic_search_conditions($search, $searchanywhere) {
372 // Add some additional sensible conditions
373 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
374 $params = array('guestid' => $CFG->siteguest
);
375 if (!empty($search)) {
376 $conditions = get_extra_user_fields($this->get_context());
377 $conditions[] = 'u.firstname';
378 $conditions[] = 'u.lastname';
379 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
380 if ($searchanywhere) {
381 $searchparam = '%' . $search . '%';
383 $searchparam = $search . '%';
386 foreach ($conditions as $key => $condition) {
387 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
388 $params["con{$i}00"] = $searchparam;
391 $tests[] = '(' . implode(' OR ', $conditions) . ')';
393 $wherecondition = implode(' AND ', $tests);
395 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
396 $extrafields[] = 'username';
397 $extrafields[] = 'lastaccess';
398 $ufields = user_picture
::fields('u', $extrafields);
400 return array($ufields, $params, $wherecondition);
404 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
406 * @param string $search the search string, if any.
407 * @param string $fields the first bit of the SQL when returning some users.
408 * @param string $countfields fhe first bit of the SQL when counting the users.
409 * @param string $sql the bulk of the SQL statement.
410 * @param array $params query parameters.
411 * @param int $page which page number of the results to show.
412 * @param int $perpage number of users per page.
413 * @param int $addedenrollment number of users added to enrollment.
414 * @return array with two elememts:
415 * int total number of users matching the search.
416 * array of user objects returned by the query.
418 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
421 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
422 $order = ' ORDER BY ' . $sort;
424 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
425 $availableusers = $DB->get_records_sql($fields . $sql . $order,
426 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
428 return array('totalusers' => $totalusers, 'users' => $availableusers);
432 * Gets an array of the users that can be enrolled in this course.
434 * @global moodle_database $DB
435 * @param int $enrolid
436 * @param string $search
437 * @param bool $searchanywhere
438 * @param int $page Defaults to 0
439 * @param int $perpage Defaults to 25
440 * @param int $addedenrollment Defaults to 0
441 * @return array Array(totalusers => int, users => array)
443 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
446 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
448 $fields = 'SELECT '.$ufields;
449 $countfields = 'SELECT COUNT(1)';
450 $sql = " FROM {user} u
451 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
452 WHERE $wherecondition
454 $params['enrolid'] = $enrolid;
456 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
460 * Searches other users and returns paginated results
462 * @global moodle_database $DB
463 * @param string $search
464 * @param bool $searchanywhere
465 * @param int $page Starting at 0
466 * @param int $perpage
469 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
472 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
474 $fields = 'SELECT ' . $ufields;
475 $countfields = 'SELECT COUNT(u.id)';
476 $sql = " FROM {user} u
477 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
478 WHERE $wherecondition
480 $params['contextid'] = $this->context
->id
;
482 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
486 * Gets an array containing some SQL to user for when selecting, params for
487 * that SQL, and the filter that was used in constructing the sql.
489 * @global moodle_database $DB
492 protected function get_instance_sql() {
494 if ($this->_instancessql
=== null) {
495 $instances = $this->get_enrolment_instances();
496 $filter = $this->get_enrolment_filter();
497 if ($filter && array_key_exists($filter, $instances)) {
498 $sql = " = :ifilter";
499 $params = array('ifilter'=>$filter);
503 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED
);
505 // no enabled instances, oops, we should probably say something
507 $params = array('never'=>-1);
510 $this->instancefilter
= $filter;
511 $this->_instancessql
= array($sql, $params, $filter);
513 return $this->_instancessql
;
517 * Returns all of the enrolment instances for this course.
519 * NOTE: since 2.4 it includes instances of disabled plugins too.
523 public function get_enrolment_instances() {
524 if ($this->_instances
=== null) {
525 $this->_instances
= enrol_get_instances($this->course
->id
, false);
527 return $this->_instances
;
531 * Returns the names for all of the enrolment instances for this course.
533 * NOTE: since 2.4 it includes instances of disabled plugins too.
537 public function get_enrolment_instance_names() {
538 if ($this->_inames
=== null) {
539 $instances = $this->get_enrolment_instances();
540 $plugins = $this->get_enrolment_plugins(false);
541 foreach ($instances as $key=>$instance) {
542 if (!isset($plugins[$instance->enrol
])) {
543 // weird, some broken stuff in plugin
544 unset($instances[$key]);
547 $this->_inames
[$key] = $plugins[$instance->enrol
]->get_instance_name($instance);
550 return $this->_inames
;
554 * Gets all of the enrolment plugins that are active for this course.
556 * @param bool $onlyenabled return only enabled enrol plugins
559 public function get_enrolment_plugins($onlyenabled = true) {
560 if ($this->_plugins
=== null) {
561 $this->_plugins
= enrol_get_plugins(true);
565 return $this->_plugins
;
568 if ($this->_allplugins
=== null) {
569 // Make sure we have the same objects in _allplugins and _plugins.
570 $this->_allplugins
= $this->_plugins
;
571 foreach (enrol_get_plugins(false) as $name=>$plugin) {
572 if (!isset($this->_allplugins
[$name])) {
573 $this->_allplugins
[$name] = $plugin;
578 return $this->_allplugins
;
582 * Gets all of the roles this course can contain.
586 public function get_all_roles() {
587 if ($this->_roles
=== null) {
588 $this->_roles
= role_fix_names(get_all_roles($this->context
), $this->context
);
590 return $this->_roles
;
594 * Gets all of the assignable roles for this course.
598 public function get_assignable_roles($otherusers = false) {
599 if ($this->_assignableroles
=== null) {
600 $this->_assignableroles
= get_assignable_roles($this->context
, ROLENAME_ALIAS
, false); // verifies unassign access control too
604 if (!is_array($this->_assignablerolesothers
)) {
605 $this->_assignablerolesothers
= array();
606 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context
, 'moodle/course:view');
607 foreach ($this->_assignableroles
as $roleid=>$role) {
608 if (isset($courseviewroles[$roleid])) {
609 $this->_assignablerolesothers
[$roleid] = $role;
613 return $this->_assignablerolesothers
;
615 return $this->_assignableroles
;
620 * Gets all of the groups for this course.
624 public function get_all_groups() {
625 if ($this->_groups
=== null) {
626 $this->_groups
= groups_get_all_groups($this->course
->id
);
627 foreach ($this->_groups
as $gid=>$group) {
628 $this->_groups
[$gid]->name
= format_string($group->name
);
631 return $this->_groups
;
635 * Unenrols a user from the course given the users ue entry
637 * @global moodle_database $DB
638 * @param stdClass $ue
641 public function unenrol_user($ue) {
643 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
644 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context
)) {
645 $plugin->unenrol_user($instance, $ue->userid
);
652 * Given a user enrolment record this method returns the plugin and enrolment
653 * instance that relate to it.
655 * @param stdClass|int $userenrolment
656 * @return array array($instance, $plugin)
658 public function get_user_enrolment_components($userenrolment) {
660 if (is_numeric($userenrolment)) {
661 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
663 $instances = $this->get_enrolment_instances();
664 $plugins = $this->get_enrolment_plugins(false);
665 if (!$userenrolment ||
!isset($instances[$userenrolment->enrolid
])) {
666 return array(false, false);
668 $instance = $instances[$userenrolment->enrolid
];
669 $plugin = $plugins[$instance->enrol
];
670 return array($instance, $plugin);
674 * Removes an assigned role from a user.
676 * @global moodle_database $DB
681 public function unassign_role_from_user($userid, $roleid) {
683 // Admins may unassign any role, others only those they could assign.
684 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
685 if (defined('AJAX_SCRIPT')) {
686 throw new moodle_exception('invalidrole');
690 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
691 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context
->id
, 'userid'=>$user->id
, 'roleid'=>$roleid));
692 foreach ($ras as $ra) {
693 if ($ra->component
) {
694 if (strpos($ra->component
, 'enrol_') !== 0) {
697 if (!$plugin = enrol_get_plugin(substr($ra->component
, 6))) {
700 if ($plugin->roles_protected()) {
704 role_unassign($ra->roleid
, $ra->userid
, $ra->contextid
, $ra->component
, $ra->itemid
);
710 * Assigns a role to a user.
716 public function assign_role_to_user($roleid, $userid) {
717 require_capability('moodle/role:assign', $this->context
);
718 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
719 if (defined('AJAX_SCRIPT')) {
720 throw new moodle_exception('invalidrole');
724 return role_assign($roleid, $userid, $this->context
->id
, '', NULL);
728 * Adds a user to a group
730 * @param stdClass $user
731 * @param int $groupid
734 public function add_user_to_group($user, $groupid) {
735 require_capability('moodle/course:managegroups', $this->context
);
736 $group = $this->get_group($groupid);
740 return groups_add_member($group->id
, $user->id
);
744 * Removes a user from a group
746 * @global moodle_database $DB
747 * @param StdClass $user
748 * @param int $groupid
751 public function remove_user_from_group($user, $groupid) {
753 require_capability('moodle/course:managegroups', $this->context
);
754 $group = $this->get_group($groupid);
755 if (!groups_remove_member_allowed($group, $user)) {
761 return groups_remove_member($group, $user);
765 * Gets the requested group
767 * @param int $groupid
768 * @return stdClass|int
770 public function get_group($groupid) {
771 $groups = $this->get_all_groups();
772 if (!array_key_exists($groupid, $groups)) {
775 return $groups[$groupid];
781 * @param stdClass $userenrolment
782 * @param stdClass $data
785 public function edit_enrolment($userenrolment, $data) {
786 //Only allow editing if the user has the appropriate capability
787 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
788 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
789 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context
)) {
790 if (!isset($data->status
)) {
791 $data->status
= $userenrolment->status
;
793 $plugin->update_user_enrol($instance, $userenrolment->userid
, $data->status
, $data->timestart
, $data->timeend
);
800 * Returns the current enrolment filter that is being applied by this class
803 public function get_enrolment_filter() {
804 return $this->instancefilter
;
808 * Gets the roles assigned to this user that are applicable for this course.
813 public function get_user_roles($userid) {
815 $ras = get_user_roles($this->context
, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
816 $plugins = $this->get_enrolment_plugins(false);
817 foreach ($ras as $ra) {
818 if ($ra->contextid
!= $this->context
->id
) {
819 if (!array_key_exists($ra->roleid
, $roles)) {
820 $roles[$ra->roleid
] = null;
822 // higher ras, course always takes precedence
825 if (array_key_exists($ra->roleid
, $roles) && $roles[$ra->roleid
] === false) {
829 if ($ra->component
) {
831 if (strpos($ra->component
, 'enrol_') === 0) {
832 $plugin = substr($ra->component
, 6);
833 if (isset($plugins[$plugin])) {
834 $changeable = !$plugins[$plugin]->roles_protected();
839 $roles[$ra->roleid
] = $changeable;
845 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
847 * @global moodle_database $DB
851 public function get_user_enrolments($userid) {
853 list($instancessql, $params, $filter) = $this->get_instance_sql();
854 $params['userid'] = $userid;
855 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
856 $instances = $this->get_enrolment_instances();
857 $plugins = $this->get_enrolment_plugins(false);
858 $inames = $this->get_enrolment_instance_names();
859 foreach ($userenrolments as &$ue) {
860 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
861 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
862 $ue->enrolmentinstancename
= $inames[$ue->enrolmentinstance
->id
];
864 return $userenrolments;
868 * Gets the groups this user belongs to
873 public function get_user_groups($userid) {
874 return groups_get_all_groups($this->course
->id
, $userid, 0, 'g.id');
878 * Retursn an array of params that would go into the URL to return to this
883 public function get_url_params() {
885 'id' => $this->course
->id
887 if (!empty($this->instancefilter
)) {
888 $args['ifilter'] = $this->instancefilter
;
890 if (!empty($this->rolefilter
)) {
891 $args['role'] = $this->rolefilter
;
893 if ($this->searchfilter
!== '') {
894 $args['search'] = $this->searchfilter
;
896 if (!empty($this->groupfilter
)) {
897 $args['group'] = $this->groupfilter
;
899 if ($this->statusfilter
!== -1) {
900 $args['status'] = $this->statusfilter
;
906 * Returns the course this object is managing enrolments for
910 public function get_course() {
911 return $this->course
;
915 * Returns the course context
919 public function get_context() {
920 return $this->context
;
924 * Gets an array of other users in this course ready for display.
926 * Other users are users who have been assigned or inherited roles within this
927 * course but have not been enrolled.
929 * @param core_enrol_renderer $renderer
930 * @param moodle_url $pageurl
931 * @param string $sort
932 * @param string $direction ASC | DESC
933 * @param int $page Starting from 0
934 * @param int $perpage
937 public function get_other_users_for_display(core_enrol_renderer
$renderer, moodle_url
$pageurl, $sort, $direction, $page, $perpage) {
939 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
940 $roles = $this->get_all_roles();
941 $plugins = $this->get_enrolment_plugins(false);
943 $context = $this->get_context();
945 $extrafields = get_extra_user_fields($context);
948 foreach ($userroles as $userrole) {
949 $contextid = $userrole->contextid
;
950 unset($userrole->contextid
); // This would collide with user avatar.
951 if (!array_key_exists($userrole->id
, $users)) {
952 $users[$userrole->id
] = $this->prepare_user_for_display($userrole, $extrafields, $now);
955 $a->role
= $roles[$userrole->roleid
]->localname
;
956 if ($contextid == $this->context
->id
) {
958 if ($userrole->component
) {
960 if (strpos($userrole->component
, 'enrol_') === 0) {
961 $plugin = substr($userrole->component
, 6);
962 if (isset($plugins[$plugin])) {
963 $changeable = !$plugins[$plugin]->roles_protected();
967 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
970 switch ($userrole->contextlevel
) {
971 case CONTEXT_COURSE
:
973 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
975 case CONTEXT_COURSECAT
:
976 $roletext = get_string('rolefromcategory', 'enrol', $a);
980 $roletext = get_string('rolefromsystem', 'enrol', $a);
984 if (!isset($users[$userrole->id
]['roles'])) {
985 $users[$userrole->id
]['roles'] = array();
987 $users[$userrole->id
]['roles'][$userrole->roleid
] = array(
989 'unchangeable' => !$changeable
996 * Gets an array of users for display, this includes minimal user information
997 * as well as minimal information on the users roles, groups, and enrolments.
999 * @param core_enrol_renderer $renderer
1000 * @param moodle_url $pageurl
1002 * @param string $direction ASC or DESC
1004 * @param int $perpage
1007 public function get_users_for_display(course_enrolment_manager
$manager, $sort, $direction, $page, $perpage) {
1008 $pageurl = $manager->get_moodlepage()->url
;
1009 $users = $this->get_users($sort, $direction, $page, $perpage);
1012 $straddgroup = get_string('addgroup', 'group');
1013 $strunenrol = get_string('unenrol', 'enrol');
1014 $stredit = get_string('edit');
1016 $allroles = $this->get_all_roles();
1017 $assignable = $this->get_assignable_roles();
1018 $allgroups = $this->get_all_groups();
1019 $context = $this->get_context();
1020 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1022 $url = new moodle_url($pageurl, $this->get_url_params());
1023 $extrafields = get_extra_user_fields($context);
1025 $enabledplugins = $this->get_enrolment_plugins(true);
1027 $userdetails = array();
1028 foreach ($users as $user) {
1029 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1032 $details['roles'] = array();
1033 foreach ($this->get_user_roles($user->id
) as $rid=>$rassignable) {
1034 $unchangeable = !$rassignable;
1035 if (!is_siteadmin() and !isset($assignable[$rid])) {
1036 $unchangeable = true;
1038 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname
, 'unchangeable'=>$unchangeable);
1042 $usergroups = $this->get_user_groups($user->id
);
1043 $details['groups'] = array();
1044 foreach($usergroups as $gid=>$unused) {
1045 $details['groups'][$gid] = $allgroups[$gid]->name
;
1049 $details['enrolments'] = array();
1050 foreach ($this->get_user_enrolments($user->id
) as $ue) {
1051 if (!isset($enabledplugins[$ue->enrolmentinstance
->enrol
])) {
1052 $details['enrolments'][$ue->id
] = array(
1053 'text' => $ue->enrolmentinstancename
,
1056 'actions' => array()
1059 } else if ($ue->timestart
and $ue->timeend
) {
1060 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart
), 'end'=>userdate($ue->timeend
)));
1061 $periodoutside = ($ue->timestart
&& $ue->timeend
&& ($now < $ue->timestart ||
$now > $ue->timeend
));
1062 } else if ($ue->timestart
) {
1063 $period = get_string('periodstart', 'enrol', userdate($ue->timestart
));
1064 $periodoutside = ($ue->timestart
&& $now < $ue->timestart
);
1065 } else if ($ue->timeend
) {
1066 $period = get_string('periodend', 'enrol', userdate($ue->timeend
));
1067 $periodoutside = ($ue->timeend
&& $now > $ue->timeend
);
1069 // If there is no start or end show when user was enrolled.
1070 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated
));
1071 $periodoutside = false;
1073 $details['enrolments'][$ue->id
] = array(
1074 'text' => $ue->enrolmentinstancename
,
1075 'period' => $period,
1076 'dimmed' => ($periodoutside or $ue->status
!= ENROL_USER_ACTIVE
or $ue->enrolmentinstance
->status
!= ENROL_INSTANCE_ENABLED
),
1077 'actions' => $ue->enrolmentplugin
->get_user_enrolment_actions($manager, $ue)
1080 $userdetails[$user->id
] = $details;
1082 return $userdetails;
1086 * Prepare a user record for display
1088 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1089 * prepare user fields for display
1091 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1093 * @param object $user The user record
1094 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1095 * additional fields may be displayed
1096 * @param int $now The time used for lastaccess calculation
1097 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
1098 * additional fields from $extrafields
1100 private function prepare_user_for_display($user, $extrafields, $now) {
1102 'userid' => $user->id
,
1103 'courseid' => $this->get_course()->id
,
1104 'picture' => new user_picture($user),
1105 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1106 'lastseen' => get_string('never'),
1108 foreach ($extrafields as $field) {
1109 $details[$field] = $user->{$field};
1112 if ($user->lastaccess
) {
1113 $details['lastseen'] = format_time($now - $user->lastaccess
);
1118 public function get_manual_enrol_buttons() {
1119 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1121 foreach ($plugins as $plugin) {
1122 $newbutton = $plugin->get_manual_enrol_button($this);
1123 if (is_array($newbutton)) {
1124 $buttons +
= $newbutton;
1125 } else if ($newbutton instanceof enrol_user_button
) {
1126 $buttons[] = $newbutton;
1132 public function has_instance($enrolpluginname) {
1133 // Make sure manual enrolments instance exists
1134 foreach ($this->get_enrolment_instances() as $instance) {
1135 if ($instance->enrol
== $enrolpluginname) {
1143 * Returns the enrolment plugin that the course manager was being filtered to.
1145 * If no filter was being applied then this function returns false.
1147 * @return enrol_plugin
1149 public function get_filtered_enrolment_plugin() {
1150 $instances = $this->get_enrolment_instances();
1151 $plugins = $this->get_enrolment_plugins(false);
1153 if (empty($this->instancefilter
) ||
!array_key_exists($this->instancefilter
, $instances)) {
1157 $instance = $instances[$this->instancefilter
];
1158 return $plugins[$instance->enrol
];
1162 * Returns and array of users + enrolment details.
1164 * Given an array of user id's this function returns and array of user enrolments for those users
1165 * as well as enough user information to display the users name and picture for each enrolment.
1167 * @global moodle_database $DB
1168 * @param array $userids
1171 public function get_users_enrolments(array $userids) {
1174 $instances = $this->get_enrolment_instances();
1175 $plugins = $this->get_enrolment_plugins(false);
1177 if (!empty($this->instancefilter
)) {
1178 $instancesql = ' = :instanceid';
1179 $instanceparams = array('instanceid' => $this->instancefilter
);
1181 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED
, 'instanceid0000');
1184 $userfields = user_picture
::fields('u');
1185 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid0000');
1187 list($sort, $sortparams) = users_order_by_sql('u');
1189 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1190 FROM {user_enrolments} ue
1191 LEFT JOIN {user} u ON u.id = ue.userid
1192 WHERE ue.enrolid $instancesql AND
1196 $rs = $DB->get_recordset_sql($sql, $idparams +
$instanceparams +
$sortparams);
1198 foreach ($rs as $ue) {
1199 $user = user_picture
::unalias($ue);
1200 $ue->id
= $ue->ueid
;
1202 if (!array_key_exists($user->id
, $users)) {
1203 $user->enrolments
= array();
1204 $users[$user->id
] = $user;
1206 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
1207 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
1208 $users[$user->id
]->enrolments
[$ue->id
] = $ue;
1216 * A button that is used to enrol users in a course
1218 * @copyright 2010 Sam Hemelryk
1219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1221 class enrol_user_button
extends single_button
{
1224 * An array containing JS YUI modules required by this button
1227 protected $jsyuimodules = array();
1230 * An array containing JS initialisation calls required by this button
1233 protected $jsinitcalls = array();
1236 * An array strings required by JS for this button
1239 protected $jsstrings = array();
1242 * Initialises the new enrol_user_button
1244 * @staticvar int $count The number of enrol user buttons already created
1245 * @param moodle_url $url
1246 * @param string $label The text to display in the button
1247 * @param string $method Either post or get
1249 public function __construct(moodle_url
$url, $label, $method = 'post') {
1252 parent
::__construct($url, $label, $method);
1253 $this->class = 'singlebutton enrolusersbutton';
1254 $this->formid
= 'enrolusersbutton-'.$count;
1258 * Adds a YUI module call that will be added to the page when the button is used.
1260 * @param string|array $modules One or more modules to require
1261 * @param string $function The JS function to call
1262 * @param array $arguments An array of arguments to pass to the function
1263 * @param string $galleryversion The YUI gallery version of any modules required
1264 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1266 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1268 $js->modules
= (array)$modules;
1269 $js->function = $function;
1270 $js->arguments
= $arguments;
1271 $js->galleryversion
= $galleryversion;
1272 $js->ondomready
= $ondomready;
1273 $this->jsyuimodules
[] = $js;
1277 * Adds a JS initialisation call to the page when the button is used.
1279 * @param string $function The function to call
1280 * @param array $extraarguments An array of arguments to pass to the function
1281 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1282 * @param array $module A module definition
1284 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1286 $js->function = $function;
1287 $js->extraarguments
= $extraarguments;
1288 $js->ondomready
= $ondomready;
1289 $js->module
= $module;
1290 $this->jsinitcalls
[] = $js;
1294 * Requires strings for JS that will be loaded when the button is used.
1296 * @param type $identifiers
1297 * @param string $component
1300 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1301 $string = new stdClass
;
1302 $string->identifiers
= (array)$identifiers;
1303 $string->component
= $component;
1305 $this->jsstrings
[] = $string;
1309 * Initialises the JS that is required by this button
1311 * @param moodle_page $page
1313 public function initialise_js(moodle_page
$page) {
1314 foreach ($this->jsyuimodules
as $js) {
1315 $page->requires
->yui_module($js->modules
, $js->function, $js->arguments
, $js->galleryversion
, $js->ondomready
);
1317 foreach ($this->jsinitcalls
as $js) {
1318 $page->requires
->js_init_call($js->function, $js->extraarguments
, $js->ondomready
, $js->module
);
1320 foreach ($this->jsstrings
as $string) {
1321 $page->requires
->strings_for_js($string->identifiers
, $string->component
, $string->a
);
1327 * User enrolment action
1329 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1332 * @copyright 2011 Sam Hemelryk
1333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1335 class user_enrolment_action
implements renderable
{
1338 * The icon to display for the action
1344 * The title for the action
1350 * The URL to the action
1356 * An array of HTML attributes
1359 protected $attributes = array();
1363 * @param pix_icon $icon
1364 * @param string $title
1365 * @param moodle_url $url
1366 * @param array $attributes
1368 public function __construct(pix_icon
$icon, $title, $url, array $attributes = null) {
1369 $this->icon
= $icon;
1370 $this->title
= $title;
1371 $this->url
= new moodle_url($url);
1372 if (!empty($attributes)) {
1373 $this->attributes
= $attributes;
1375 $this->attributes
['title'] = $title;
1379 * Returns the icon for this action
1382 public function get_icon() {
1387 * Returns the title for this action
1390 public function get_title() {
1391 return $this->title
;
1395 * Returns the URL for this action
1396 * @return moodle_url
1398 public function get_url() {
1403 * Returns the attributes to use for this action
1406 public function get_attributes() {
1407 return $this->attributes
;
1411 class enrol_ajax_exception
extends moodle_exception
{
1414 * @param string $errorcode The name of the string from error.php to print
1415 * @param string $module name of module
1416 * @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.
1417 * @param object $a Extra words and phrases that might be required in the error string
1418 * @param string $debuginfo optional debugging information
1420 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1421 parent
::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1426 * This class is used to manage a bulk operations for enrolment plugins.
1428 * @copyright 2011 Sam Hemelryk
1429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1431 abstract class enrol_bulk_enrolment_operation
{
1434 * The course enrolment manager
1435 * @var course_enrolment_manager
1440 * The enrolment plugin to which this operation belongs
1447 * @param course_enrolment_manager $manager
1448 * @param stdClass $plugin
1450 public function __construct(course_enrolment_manager
$manager, enrol_plugin
$plugin = null) {
1451 $this->manager
= $manager;
1452 $this->plugin
= $plugin;
1456 * Returns a moodleform used for this operation, or false if no form is required and the action
1457 * should be immediatly processed.
1459 * @param moodle_url|string $defaultaction
1460 * @param mixed $defaultcustomdata
1461 * @return enrol_bulk_enrolment_change_form|moodleform|false
1463 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1468 * Returns the title to use for this bulk operation
1472 abstract public function get_title();
1475 * Returns the identifier for this bulk operation.
1476 * This should be the same identifier used by the plugins function when returning
1477 * all of its bulk operations.
1481 abstract public function get_identifier();
1484 * Processes the bulk operation on the given users
1486 * @param course_enrolment_manager $manager
1487 * @param array $users
1488 * @param stdClass $properties
1490 abstract public function process(course_enrolment_manager
$manager, array $users, stdClass
$properties);