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 ORDER BY u.$sort $direction";
248 $this->users
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
250 return $this->users
[$key];
254 * Obtains WHERE clause to filter results by defined search and role filter
255 * (instance filter is handled separately in JOIN clause, see
258 * @return array Two-element array with SQL and params for WHERE clause
260 protected function get_filter_sql() {
264 $extrafields = get_extra_user_fields($this->get_context());
265 list($sql, $params) = users_search_sql($this->searchfilter
, 'u', true, $extrafields);
268 if ($this->rolefilter
) {
270 $contextids = $this->context
->get_parent_context_ids();
271 $contextids[] = $this->context
->id
;
272 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
);
273 $params +
= $contextparams;
275 // Role check condition.
276 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
277 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
278 $params['roleid'] = $this->rolefilter
;
282 if ($this->groupfilter
) {
283 $sql .= " AND gm.groupid = :groupid";
284 $params['groupid'] = $this->groupfilter
;
288 if ($this->statusfilter
=== ENROL_USER_ACTIVE
) {
289 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
290 AND (ue.timeend = 0 OR ue.timeend > :now2)";
291 $now = round(time(), -2); // rounding helps caching in DB
292 $params +
= array('enabled' => ENROL_INSTANCE_ENABLED
,
293 'active' => ENROL_USER_ACTIVE
,
296 } else if ($this->statusfilter
=== ENROL_USER_SUSPENDED
) {
297 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
298 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
299 $now = round(time(), -2); // rounding helps caching in DB
300 $params +
= array('disabled' => ENROL_INSTANCE_DISABLED
,
301 'inactive' => ENROL_USER_SUSPENDED
,
306 return array($sql, $params);
310 * Gets and array of other users.
312 * Other users are users who have been assigned roles or inherited roles
313 * within this course but who have not been enrolled in the course
315 * @global moodle_database $DB
316 * @param string $sort
317 * @param string $direction
319 * @param int $perpage
322 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
324 if ($direction !== 'ASC') {
327 $key = md5("$sort-$direction-$page-$perpage");
328 if (!array_key_exists($key, $this->otherusers
)) {
329 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
330 $params['courseid'] = $this->course
->id
;
331 $params['cid'] = $this->course
->id
;
332 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
333 FROM {role_assignments} ra
334 JOIN {user} u ON u.id = ra.userid
335 JOIN {context} ctx ON ra.contextid = ctx.id
337 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
338 FROM {user_enrolments} ue
339 LEFT JOIN {enrol} e ON e.id=ue.enrolid
340 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
341 WHERE e.courseid = :courseid
342 ) ue ON ue.userid=u.id
343 WHERE ctx.id $ctxcondition AND
345 ORDER BY u.$sort $direction, ctx.depth DESC";
346 $this->otherusers
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
348 return $this->otherusers
[$key];
352 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
354 * @param string $search the search term, if any.
355 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
356 * @return array with three elements:
357 * string list of fields to SELECT,
358 * string contents of SQL WHERE clause,
359 * array query params. Note that the SQL snippets use named parameters.
361 protected function get_basic_search_conditions($search, $searchanywhere) {
364 // Add some additional sensible conditions
365 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
366 $params = array('guestid' => $CFG->siteguest
);
367 if (!empty($search)) {
368 $conditions = get_extra_user_fields($this->get_context());
369 $conditions[] = 'u.firstname';
370 $conditions[] = 'u.lastname';
371 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
372 if ($searchanywhere) {
373 $searchparam = '%' . $search . '%';
375 $searchparam = $search . '%';
378 foreach ($conditions as $key => $condition) {
379 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
380 $params["con{$i}00"] = $searchparam;
383 $tests[] = '(' . implode(' OR ', $conditions) . ')';
385 $wherecondition = implode(' AND ', $tests);
387 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
388 $extrafields[] = 'username';
389 $extrafields[] = 'lastaccess';
390 $ufields = user_picture
::fields('u', $extrafields);
392 return array($ufields, $params, $wherecondition);
396 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
398 * @param string $search the search string, if any.
399 * @param string $fields the first bit of the SQL when returning some users.
400 * @param string $countfields fhe first bit of the SQL when counting the users.
401 * @param string $sql the bulk of the SQL statement.
402 * @param array $params query parameters.
403 * @param int $page which page number of the results to show.
404 * @param int $perpage number of users per page.
405 * @param int $addedenrollment number of users added to enrollment.
406 * @return array with two elememts:
407 * int total number of users matching the search.
408 * array of user objects returned by the query.
410 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
413 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
414 $order = ' ORDER BY ' . $sort;
416 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
417 $availableusers = $DB->get_records_sql($fields . $sql . $order,
418 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
420 return array('totalusers' => $totalusers, 'users' => $availableusers);
424 * Gets an array of the users that can be enrolled in this course.
426 * @global moodle_database $DB
427 * @param int $enrolid
428 * @param string $search
429 * @param bool $searchanywhere
430 * @param int $page Defaults to 0
431 * @param int $perpage Defaults to 25
432 * @param int $addedenrollment Defaults to 0
433 * @return array Array(totalusers => int, users => array)
435 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
438 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
440 $fields = 'SELECT '.$ufields;
441 $countfields = 'SELECT COUNT(1)';
442 $sql = " FROM {user} u
443 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
444 WHERE $wherecondition
446 $params['enrolid'] = $enrolid;
448 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
452 * Searches other users and returns paginated results
454 * @global moodle_database $DB
455 * @param string $search
456 * @param bool $searchanywhere
457 * @param int $page Starting at 0
458 * @param int $perpage
461 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
464 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
466 $fields = 'SELECT ' . $ufields;
467 $countfields = 'SELECT COUNT(u.id)';
468 $sql = " FROM {user} u
469 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
470 WHERE $wherecondition
472 $params['contextid'] = $this->context
->id
;
474 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
478 * Gets an array containing some SQL to user for when selecting, params for
479 * that SQL, and the filter that was used in constructing the sql.
481 * @global moodle_database $DB
484 protected function get_instance_sql() {
486 if ($this->_instancessql
=== null) {
487 $instances = $this->get_enrolment_instances();
488 $filter = $this->get_enrolment_filter();
489 if ($filter && array_key_exists($filter, $instances)) {
490 $sql = " = :ifilter";
491 $params = array('ifilter'=>$filter);
495 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED
);
497 // no enabled instances, oops, we should probably say something
499 $params = array('never'=>-1);
502 $this->instancefilter
= $filter;
503 $this->_instancessql
= array($sql, $params, $filter);
505 return $this->_instancessql
;
509 * Returns all of the enrolment instances for this course.
511 * NOTE: since 2.4 it includes instances of disabled plugins too.
515 public function get_enrolment_instances() {
516 if ($this->_instances
=== null) {
517 $this->_instances
= enrol_get_instances($this->course
->id
, false);
519 return $this->_instances
;
523 * Returns the names for all of the enrolment instances for this course.
525 * NOTE: since 2.4 it includes instances of disabled plugins too.
529 public function get_enrolment_instance_names() {
530 if ($this->_inames
=== null) {
531 $instances = $this->get_enrolment_instances();
532 $plugins = $this->get_enrolment_plugins(false);
533 foreach ($instances as $key=>$instance) {
534 if (!isset($plugins[$instance->enrol
])) {
535 // weird, some broken stuff in plugin
536 unset($instances[$key]);
539 $this->_inames
[$key] = $plugins[$instance->enrol
]->get_instance_name($instance);
542 return $this->_inames
;
546 * Gets all of the enrolment plugins that are active for this course.
548 * @param bool $onlyenabled return only enabled enrol plugins
551 public function get_enrolment_plugins($onlyenabled = true) {
552 if ($this->_plugins
=== null) {
553 $this->_plugins
= enrol_get_plugins(true);
557 return $this->_plugins
;
560 if ($this->_allplugins
=== null) {
561 // Make sure we have the same objects in _allplugins and _plugins.
562 $this->_allplugins
= $this->_plugins
;
563 foreach (enrol_get_plugins(false) as $name=>$plugin) {
564 if (!isset($this->_allplugins
[$name])) {
565 $this->_allplugins
[$name] = $plugin;
570 return $this->_allplugins
;
574 * Gets all of the roles this course can contain.
578 public function get_all_roles() {
579 if ($this->_roles
=== null) {
580 $this->_roles
= role_fix_names(get_all_roles($this->context
), $this->context
);
582 return $this->_roles
;
586 * Gets all of the assignable roles for this course.
590 public function get_assignable_roles($otherusers = false) {
591 if ($this->_assignableroles
=== null) {
592 $this->_assignableroles
= get_assignable_roles($this->context
, ROLENAME_ALIAS
, false); // verifies unassign access control too
596 if (!is_array($this->_assignablerolesothers
)) {
597 $this->_assignablerolesothers
= array();
598 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context
, 'moodle/course:view');
599 foreach ($this->_assignableroles
as $roleid=>$role) {
600 if (isset($courseviewroles[$roleid])) {
601 $this->_assignablerolesothers
[$roleid] = $role;
605 return $this->_assignablerolesothers
;
607 return $this->_assignableroles
;
612 * Gets all of the groups for this course.
616 public function get_all_groups() {
617 if ($this->_groups
=== null) {
618 $this->_groups
= groups_get_all_groups($this->course
->id
);
619 foreach ($this->_groups
as $gid=>$group) {
620 $this->_groups
[$gid]->name
= format_string($group->name
);
623 return $this->_groups
;
627 * Unenrols a user from the course given the users ue entry
629 * @global moodle_database $DB
630 * @param stdClass $ue
633 public function unenrol_user($ue) {
635 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
636 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context
)) {
637 $plugin->unenrol_user($instance, $ue->userid
);
644 * Given a user enrolment record this method returns the plugin and enrolment
645 * instance that relate to it.
647 * @param stdClass|int $userenrolment
648 * @return array array($instance, $plugin)
650 public function get_user_enrolment_components($userenrolment) {
652 if (is_numeric($userenrolment)) {
653 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
655 $instances = $this->get_enrolment_instances();
656 $plugins = $this->get_enrolment_plugins(false);
657 if (!$userenrolment ||
!isset($instances[$userenrolment->enrolid
])) {
658 return array(false, false);
660 $instance = $instances[$userenrolment->enrolid
];
661 $plugin = $plugins[$instance->enrol
];
662 return array($instance, $plugin);
666 * Removes an assigned role from a user.
668 * @global moodle_database $DB
673 public function unassign_role_from_user($userid, $roleid) {
675 // Admins may unassign any role, others only those they could assign.
676 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
677 if (defined('AJAX_SCRIPT')) {
678 throw new moodle_exception('invalidrole');
682 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
683 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context
->id
, 'userid'=>$user->id
, 'roleid'=>$roleid));
684 foreach ($ras as $ra) {
685 if ($ra->component
) {
686 if (strpos($ra->component
, 'enrol_') !== 0) {
689 if (!$plugin = enrol_get_plugin(substr($ra->component
, 6))) {
692 if ($plugin->roles_protected()) {
696 role_unassign($ra->roleid
, $ra->userid
, $ra->contextid
, $ra->component
, $ra->itemid
);
702 * Assigns a role to a user.
708 public function assign_role_to_user($roleid, $userid) {
709 require_capability('moodle/role:assign', $this->context
);
710 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
711 if (defined('AJAX_SCRIPT')) {
712 throw new moodle_exception('invalidrole');
716 return role_assign($roleid, $userid, $this->context
->id
, '', NULL);
720 * Adds a user to a group
722 * @param stdClass $user
723 * @param int $groupid
726 public function add_user_to_group($user, $groupid) {
727 require_capability('moodle/course:managegroups', $this->context
);
728 $group = $this->get_group($groupid);
732 return groups_add_member($group->id
, $user->id
);
736 * Removes a user from a group
738 * @global moodle_database $DB
739 * @param StdClass $user
740 * @param int $groupid
743 public function remove_user_from_group($user, $groupid) {
745 require_capability('moodle/course:managegroups', $this->context
);
746 $group = $this->get_group($groupid);
747 if (!groups_remove_member_allowed($group, $user)) {
753 return groups_remove_member($group, $user);
757 * Gets the requested group
759 * @param int $groupid
760 * @return stdClass|int
762 public function get_group($groupid) {
763 $groups = $this->get_all_groups();
764 if (!array_key_exists($groupid, $groups)) {
767 return $groups[$groupid];
773 * @param stdClass $userenrolment
774 * @param stdClass $data
777 public function edit_enrolment($userenrolment, $data) {
778 //Only allow editing if the user has the appropriate capability
779 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
780 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
781 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context
)) {
782 if (!isset($data->status
)) {
783 $data->status
= $userenrolment->status
;
785 $plugin->update_user_enrol($instance, $userenrolment->userid
, $data->status
, $data->timestart
, $data->timeend
);
792 * Returns the current enrolment filter that is being applied by this class
795 public function get_enrolment_filter() {
796 return $this->instancefilter
;
800 * Gets the roles assigned to this user that are applicable for this course.
805 public function get_user_roles($userid) {
807 $ras = get_user_roles($this->context
, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
808 $plugins = $this->get_enrolment_plugins(false);
809 foreach ($ras as $ra) {
810 if ($ra->contextid
!= $this->context
->id
) {
811 if (!array_key_exists($ra->roleid
, $roles)) {
812 $roles[$ra->roleid
] = null;
814 // higher ras, course always takes precedence
817 if (array_key_exists($ra->roleid
, $roles) && $roles[$ra->roleid
] === false) {
821 if ($ra->component
) {
823 if (strpos($ra->component
, 'enrol_') === 0) {
824 $plugin = substr($ra->component
, 6);
825 if (isset($plugins[$plugin])) {
826 $changeable = !$plugins[$plugin]->roles_protected();
831 $roles[$ra->roleid
] = $changeable;
837 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
839 * @global moodle_database $DB
843 public function get_user_enrolments($userid) {
845 list($instancessql, $params, $filter) = $this->get_instance_sql();
846 $params['userid'] = $userid;
847 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
848 $instances = $this->get_enrolment_instances();
849 $plugins = $this->get_enrolment_plugins(false);
850 $inames = $this->get_enrolment_instance_names();
851 foreach ($userenrolments as &$ue) {
852 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
853 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
854 $ue->enrolmentinstancename
= $inames[$ue->enrolmentinstance
->id
];
856 return $userenrolments;
860 * Gets the groups this user belongs to
865 public function get_user_groups($userid) {
866 return groups_get_all_groups($this->course
->id
, $userid, 0, 'g.id');
870 * Retursn an array of params that would go into the URL to return to this
875 public function get_url_params() {
877 'id' => $this->course
->id
879 if (!empty($this->instancefilter
)) {
880 $args['ifilter'] = $this->instancefilter
;
882 if (!empty($this->rolefilter
)) {
883 $args['role'] = $this->rolefilter
;
885 if ($this->searchfilter
!== '') {
886 $args['search'] = $this->searchfilter
;
888 if (!empty($this->groupfilter
)) {
889 $args['filtergroup'] = $this->groupfilter
;
891 if ($this->statusfilter
!== -1) {
892 $args['status'] = $this->statusfilter
;
898 * Returns the course this object is managing enrolments for
902 public function get_course() {
903 return $this->course
;
907 * Returns the course context
911 public function get_context() {
912 return $this->context
;
916 * Gets an array of other users in this course ready for display.
918 * Other users are users who have been assigned or inherited roles within this
919 * course but have not been enrolled.
921 * @param core_enrol_renderer $renderer
922 * @param moodle_url $pageurl
923 * @param string $sort
924 * @param string $direction ASC | DESC
925 * @param int $page Starting from 0
926 * @param int $perpage
929 public function get_other_users_for_display(core_enrol_renderer
$renderer, moodle_url
$pageurl, $sort, $direction, $page, $perpage) {
931 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
932 $roles = $this->get_all_roles();
933 $plugins = $this->get_enrolment_plugins(false);
935 $context = $this->get_context();
937 $extrafields = get_extra_user_fields($context);
940 foreach ($userroles as $userrole) {
941 $contextid = $userrole->contextid
;
942 unset($userrole->contextid
); // This would collide with user avatar.
943 if (!array_key_exists($userrole->id
, $users)) {
944 $users[$userrole->id
] = $this->prepare_user_for_display($userrole, $extrafields, $now);
947 $a->role
= $roles[$userrole->roleid
]->localname
;
948 if ($contextid == $this->context
->id
) {
950 if ($userrole->component
) {
952 if (strpos($userrole->component
, 'enrol_') === 0) {
953 $plugin = substr($userrole->component
, 6);
954 if (isset($plugins[$plugin])) {
955 $changeable = !$plugins[$plugin]->roles_protected();
959 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
962 switch ($userrole->contextlevel
) {
963 case CONTEXT_COURSE
:
965 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
967 case CONTEXT_COURSECAT
:
968 $roletext = get_string('rolefromcategory', 'enrol', $a);
972 $roletext = get_string('rolefromsystem', 'enrol', $a);
976 if (!isset($users[$userrole->id
]['roles'])) {
977 $users[$userrole->id
]['roles'] = array();
979 $users[$userrole->id
]['roles'][$userrole->roleid
] = array(
981 'unchangeable' => !$changeable
988 * Gets an array of users for display, this includes minimal user information
989 * as well as minimal information on the users roles, groups, and enrolments.
991 * @param core_enrol_renderer $renderer
992 * @param moodle_url $pageurl
994 * @param string $direction ASC or DESC
996 * @param int $perpage
999 public function get_users_for_display(course_enrolment_manager
$manager, $sort, $direction, $page, $perpage) {
1000 $pageurl = $manager->get_moodlepage()->url
;
1001 $users = $this->get_users($sort, $direction, $page, $perpage);
1004 $straddgroup = get_string('addgroup', 'group');
1005 $strunenrol = get_string('unenrol', 'enrol');
1006 $stredit = get_string('edit');
1008 $allroles = $this->get_all_roles();
1009 $assignable = $this->get_assignable_roles();
1010 $allgroups = $this->get_all_groups();
1011 $context = $this->get_context();
1012 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1014 $url = new moodle_url($pageurl, $this->get_url_params());
1015 $extrafields = get_extra_user_fields($context);
1017 $enabledplugins = $this->get_enrolment_plugins(true);
1019 $userdetails = array();
1020 foreach ($users as $user) {
1021 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1024 $details['roles'] = array();
1025 foreach ($this->get_user_roles($user->id
) as $rid=>$rassignable) {
1026 $unchangeable = !$rassignable;
1027 if (!is_siteadmin() and !isset($assignable[$rid])) {
1028 $unchangeable = true;
1030 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname
, 'unchangeable'=>$unchangeable);
1034 $usergroups = $this->get_user_groups($user->id
);
1035 $details['groups'] = array();
1036 foreach($usergroups as $gid=>$unused) {
1037 $details['groups'][$gid] = $allgroups[$gid]->name
;
1041 $details['enrolments'] = array();
1042 foreach ($this->get_user_enrolments($user->id
) as $ue) {
1043 if (!isset($enabledplugins[$ue->enrolmentinstance
->enrol
])) {
1044 $details['enrolments'][$ue->id
] = array(
1045 'text' => $ue->enrolmentinstancename
,
1048 'actions' => array()
1051 } else if ($ue->timestart
and $ue->timeend
) {
1052 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart
), 'end'=>userdate($ue->timeend
)));
1053 $periodoutside = ($ue->timestart
&& $ue->timeend
&& ($now < $ue->timestart ||
$now > $ue->timeend
));
1054 } else if ($ue->timestart
) {
1055 $period = get_string('periodstart', 'enrol', userdate($ue->timestart
));
1056 $periodoutside = ($ue->timestart
&& $now < $ue->timestart
);
1057 } else if ($ue->timeend
) {
1058 $period = get_string('periodend', 'enrol', userdate($ue->timeend
));
1059 $periodoutside = ($ue->timeend
&& $now > $ue->timeend
);
1061 // If there is no start or end show when user was enrolled.
1062 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated
));
1063 $periodoutside = false;
1065 $details['enrolments'][$ue->id
] = array(
1066 'text' => $ue->enrolmentinstancename
,
1067 'period' => $period,
1068 'dimmed' => ($periodoutside or $ue->status
!= ENROL_USER_ACTIVE
or $ue->enrolmentinstance
->status
!= ENROL_INSTANCE_ENABLED
),
1069 'actions' => $ue->enrolmentplugin
->get_user_enrolment_actions($manager, $ue)
1072 $userdetails[$user->id
] = $details;
1074 return $userdetails;
1078 * Prepare a user record for display
1080 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1081 * prepare user fields for display
1083 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1085 * @param object $user The user record
1086 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1087 * additional fields may be displayed
1088 * @param int $now The time used for lastaccess calculation
1089 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
1090 * additional fields from $extrafields
1092 private function prepare_user_for_display($user, $extrafields, $now) {
1094 'userid' => $user->id
,
1095 'courseid' => $this->get_course()->id
,
1096 'picture' => new user_picture($user),
1097 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1098 'lastseen' => get_string('never'),
1099 'lastcourseaccess' => get_string('never'),
1102 foreach ($extrafields as $field) {
1103 $details[$field] = $user->{$field};
1106 // Last time user has accessed the site.
1107 if ($user->lastaccess
) {
1108 $details['lastseen'] = format_time($now - $user->lastaccess
);
1111 // Last time user has accessed the course.
1112 if ($user->lastseen
) {
1113 $details['lastcourseaccess'] = format_time($now - $user->lastseen
);
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 Deprecated: The gallery version to use
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 = null, $ondomready = false) {
1267 if ($galleryversion != null) {
1268 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER
);
1272 $js->modules
= (array)$modules;
1273 $js->function = $function;
1274 $js->arguments
= $arguments;
1275 $js->ondomready
= $ondomready;
1276 $this->jsyuimodules
[] = $js;
1280 * Adds a JS initialisation call to the page when the button is used.
1282 * @param string $function The function to call
1283 * @param array $extraarguments An array of arguments to pass to the function
1284 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1285 * @param array $module A module definition
1287 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1289 $js->function = $function;
1290 $js->extraarguments
= $extraarguments;
1291 $js->ondomready
= $ondomready;
1292 $js->module
= $module;
1293 $this->jsinitcalls
[] = $js;
1297 * Requires strings for JS that will be loaded when the button is used.
1299 * @param type $identifiers
1300 * @param string $component
1303 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1304 $string = new stdClass
;
1305 $string->identifiers
= (array)$identifiers;
1306 $string->component
= $component;
1308 $this->jsstrings
[] = $string;
1312 * Initialises the JS that is required by this button
1314 * @param moodle_page $page
1316 public function initialise_js(moodle_page
$page) {
1317 foreach ($this->jsyuimodules
as $js) {
1318 $page->requires
->yui_module($js->modules
, $js->function, $js->arguments
, null, $js->ondomready
);
1320 foreach ($this->jsinitcalls
as $js) {
1321 $page->requires
->js_init_call($js->function, $js->extraarguments
, $js->ondomready
, $js->module
);
1323 foreach ($this->jsstrings
as $string) {
1324 $page->requires
->strings_for_js($string->identifiers
, $string->component
, $string->a
);
1330 * User enrolment action
1332 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1335 * @copyright 2011 Sam Hemelryk
1336 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1338 class user_enrolment_action
implements renderable
{
1341 * The icon to display for the action
1347 * The title for the action
1353 * The URL to the action
1359 * An array of HTML attributes
1362 protected $attributes = array();
1366 * @param pix_icon $icon
1367 * @param string $title
1368 * @param moodle_url $url
1369 * @param array $attributes
1371 public function __construct(pix_icon
$icon, $title, $url, array $attributes = null) {
1372 $this->icon
= $icon;
1373 $this->title
= $title;
1374 $this->url
= new moodle_url($url);
1375 if (!empty($attributes)) {
1376 $this->attributes
= $attributes;
1378 $this->attributes
['title'] = $title;
1382 * Returns the icon for this action
1385 public function get_icon() {
1390 * Returns the title for this action
1393 public function get_title() {
1394 return $this->title
;
1398 * Returns the URL for this action
1399 * @return moodle_url
1401 public function get_url() {
1406 * Returns the attributes to use for this action
1409 public function get_attributes() {
1410 return $this->attributes
;
1414 class enrol_ajax_exception
extends moodle_exception
{
1417 * @param string $errorcode The name of the string from error.php to print
1418 * @param string $module name of module
1419 * @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.
1420 * @param object $a Extra words and phrases that might be required in the error string
1421 * @param string $debuginfo optional debugging information
1423 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1424 parent
::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1429 * This class is used to manage a bulk operations for enrolment plugins.
1431 * @copyright 2011 Sam Hemelryk
1432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1434 abstract class enrol_bulk_enrolment_operation
{
1437 * The course enrolment manager
1438 * @var course_enrolment_manager
1443 * The enrolment plugin to which this operation belongs
1450 * @param course_enrolment_manager $manager
1451 * @param stdClass $plugin
1453 public function __construct(course_enrolment_manager
$manager, enrol_plugin
$plugin = null) {
1454 $this->manager
= $manager;
1455 $this->plugin
= $plugin;
1459 * Returns a moodleform used for this operation, or false if no form is required and the action
1460 * should be immediatly processed.
1462 * @param moodle_url|string $defaultaction
1463 * @param mixed $defaultcustomdata
1464 * @return enrol_bulk_enrolment_change_form|moodleform|false
1466 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1471 * Returns the title to use for this bulk operation
1475 abstract public function get_title();
1478 * Returns the identifier for this bulk operation.
1479 * This should be the same identifier used by the plugins function when returning
1480 * all of its bulk operations.
1484 abstract public function get_identifier();
1487 * Processes the bulk operation on the given users
1489 * @param course_enrolment_manager $manager
1490 * @param array $users
1491 * @param stdClass $properties
1493 abstract public function process(course_enrolment_manager
$manager, array $users, stdClass
$properties);