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 if ($this->groupfilter
) {
176 $sqltotal .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
177 ON (u.id = gm.userid AND g.courseid = e.courseid)";
179 $sqltotal .= "WHERE $filtersql";
180 $this->totalusers
= (int)$DB->count_records_sql($sqltotal, $params);
182 return $this->totalusers
;
186 * Returns the total number of enrolled users in the course.
188 * If a filter was specificed this will be the total number of users enrolled
189 * in this course by means of that instance.
191 * @global moodle_database $DB
194 public function get_total_other_users() {
196 if ($this->totalotherusers
=== null) {
197 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
198 $params['courseid'] = $this->course
->id
;
199 $sql = "SELECT COUNT(DISTINCT u.id)
200 FROM {role_assignments} ra
201 JOIN {user} u ON u.id = ra.userid
202 JOIN {context} ctx ON ra.contextid = ctx.id
204 SELECT ue.id, ue.userid
205 FROM {user_enrolments} ue
206 LEFT JOIN {enrol} e ON e.id=ue.enrolid
207 WHERE e.courseid = :courseid
208 ) ue ON ue.userid=u.id
209 WHERE ctx.id $ctxcondition AND
211 $this->totalotherusers
= (int)$DB->count_records_sql($sql, $params);
213 return $this->totalotherusers
;
217 * Gets all of the users enrolled in this course.
219 * If a filter was specified this will be the users who were enrolled
220 * in this course by means of that instance. If role or search filters were
221 * specified then these will also be applied.
223 * @global moodle_database $DB
224 * @param string $sort
225 * @param string $direction ASC or DESC
226 * @param int $page First page should be 0
227 * @param int $perpage Defaults to 25
230 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
232 if ($direction !== 'ASC') {
235 $key = md5("$sort-$direction-$page-$perpage");
236 if (!array_key_exists($key, $this->users
)) {
237 list($instancessql, $params, $filter) = $this->get_instance_sql();
238 list($filtersql, $moreparams) = $this->get_filter_sql();
239 $params +
= $moreparams;
240 $extrafields = get_extra_user_fields($this->get_context());
241 $extrafields[] = 'lastaccess';
242 $ufields = user_picture
::fields('u', $extrafields);
243 $sql = "SELECT DISTINCT $ufields, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
245 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
246 JOIN {enrol} e ON (e.id = ue.enrolid)
247 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
248 if ($this->groupfilter
) {
249 $sql .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
250 ON (u.id = gm.userid AND g.courseid = e.courseid)";
252 $sql .= "WHERE $filtersql
253 ORDER BY $sort $direction";
254 $this->users
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
256 return $this->users
[$key];
260 * Obtains WHERE clause to filter results by defined search and role filter
261 * (instance filter is handled separately in JOIN clause, see
264 * @return array Two-element array with SQL and params for WHERE clause
266 protected function get_filter_sql() {
270 $extrafields = get_extra_user_fields($this->get_context());
271 list($sql, $params) = users_search_sql($this->searchfilter
, 'u', true, $extrafields);
274 if ($this->rolefilter
) {
276 $contextids = $this->context
->get_parent_context_ids();
277 $contextids[] = $this->context
->id
;
278 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
);
279 $params +
= $contextparams;
281 // Role check condition.
282 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
283 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
284 $params['roleid'] = $this->rolefilter
;
288 if ($this->groupfilter
) {
289 if ($this->groupfilter
< 0) {
290 // Show users who are not in any group.
291 $sql .= " AND gm.groupid IS NULL";
293 $sql .= " AND gm.groupid = :groupid";
294 $params['groupid'] = $this->groupfilter
;
299 if ($this->statusfilter
=== ENROL_USER_ACTIVE
) {
300 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
301 AND (ue.timeend = 0 OR ue.timeend > :now2)";
302 $now = round(time(), -2); // rounding helps caching in DB
303 $params +
= array('enabled' => ENROL_INSTANCE_ENABLED
,
304 'active' => ENROL_USER_ACTIVE
,
307 } else if ($this->statusfilter
=== ENROL_USER_SUSPENDED
) {
308 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
309 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
310 $now = round(time(), -2); // rounding helps caching in DB
311 $params +
= array('disabled' => ENROL_INSTANCE_DISABLED
,
312 'inactive' => ENROL_USER_SUSPENDED
,
317 return array($sql, $params);
321 * Gets and array of other users.
323 * Other users are users who have been assigned roles or inherited roles
324 * within this course but who have not been enrolled in the course
326 * @global moodle_database $DB
327 * @param string $sort
328 * @param string $direction
330 * @param int $perpage
333 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
335 if ($direction !== 'ASC') {
338 $key = md5("$sort-$direction-$page-$perpage");
339 if (!array_key_exists($key, $this->otherusers
)) {
340 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
341 $params['courseid'] = $this->course
->id
;
342 $params['cid'] = $this->course
->id
;
343 $extrafields = get_extra_user_fields($this->get_context());
344 $ufields = user_picture
::fields('u', $extrafields);
345 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, $ufields,
346 coalesce(u.lastaccess,0) AS lastaccess
347 FROM {role_assignments} ra
348 JOIN {user} u ON u.id = ra.userid
349 JOIN {context} ctx ON ra.contextid = ctx.id
351 SELECT ue.id, ue.userid
352 FROM {user_enrolments} ue
353 JOIN {enrol} e ON e.id = ue.enrolid
354 WHERE e.courseid = :courseid
355 ) ue ON ue.userid=u.id
356 WHERE ctx.id $ctxcondition AND
358 ORDER BY $sort $direction, ctx.depth DESC";
359 $this->otherusers
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
361 return $this->otherusers
[$key];
365 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
367 * @param string $search the search term, if any.
368 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
369 * @return array with three elements:
370 * string list of fields to SELECT,
371 * string contents of SQL WHERE clause,
372 * array query params. Note that the SQL snippets use named parameters.
374 protected function get_basic_search_conditions($search, $searchanywhere) {
377 // Add some additional sensible conditions
378 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
379 $params = array('guestid' => $CFG->siteguest
);
380 if (!empty($search)) {
381 $conditions = get_extra_user_fields($this->get_context());
382 $conditions[] = 'u.firstname';
383 $conditions[] = 'u.lastname';
384 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
385 if ($searchanywhere) {
386 $searchparam = '%' . $search . '%';
388 $searchparam = $search . '%';
391 foreach ($conditions as $key => $condition) {
392 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
393 $params["con{$i}00"] = $searchparam;
396 $tests[] = '(' . implode(' OR ', $conditions) . ')';
398 $wherecondition = implode(' AND ', $tests);
400 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
401 $extrafields[] = 'username';
402 $extrafields[] = 'lastaccess';
403 $ufields = user_picture
::fields('u', $extrafields);
405 return array($ufields, $params, $wherecondition);
409 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
411 * @param string $search the search string, if any.
412 * @param string $fields the first bit of the SQL when returning some users.
413 * @param string $countfields fhe first bit of the SQL when counting the users.
414 * @param string $sql the bulk of the SQL statement.
415 * @param array $params query parameters.
416 * @param int $page which page number of the results to show.
417 * @param int $perpage number of users per page.
418 * @param int $addedenrollment number of users added to enrollment.
419 * @return array with two elememts:
420 * int total number of users matching the search.
421 * array of user objects returned by the query.
423 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
426 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
427 $order = ' ORDER BY ' . $sort;
429 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
430 $availableusers = $DB->get_records_sql($fields . $sql . $order,
431 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
433 return array('totalusers' => $totalusers, 'users' => $availableusers);
437 * Gets an array of the users that can be enrolled in this course.
439 * @global moodle_database $DB
440 * @param int $enrolid
441 * @param string $search
442 * @param bool $searchanywhere
443 * @param int $page Defaults to 0
444 * @param int $perpage Defaults to 25
445 * @param int $addedenrollment Defaults to 0
446 * @return array Array(totalusers => int, users => array)
448 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
451 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
453 $fields = 'SELECT '.$ufields;
454 $countfields = 'SELECT COUNT(1)';
455 $sql = " FROM {user} u
456 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
457 WHERE $wherecondition
459 $params['enrolid'] = $enrolid;
461 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
465 * Searches other users and returns paginated results
467 * @global moodle_database $DB
468 * @param string $search
469 * @param bool $searchanywhere
470 * @param int $page Starting at 0
471 * @param int $perpage
474 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
477 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
479 $fields = 'SELECT ' . $ufields;
480 $countfields = 'SELECT COUNT(u.id)';
481 $sql = " FROM {user} u
482 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
483 WHERE $wherecondition
485 $params['contextid'] = $this->context
->id
;
487 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
491 * Gets an array containing some SQL to user for when selecting, params for
492 * that SQL, and the filter that was used in constructing the sql.
494 * @global moodle_database $DB
497 protected function get_instance_sql() {
499 if ($this->_instancessql
=== null) {
500 $instances = $this->get_enrolment_instances();
501 $filter = $this->get_enrolment_filter();
502 if ($filter && array_key_exists($filter, $instances)) {
503 $sql = " = :ifilter";
504 $params = array('ifilter'=>$filter);
508 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED
);
510 // no enabled instances, oops, we should probably say something
512 $params = array('never'=>-1);
515 $this->instancefilter
= $filter;
516 $this->_instancessql
= array($sql, $params, $filter);
518 return $this->_instancessql
;
522 * Returns all of the enrolment instances for this course.
524 * NOTE: since 2.4 it includes instances of disabled plugins too.
528 public function get_enrolment_instances() {
529 if ($this->_instances
=== null) {
530 $this->_instances
= enrol_get_instances($this->course
->id
, false);
532 return $this->_instances
;
536 * Returns the names for all of the enrolment instances for this course.
538 * NOTE: since 2.4 it includes instances of disabled plugins too.
542 public function get_enrolment_instance_names() {
543 if ($this->_inames
=== null) {
544 $instances = $this->get_enrolment_instances();
545 $plugins = $this->get_enrolment_plugins(false);
546 foreach ($instances as $key=>$instance) {
547 if (!isset($plugins[$instance->enrol
])) {
548 // weird, some broken stuff in plugin
549 unset($instances[$key]);
552 $this->_inames
[$key] = $plugins[$instance->enrol
]->get_instance_name($instance);
555 return $this->_inames
;
559 * Gets all of the enrolment plugins that are active for this course.
561 * @param bool $onlyenabled return only enabled enrol plugins
564 public function get_enrolment_plugins($onlyenabled = true) {
565 if ($this->_plugins
=== null) {
566 $this->_plugins
= enrol_get_plugins(true);
570 return $this->_plugins
;
573 if ($this->_allplugins
=== null) {
574 // Make sure we have the same objects in _allplugins and _plugins.
575 $this->_allplugins
= $this->_plugins
;
576 foreach (enrol_get_plugins(false) as $name=>$plugin) {
577 if (!isset($this->_allplugins
[$name])) {
578 $this->_allplugins
[$name] = $plugin;
583 return $this->_allplugins
;
587 * Gets all of the roles this course can contain.
591 public function get_all_roles() {
592 if ($this->_roles
=== null) {
593 $this->_roles
= role_fix_names(get_all_roles($this->context
), $this->context
);
595 return $this->_roles
;
599 * Gets all of the assignable roles for this course.
603 public function get_assignable_roles($otherusers = false) {
604 if ($this->_assignableroles
=== null) {
605 $this->_assignableroles
= get_assignable_roles($this->context
, ROLENAME_ALIAS
, false); // verifies unassign access control too
609 if (!is_array($this->_assignablerolesothers
)) {
610 $this->_assignablerolesothers
= array();
611 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context
, 'moodle/course:view');
612 foreach ($this->_assignableroles
as $roleid=>$role) {
613 if (isset($courseviewroles[$roleid])) {
614 $this->_assignablerolesothers
[$roleid] = $role;
618 return $this->_assignablerolesothers
;
620 return $this->_assignableroles
;
625 * Gets all of the assignable roles for this course, wrapped in an array to ensure
626 * role sort order is not lost during json deserialisation.
628 * @param boolean $otherusers whether to include the assignable roles for other users
631 public function get_assignable_roles_for_json($otherusers = false) {
632 $rolesarray = array();
633 $assignable = $this->get_assignable_roles($otherusers);
634 foreach ($assignable as $id => $role) {
635 $rolesarray[] = array('id' => $id, 'name' => $role);
641 * Gets all of the groups for this course.
645 public function get_all_groups() {
646 if ($this->_groups
=== null) {
647 $this->_groups
= groups_get_all_groups($this->course
->id
);
648 foreach ($this->_groups
as $gid=>$group) {
649 $this->_groups
[$gid]->name
= format_string($group->name
);
652 return $this->_groups
;
656 * Unenrols a user from the course given the users ue entry
658 * @global moodle_database $DB
659 * @param stdClass $ue
662 public function unenrol_user($ue) {
664 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
665 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context
)) {
666 $plugin->unenrol_user($instance, $ue->userid
);
673 * Given a user enrolment record this method returns the plugin and enrolment
674 * instance that relate to it.
676 * @param stdClass|int $userenrolment
677 * @return array array($instance, $plugin)
679 public function get_user_enrolment_components($userenrolment) {
681 if (is_numeric($userenrolment)) {
682 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
684 $instances = $this->get_enrolment_instances();
685 $plugins = $this->get_enrolment_plugins(false);
686 if (!$userenrolment ||
!isset($instances[$userenrolment->enrolid
])) {
687 return array(false, false);
689 $instance = $instances[$userenrolment->enrolid
];
690 $plugin = $plugins[$instance->enrol
];
691 return array($instance, $plugin);
695 * Removes an assigned role from a user.
697 * @global moodle_database $DB
702 public function unassign_role_from_user($userid, $roleid) {
704 // Admins may unassign any role, others only those they could assign.
705 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
706 if (defined('AJAX_SCRIPT')) {
707 throw new moodle_exception('invalidrole');
711 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
712 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context
->id
, 'userid'=>$user->id
, 'roleid'=>$roleid));
713 foreach ($ras as $ra) {
714 if ($ra->component
) {
715 if (strpos($ra->component
, 'enrol_') !== 0) {
718 if (!$plugin = enrol_get_plugin(substr($ra->component
, 6))) {
721 if ($plugin->roles_protected()) {
725 role_unassign($ra->roleid
, $ra->userid
, $ra->contextid
, $ra->component
, $ra->itemid
);
731 * Assigns a role to a user.
737 public function assign_role_to_user($roleid, $userid) {
738 require_capability('moodle/role:assign', $this->context
);
739 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
740 if (defined('AJAX_SCRIPT')) {
741 throw new moodle_exception('invalidrole');
745 return role_assign($roleid, $userid, $this->context
->id
, '', NULL);
749 * Adds a user to a group
751 * @param stdClass $user
752 * @param int $groupid
755 public function add_user_to_group($user, $groupid) {
756 require_capability('moodle/course:managegroups', $this->context
);
757 $group = $this->get_group($groupid);
761 return groups_add_member($group->id
, $user->id
);
765 * Removes a user from a group
767 * @global moodle_database $DB
768 * @param StdClass $user
769 * @param int $groupid
772 public function remove_user_from_group($user, $groupid) {
774 require_capability('moodle/course:managegroups', $this->context
);
775 $group = $this->get_group($groupid);
776 if (!groups_remove_member_allowed($group, $user)) {
782 return groups_remove_member($group, $user);
786 * Gets the requested group
788 * @param int $groupid
789 * @return stdClass|int
791 public function get_group($groupid) {
792 $groups = $this->get_all_groups();
793 if (!array_key_exists($groupid, $groups)) {
796 return $groups[$groupid];
802 * @param stdClass $userenrolment
803 * @param stdClass $data
806 public function edit_enrolment($userenrolment, $data) {
807 //Only allow editing if the user has the appropriate capability
808 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
809 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
810 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context
)) {
811 if (!isset($data->status
)) {
812 $data->status
= $userenrolment->status
;
814 $plugin->update_user_enrol($instance, $userenrolment->userid
, $data->status
, $data->timestart
, $data->timeend
);
821 * Returns the current enrolment filter that is being applied by this class
824 public function get_enrolment_filter() {
825 return $this->instancefilter
;
829 * Gets the roles assigned to this user that are applicable for this course.
834 public function get_user_roles($userid) {
836 $ras = get_user_roles($this->context
, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
837 $plugins = $this->get_enrolment_plugins(false);
838 foreach ($ras as $ra) {
839 if ($ra->contextid
!= $this->context
->id
) {
840 if (!array_key_exists($ra->roleid
, $roles)) {
841 $roles[$ra->roleid
] = null;
843 // higher ras, course always takes precedence
846 if (array_key_exists($ra->roleid
, $roles) && $roles[$ra->roleid
] === false) {
850 if ($ra->component
) {
852 if (strpos($ra->component
, 'enrol_') === 0) {
853 $plugin = substr($ra->component
, 6);
854 if (isset($plugins[$plugin])) {
855 $changeable = !$plugins[$plugin]->roles_protected();
860 $roles[$ra->roleid
] = $changeable;
866 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
868 * @global moodle_database $DB
872 public function get_user_enrolments($userid) {
874 list($instancessql, $params, $filter) = $this->get_instance_sql();
875 $params['userid'] = $userid;
876 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
877 $instances = $this->get_enrolment_instances();
878 $plugins = $this->get_enrolment_plugins(false);
879 $inames = $this->get_enrolment_instance_names();
880 foreach ($userenrolments as &$ue) {
881 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
882 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
883 $ue->enrolmentinstancename
= $inames[$ue->enrolmentinstance
->id
];
885 return $userenrolments;
889 * Gets the groups this user belongs to
894 public function get_user_groups($userid) {
895 return groups_get_all_groups($this->course
->id
, $userid, 0, 'g.id');
899 * Retursn an array of params that would go into the URL to return to this
904 public function get_url_params() {
906 'id' => $this->course
->id
908 if (!empty($this->instancefilter
)) {
909 $args['ifilter'] = $this->instancefilter
;
911 if (!empty($this->rolefilter
)) {
912 $args['role'] = $this->rolefilter
;
914 if ($this->searchfilter
!== '') {
915 $args['search'] = $this->searchfilter
;
917 if (!empty($this->groupfilter
)) {
918 $args['filtergroup'] = $this->groupfilter
;
920 if ($this->statusfilter
!== -1) {
921 $args['status'] = $this->statusfilter
;
927 * Returns the course this object is managing enrolments for
931 public function get_course() {
932 return $this->course
;
936 * Returns the course context
940 public function get_context() {
941 return $this->context
;
945 * Gets an array of other users in this course ready for display.
947 * Other users are users who have been assigned or inherited roles within this
948 * course but have not been enrolled.
950 * @param core_enrol_renderer $renderer
951 * @param moodle_url $pageurl
952 * @param string $sort
953 * @param string $direction ASC | DESC
954 * @param int $page Starting from 0
955 * @param int $perpage
958 public function get_other_users_for_display(core_enrol_renderer
$renderer, moodle_url
$pageurl, $sort, $direction, $page, $perpage) {
960 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
961 $roles = $this->get_all_roles();
962 $plugins = $this->get_enrolment_plugins(false);
964 $context = $this->get_context();
966 $extrafields = get_extra_user_fields($context);
969 foreach ($userroles as $userrole) {
970 $contextid = $userrole->contextid
;
971 unset($userrole->contextid
); // This would collide with user avatar.
972 if (!array_key_exists($userrole->id
, $users)) {
973 $users[$userrole->id
] = $this->prepare_user_for_display($userrole, $extrafields, $now);
976 $a->role
= $roles[$userrole->roleid
]->localname
;
977 if ($contextid == $this->context
->id
) {
979 if ($userrole->component
) {
981 if (strpos($userrole->component
, 'enrol_') === 0) {
982 $plugin = substr($userrole->component
, 6);
983 if (isset($plugins[$plugin])) {
984 $changeable = !$plugins[$plugin]->roles_protected();
988 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
991 switch ($userrole->contextlevel
) {
992 case CONTEXT_COURSE
:
994 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
996 case CONTEXT_COURSECAT
:
997 $roletext = get_string('rolefromcategory', 'enrol', $a);
1001 $roletext = get_string('rolefromsystem', 'enrol', $a);
1005 if (!isset($users[$userrole->id
]['roles'])) {
1006 $users[$userrole->id
]['roles'] = array();
1008 $users[$userrole->id
]['roles'][$userrole->roleid
] = array(
1009 'text' => $roletext,
1010 'unchangeable' => !$changeable
1017 * Gets an array of users for display, this includes minimal user information
1018 * as well as minimal information on the users roles, groups, and enrolments.
1020 * @param core_enrol_renderer $renderer
1021 * @param moodle_url $pageurl
1023 * @param string $direction ASC or DESC
1025 * @param int $perpage
1028 public function get_users_for_display(course_enrolment_manager
$manager, $sort, $direction, $page, $perpage) {
1029 $pageurl = $manager->get_moodlepage()->url
;
1030 $users = $this->get_users($sort, $direction, $page, $perpage);
1033 $straddgroup = get_string('addgroup', 'group');
1034 $strunenrol = get_string('unenrol', 'enrol');
1035 $stredit = get_string('edit');
1037 $allroles = $this->get_all_roles();
1038 $assignable = $this->get_assignable_roles();
1039 $allgroups = $this->get_all_groups();
1040 $context = $this->get_context();
1041 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1043 $url = new moodle_url($pageurl, $this->get_url_params());
1044 $extrafields = get_extra_user_fields($context);
1046 $enabledplugins = $this->get_enrolment_plugins(true);
1048 $userdetails = array();
1049 foreach ($users as $user) {
1050 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1053 $details['roles'] = array();
1054 foreach ($this->get_user_roles($user->id
) as $rid=>$rassignable) {
1055 $unchangeable = !$rassignable;
1056 if (!is_siteadmin() and !isset($assignable[$rid])) {
1057 $unchangeable = true;
1059 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname
, 'unchangeable'=>$unchangeable);
1063 $usergroups = $this->get_user_groups($user->id
);
1064 $details['groups'] = array();
1065 foreach($usergroups as $gid=>$unused) {
1066 $details['groups'][$gid] = $allgroups[$gid]->name
;
1070 $details['enrolments'] = array();
1071 foreach ($this->get_user_enrolments($user->id
) as $ue) {
1072 if (!isset($enabledplugins[$ue->enrolmentinstance
->enrol
])) {
1073 $details['enrolments'][$ue->id
] = array(
1074 'text' => $ue->enrolmentinstancename
,
1077 'actions' => array()
1080 } else if ($ue->timestart
and $ue->timeend
) {
1081 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart
), 'end'=>userdate($ue->timeend
)));
1082 $periodoutside = ($ue->timestart
&& $ue->timeend
&& ($now < $ue->timestart ||
$now > $ue->timeend
));
1083 } else if ($ue->timestart
) {
1084 $period = get_string('periodstart', 'enrol', userdate($ue->timestart
));
1085 $periodoutside = ($ue->timestart
&& $now < $ue->timestart
);
1086 } else if ($ue->timeend
) {
1087 $period = get_string('periodend', 'enrol', userdate($ue->timeend
));
1088 $periodoutside = ($ue->timeend
&& $now > $ue->timeend
);
1090 // If there is no start or end show when user was enrolled.
1091 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated
));
1092 $periodoutside = false;
1094 $details['enrolments'][$ue->id
] = array(
1095 'text' => $ue->enrolmentinstancename
,
1096 'period' => $period,
1097 'dimmed' => ($periodoutside or $ue->status
!= ENROL_USER_ACTIVE
or $ue->enrolmentinstance
->status
!= ENROL_INSTANCE_ENABLED
),
1098 'actions' => $ue->enrolmentplugin
->get_user_enrolment_actions($manager, $ue)
1101 $userdetails[$user->id
] = $details;
1103 return $userdetails;
1107 * Prepare a user record for display
1109 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1110 * prepare user fields for display
1112 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1114 * @param object $user The user record
1115 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1116 * additional fields may be displayed
1117 * @param int $now The time used for lastaccess calculation
1118 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1119 * additional fields from $extrafields
1121 private function prepare_user_for_display($user, $extrafields, $now) {
1123 'userid' => $user->id
,
1124 'courseid' => $this->get_course()->id
,
1125 'picture' => new user_picture($user),
1126 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1127 'lastaccess' => get_string('never'),
1128 'lastcourseaccess' => get_string('never'),
1131 foreach ($extrafields as $field) {
1132 $details[$field] = $user->{$field};
1135 // Last time user has accessed the site.
1136 if (!empty($user->lastaccess
)) {
1137 $details['lastaccess'] = format_time($now - $user->lastaccess
);
1140 // Last time user has accessed the course.
1141 if (!empty($user->lastcourseaccess
)) {
1142 $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess
);
1147 public function get_manual_enrol_buttons() {
1148 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1150 foreach ($plugins as $plugin) {
1151 $newbutton = $plugin->get_manual_enrol_button($this);
1152 if (is_array($newbutton)) {
1153 $buttons +
= $newbutton;
1154 } else if ($newbutton instanceof enrol_user_button
) {
1155 $buttons[] = $newbutton;
1161 public function has_instance($enrolpluginname) {
1162 // Make sure manual enrolments instance exists
1163 foreach ($this->get_enrolment_instances() as $instance) {
1164 if ($instance->enrol
== $enrolpluginname) {
1172 * Returns the enrolment plugin that the course manager was being filtered to.
1174 * If no filter was being applied then this function returns false.
1176 * @return enrol_plugin
1178 public function get_filtered_enrolment_plugin() {
1179 $instances = $this->get_enrolment_instances();
1180 $plugins = $this->get_enrolment_plugins(false);
1182 if (empty($this->instancefilter
) ||
!array_key_exists($this->instancefilter
, $instances)) {
1186 $instance = $instances[$this->instancefilter
];
1187 return $plugins[$instance->enrol
];
1191 * Returns and array of users + enrolment details.
1193 * Given an array of user id's this function returns and array of user enrolments for those users
1194 * as well as enough user information to display the users name and picture for each enrolment.
1196 * @global moodle_database $DB
1197 * @param array $userids
1200 public function get_users_enrolments(array $userids) {
1203 $instances = $this->get_enrolment_instances();
1204 $plugins = $this->get_enrolment_plugins(false);
1206 if (!empty($this->instancefilter
)) {
1207 $instancesql = ' = :instanceid';
1208 $instanceparams = array('instanceid' => $this->instancefilter
);
1210 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED
, 'instanceid0000');
1213 $userfields = user_picture
::fields('u');
1214 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid0000');
1216 list($sort, $sortparams) = users_order_by_sql('u');
1218 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1219 FROM {user_enrolments} ue
1220 LEFT JOIN {user} u ON u.id = ue.userid
1221 WHERE ue.enrolid $instancesql AND
1225 $rs = $DB->get_recordset_sql($sql, $idparams +
$instanceparams +
$sortparams);
1227 foreach ($rs as $ue) {
1228 $user = user_picture
::unalias($ue);
1229 $ue->id
= $ue->ueid
;
1231 if (!array_key_exists($user->id
, $users)) {
1232 $user->enrolments
= array();
1233 $users[$user->id
] = $user;
1235 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
1236 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
1237 $users[$user->id
]->enrolments
[$ue->id
] = $ue;
1245 * A button that is used to enrol users in a course
1247 * @copyright 2010 Sam Hemelryk
1248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1250 class enrol_user_button
extends single_button
{
1253 * An array containing JS YUI modules required by this button
1256 protected $jsyuimodules = array();
1259 * An array containing JS initialisation calls required by this button
1262 protected $jsinitcalls = array();
1265 * An array strings required by JS for this button
1268 protected $jsstrings = array();
1271 * Initialises the new enrol_user_button
1273 * @staticvar int $count The number of enrol user buttons already created
1274 * @param moodle_url $url
1275 * @param string $label The text to display in the button
1276 * @param string $method Either post or get
1278 public function __construct(moodle_url
$url, $label, $method = 'post') {
1281 parent
::__construct($url, $label, $method);
1282 $this->class = 'singlebutton enrolusersbutton';
1283 $this->formid
= 'enrolusersbutton-'.$count;
1287 * Adds a YUI module call that will be added to the page when the button is used.
1289 * @param string|array $modules One or more modules to require
1290 * @param string $function The JS function to call
1291 * @param array $arguments An array of arguments to pass to the function
1292 * @param string $galleryversion Deprecated: The gallery version to use
1293 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1295 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1296 if ($galleryversion != null) {
1297 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER
);
1301 $js->modules
= (array)$modules;
1302 $js->function = $function;
1303 $js->arguments
= $arguments;
1304 $js->ondomready
= $ondomready;
1305 $this->jsyuimodules
[] = $js;
1309 * Adds a JS initialisation call to the page when the button is used.
1311 * @param string $function The function to call
1312 * @param array $extraarguments An array of arguments to pass to the function
1313 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1314 * @param array $module A module definition
1316 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1318 $js->function = $function;
1319 $js->extraarguments
= $extraarguments;
1320 $js->ondomready
= $ondomready;
1321 $js->module
= $module;
1322 $this->jsinitcalls
[] = $js;
1326 * Requires strings for JS that will be loaded when the button is used.
1328 * @param type $identifiers
1329 * @param string $component
1332 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1333 $string = new stdClass
;
1334 $string->identifiers
= (array)$identifiers;
1335 $string->component
= $component;
1337 $this->jsstrings
[] = $string;
1341 * Initialises the JS that is required by this button
1343 * @param moodle_page $page
1345 public function initialise_js(moodle_page
$page) {
1346 foreach ($this->jsyuimodules
as $js) {
1347 $page->requires
->yui_module($js->modules
, $js->function, $js->arguments
, null, $js->ondomready
);
1349 foreach ($this->jsinitcalls
as $js) {
1350 $page->requires
->js_init_call($js->function, $js->extraarguments
, $js->ondomready
, $js->module
);
1352 foreach ($this->jsstrings
as $string) {
1353 $page->requires
->strings_for_js($string->identifiers
, $string->component
, $string->a
);
1359 * User enrolment action
1361 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1364 * @copyright 2011 Sam Hemelryk
1365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1367 class user_enrolment_action
implements renderable
{
1370 * The icon to display for the action
1376 * The title for the action
1382 * The URL to the action
1388 * An array of HTML attributes
1391 protected $attributes = array();
1395 * @param pix_icon $icon
1396 * @param string $title
1397 * @param moodle_url $url
1398 * @param array $attributes
1400 public function __construct(pix_icon
$icon, $title, $url, array $attributes = null) {
1401 $this->icon
= $icon;
1402 $this->title
= $title;
1403 $this->url
= new moodle_url($url);
1404 if (!empty($attributes)) {
1405 $this->attributes
= $attributes;
1407 $this->attributes
['title'] = $title;
1411 * Returns the icon for this action
1414 public function get_icon() {
1419 * Returns the title for this action
1422 public function get_title() {
1423 return $this->title
;
1427 * Returns the URL for this action
1428 * @return moodle_url
1430 public function get_url() {
1435 * Returns the attributes to use for this action
1438 public function get_attributes() {
1439 return $this->attributes
;
1443 class enrol_ajax_exception
extends moodle_exception
{
1446 * @param string $errorcode The name of the string from error.php to print
1447 * @param string $module name of module
1448 * @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.
1449 * @param object $a Extra words and phrases that might be required in the error string
1450 * @param string $debuginfo optional debugging information
1452 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1453 parent
::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1458 * This class is used to manage a bulk operations for enrolment plugins.
1460 * @copyright 2011 Sam Hemelryk
1461 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1463 abstract class enrol_bulk_enrolment_operation
{
1466 * The course enrolment manager
1467 * @var course_enrolment_manager
1472 * The enrolment plugin to which this operation belongs
1479 * @param course_enrolment_manager $manager
1480 * @param stdClass $plugin
1482 public function __construct(course_enrolment_manager
$manager, enrol_plugin
$plugin = null) {
1483 $this->manager
= $manager;
1484 $this->plugin
= $plugin;
1488 * Returns a moodleform used for this operation, or false if no form is required and the action
1489 * should be immediatly processed.
1491 * @param moodle_url|string $defaultaction
1492 * @param mixed $defaultcustomdata
1493 * @return enrol_bulk_enrolment_change_form|moodleform|false
1495 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1500 * Returns the title to use for this bulk operation
1504 abstract public function get_title();
1507 * Returns the identifier for this bulk operation.
1508 * This should be the same identifier used by the plugins function when returning
1509 * all of its bulk operations.
1513 abstract public function get_identifier();
1516 * Processes the bulk operation on the given users
1518 * @param course_enrolment_manager $manager
1519 * @param array $users
1520 * @param stdClass $properties
1522 abstract public function process(course_enrolment_manager
$manager, array $users, stdClass
$properties);