3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains the course_enrolment_manager class which is used to interface
20 * with the functions that exist in enrollib.php in relation to a single course.
24 * @copyright 2010 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') ||
die();
31 * This class provides a targeted tied together means of interfacing the enrolment
32 * tasks together with a course.
34 * It is provided as a convenience more than anything else.
36 * @copyright 2010 Sam Hemelryk
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class course_enrolment_manager
{
47 * The course we are managing enrolments for
50 protected $course = null;
52 * Limits the focus of the manager to one enrolment plugin instance
55 protected $instancefilter = null;
58 * The total number of users enrolled in the course
59 * Populated by course_enrolment_manager::get_total_users
62 protected $totalusers = null;
64 * An array of users currently enrolled in the course
65 * Populated by course_enrolment_manager::get_users
68 protected $users = array();
71 * An array of users who have roles within this course but who have not
72 * been enrolled in the course
75 protected $otherusers = array();
78 * The total number of users who hold a role within the course but who
82 protected $totalotherusers = null;
85 * The current moodle_page object
88 protected $moodlepage = null;
91 * These variables are used to cache the information this class uses
92 * please never use these directly instead use their get_ counterparts.
96 private $_instancessql = null;
97 private $_instances = null;
98 private $_inames = null;
99 private $_plugins = null;
100 private $_allplugins = null;
101 private $_roles = null;
102 private $_assignableroles = null;
103 private $_assignablerolesothers = null;
104 private $_groups = null;
108 * Constructs the course enrolment manager
110 * @param moodle_page $moodlepage
111 * @param stdClass $course
112 * @param string $instancefilter
114 public function __construct(moodle_page
$moodlepage, $course, $instancefilter = null) {
115 $this->moodlepage
= $moodlepage;
116 $this->context
= context_course
::instance($course->id
);
117 $this->course
= $course;
118 $this->instancefilter
= $instancefilter;
122 * Returns the current moodle page
123 * @return moodle_page
125 public function get_moodlepage() {
126 return $this->moodlepage
;
130 * Returns the total number of enrolled users in the course.
132 * If a filter was specificed this will be the total number of users enrolled
133 * in this course by means of that instance.
135 * @global moodle_database $DB
138 public function get_total_users() {
140 if ($this->totalusers
=== null) {
141 list($instancessql, $params, $filter) = $this->get_instance_sql();
142 $sqltotal = "SELECT COUNT(DISTINCT u.id)
144 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
145 JOIN {enrol} e ON (e.id = ue.enrolid)";
146 $this->totalusers
= (int)$DB->count_records_sql($sqltotal, $params);
148 return $this->totalusers
;
152 * Returns the total number of enrolled users in the course.
154 * If a filter was specificed this will be the total number of users enrolled
155 * in this course by means of that instance.
157 * @global moodle_database $DB
160 public function get_total_other_users() {
162 if ($this->totalotherusers
=== null) {
163 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context
, true), SQL_PARAMS_NAMED
, 'ctx');
164 $params['courseid'] = $this->course
->id
;
165 $sql = "SELECT COUNT(DISTINCT u.id)
166 FROM {role_assignments} ra
167 JOIN {user} u ON u.id = ra.userid
168 JOIN {context} ctx ON ra.contextid = ctx.id
170 SELECT ue.id, ue.userid
171 FROM {user_enrolments} ue
172 LEFT JOIN {enrol} e ON e.id=ue.enrolid
173 WHERE e.courseid = :courseid
174 ) ue ON ue.userid=u.id
175 WHERE ctx.id $ctxcondition AND
177 $this->totalotherusers
= (int)$DB->count_records_sql($sql, $params);
179 return $this->totalotherusers
;
183 * Gets all of the users enrolled in this course.
185 * If a filter was specified this will be the users who were enrolled
186 * in this course by means of that instance.
188 * @global moodle_database $DB
189 * @param string $sort
190 * @param string $direction ASC or DESC
191 * @param int $page First page should be 0
192 * @param int $perpage Defaults to 25
195 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
197 if ($direction !== 'ASC') {
200 $key = md5("$sort-$direction-$page-$perpage");
201 if (!array_key_exists($key, $this->users
)) {
202 list($instancessql, $params, $filter) = $this->get_instance_sql();
203 $extrafields = get_extra_user_fields($this->get_context());
204 $extrafields[] = 'lastaccess';
205 $ufields = user_picture
::fields('u', $extrafields);
206 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
208 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
209 JOIN {enrol} e ON (e.id = ue.enrolid)
210 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
211 if ($sort === 'firstname') {
212 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
213 } else if ($sort === 'lastname') {
214 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
215 } else if ($sort === 'email') {
216 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
217 } else if ($sort === 'lastseen') {
218 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
220 $this->users
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
222 return $this->users
[$key];
226 * Gets and array of other users.
228 * Other users are users who have been assigned roles or inherited roles
229 * within this course but who have not been enrolled in the course
231 * @global moodle_database $DB
232 * @param string $sort
233 * @param string $direction
235 * @param int $perpage
238 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
240 if ($direction !== 'ASC') {
243 $key = md5("$sort-$direction-$page-$perpage");
244 if (!array_key_exists($key, $this->otherusers
)) {
245 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context
, true), SQL_PARAMS_NAMED
, 'ctx');
246 $params['courseid'] = $this->course
->id
;
247 $params['cid'] = $this->course
->id
;
248 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
249 FROM {role_assignments} ra
250 JOIN {user} u ON u.id = ra.userid
251 JOIN {context} ctx ON ra.contextid = ctx.id
253 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
254 FROM {user_enrolments} ue
255 LEFT JOIN {enrol} e ON e.id=ue.enrolid
256 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
257 WHERE e.courseid = :courseid
258 ) ue ON ue.userid=u.id
259 WHERE ctx.id $ctxcondition AND
261 ORDER BY u.$sort $direction, ctx.depth DESC";
262 $this->otherusers
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
264 return $this->otherusers
[$key];
268 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
270 * @param string $search the search term, if any.
271 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
272 * @return array with three elements:
273 * string list of fields to SELECT,
274 * string contents of SQL WHERE clause,
275 * array query params. Note that the SQL snippets use named parameters.
277 protected function get_basic_search_conditions($search, $searchanywhere) {
280 // Add some additional sensible conditions
281 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
282 $params = array('guestid' => $CFG->siteguest
);
283 if (!empty($search)) {
284 $conditions = get_extra_user_fields($this->get_context());
285 $conditions[] = 'u.firstname';
286 $conditions[] = 'u.lastname';
287 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
288 if ($searchanywhere) {
289 $searchparam = '%' . $search . '%';
291 $searchparam = $search . '%';
294 foreach ($conditions as $key => $condition) {
295 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
296 $params["con{$i}00"] = $searchparam;
299 $tests[] = '(' . implode(' OR ', $conditions) . ')';
301 $wherecondition = implode(' AND ', $tests);
303 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
304 $extrafields[] = 'username';
305 $extrafields[] = 'lastaccess';
306 $ufields = user_picture
::fields('u', $extrafields);
308 return array($ufields, $params, $wherecondition);
312 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
314 * @param string $search the search string, if any.
315 * @param string $fields the first bit of the SQL when returning some users.
316 * @param string $countfields fhe first bit of the SQL when counting the users.
317 * @param string $sql the bulk of the SQL statement.
318 * @param array $params query parameters.
319 * @param int $page which page number of the results to show.
320 * @param int $perpage number of users per page.
321 * @return array with two elememts:
322 * int total number of users matching the search.
323 * array of user objects returned by the query.
325 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage) {
328 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
329 $order = ' ORDER BY ' . $sort;
331 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
332 $availableusers = $DB->get_records_sql($fields . $sql . $order,
333 array_merge($params, $sortparams), $page*$perpage, $perpage);
335 return array('totalusers' => $totalusers, 'users' => $availableusers);
339 * Gets an array of the users that can be enrolled in this course.
341 * @global moodle_database $DB
342 * @param int $enrolid
343 * @param string $search
344 * @param bool $searchanywhere
345 * @param int $page Defaults to 0
346 * @param int $perpage Defaults to 25
347 * @return array Array(totalusers => int, users => array)
349 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25) {
352 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
354 $fields = 'SELECT '.$ufields;
355 $countfields = 'SELECT COUNT(1)';
356 $sql = " FROM {user} u
357 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
358 WHERE $wherecondition
360 $params['enrolid'] = $enrolid;
362 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
366 * Searches other users and returns paginated results
368 * @global moodle_database $DB
369 * @param string $search
370 * @param bool $searchanywhere
371 * @param int $page Starting at 0
372 * @param int $perpage
375 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
378 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
380 $fields = 'SELECT ' . $ufields;
381 $countfields = 'SELECT COUNT(u.id)';
382 $sql = " FROM {user} u
383 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
384 WHERE $wherecondition
386 $params['contextid'] = $this->context
->id
;
388 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
392 * Gets an array containing some SQL to user for when selecting, params for
393 * that SQL, and the filter that was used in constructing the sql.
395 * @global moodle_database $DB
398 protected function get_instance_sql() {
400 if ($this->_instancessql
=== null) {
401 $instances = $this->get_enrolment_instances();
402 $filter = $this->get_enrolment_filter();
403 if ($filter && array_key_exists($filter, $instances)) {
404 $sql = " = :ifilter";
405 $params = array('ifilter'=>$filter);
409 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED
);
411 // no enabled instances, oops, we should probably say something
413 $params = array('never'=>-1);
416 $this->instancefilter
= $filter;
417 $this->_instancessql
= array($sql, $params, $filter);
419 return $this->_instancessql
;
423 * Returns all of the enrolment instances for this course.
425 * NOTE: since 2.4 it includes instances of disabled plugins too.
429 public function get_enrolment_instances() {
430 if ($this->_instances
=== null) {
431 $this->_instances
= enrol_get_instances($this->course
->id
, false);
433 return $this->_instances
;
437 * Returns the names for all of the enrolment instances for this course.
439 * NOTE: since 2.4 it includes instances of disabled plugins too.
443 public function get_enrolment_instance_names() {
444 if ($this->_inames
=== null) {
445 $instances = $this->get_enrolment_instances();
446 $plugins = $this->get_enrolment_plugins(false);
447 foreach ($instances as $key=>$instance) {
448 if (!isset($plugins[$instance->enrol
])) {
449 // weird, some broken stuff in plugin
450 unset($instances[$key]);
453 $this->_inames
[$key] = $plugins[$instance->enrol
]->get_instance_name($instance);
456 return $this->_inames
;
460 * Gets all of the enrolment plugins that are active for this course.
462 * @param bool $onlyenabled return only enabled enrol plugins
465 public function get_enrolment_plugins($onlyenabled = true) {
466 if ($this->_plugins
=== null) {
467 $this->_plugins
= enrol_get_plugins(true);
471 return $this->_plugins
;
474 if ($this->_allplugins
=== null) {
475 // Make sure we have the same objects in _allplugins and _plugins.
476 $this->_allplugins
= $this->_plugins
;
477 foreach (enrol_get_plugins(false) as $name=>$plugin) {
478 if (!isset($this->_allplugins
[$name])) {
479 $this->_allplugins
[$name] = $plugin;
484 return $this->_allplugins
;
488 * Gets all of the roles this course can contain.
492 public function get_all_roles() {
493 if ($this->_roles
=== null) {
494 $this->_roles
= role_fix_names(get_all_roles($this->context
), $this->context
);
496 return $this->_roles
;
500 * Gets all of the assignable roles for this course.
504 public function get_assignable_roles($otherusers = false) {
505 if ($this->_assignableroles
=== null) {
506 $this->_assignableroles
= get_assignable_roles($this->context
, ROLENAME_ALIAS
, false); // verifies unassign access control too
510 if (!is_array($this->_assignablerolesothers
)) {
511 $this->_assignablerolesothers
= array();
512 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context
, 'moodle/course:view');
513 foreach ($this->_assignableroles
as $roleid=>$role) {
514 if (isset($courseviewroles[$roleid])) {
515 $this->_assignablerolesothers
[$roleid] = $role;
519 return $this->_assignablerolesothers
;
521 return $this->_assignableroles
;
526 * Gets all of the groups for this course.
530 public function get_all_groups() {
531 if ($this->_groups
=== null) {
532 $this->_groups
= groups_get_all_groups($this->course
->id
);
533 foreach ($this->_groups
as $gid=>$group) {
534 $this->_groups
[$gid]->name
= format_string($group->name
);
537 return $this->_groups
;
541 * Unenrols a user from the course given the users ue entry
543 * @global moodle_database $DB
544 * @param stdClass $ue
547 public function unenrol_user($ue) {
549 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
550 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context
)) {
551 $plugin->unenrol_user($instance, $ue->userid
);
558 * Given a user enrolment record this method returns the plugin and enrolment
559 * instance that relate to it.
561 * @param stdClass|int $userenrolment
562 * @return array array($instance, $plugin)
564 public function get_user_enrolment_components($userenrolment) {
566 if (is_numeric($userenrolment)) {
567 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
569 $instances = $this->get_enrolment_instances();
570 $plugins = $this->get_enrolment_plugins(false);
571 if (!$userenrolment ||
!isset($instances[$userenrolment->enrolid
])) {
572 return array(false, false);
574 $instance = $instances[$userenrolment->enrolid
];
575 $plugin = $plugins[$instance->enrol
];
576 return array($instance, $plugin);
580 * Removes an assigned role from a user.
582 * @global moodle_database $DB
587 public function unassign_role_from_user($userid, $roleid) {
589 require_capability('moodle/role:assign', $this->context
);
590 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
592 role_unassign($roleid, $user->id
, $this->context
->id
, '', NULL);
593 } catch (Exception
$e) {
594 if (defined('AJAX_SCRIPT')) {
603 * Assigns a role to a user.
609 public function assign_role_to_user($roleid, $userid) {
610 require_capability('moodle/role:assign', $this->context
);
611 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
612 if (defined('AJAX_SCRIPT')) {
613 throw new moodle_exception('invalidrole');
617 return role_assign($roleid, $userid, $this->context
->id
, '', NULL);
621 * Adds a user to a group
623 * @param stdClass $user
624 * @param int $groupid
627 public function add_user_to_group($user, $groupid) {
628 require_capability('moodle/course:managegroups', $this->context
);
629 $group = $this->get_group($groupid);
633 return groups_add_member($group->id
, $user->id
);
637 * Removes a user from a group
639 * @global moodle_database $DB
640 * @param StdClass $user
641 * @param int $groupid
644 public function remove_user_from_group($user, $groupid) {
646 require_capability('moodle/course:managegroups', $this->context
);
647 $group = $this->get_group($groupid);
648 if (!groups_remove_member_allowed($group, $user)) {
654 return groups_remove_member($group, $user);
658 * Gets the requested group
660 * @param int $groupid
661 * @return stdClass|int
663 public function get_group($groupid) {
664 $groups = $this->get_all_groups();
665 if (!array_key_exists($groupid, $groups)) {
668 return $groups[$groupid];
674 * @param stdClass $userenrolment
675 * @param stdClass $data
678 public function edit_enrolment($userenrolment, $data) {
679 //Only allow editing if the user has the appropriate capability
680 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
681 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
682 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context
)) {
683 if (!isset($data->status
)) {
684 $data->status
= $userenrolment->status
;
686 $plugin->update_user_enrol($instance, $userenrolment->userid
, $data->status
, $data->timestart
, $data->timeend
);
693 * Returns the current enrolment filter that is being applied by this class
696 public function get_enrolment_filter() {
697 return $this->instancefilter
;
701 * Gets the roles assigned to this user that are applicable for this course.
706 public function get_user_roles($userid) {
708 $ras = get_user_roles($this->context
, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
709 foreach ($ras as $ra) {
710 if ($ra->contextid
!= $this->context
->id
) {
711 if (!array_key_exists($ra->roleid
, $roles)) {
712 $roles[$ra->roleid
] = null;
714 // higher ras, course always takes precedence
717 if (array_key_exists($ra->roleid
, $roles) && $roles[$ra->roleid
] === false) {
720 $roles[$ra->roleid
] = ($ra->itemid
== 0 and $ra->component
=== '');
726 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
728 * @global moodle_database $DB
732 public function get_user_enrolments($userid) {
734 list($instancessql, $params, $filter) = $this->get_instance_sql();
735 $params['userid'] = $userid;
736 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
737 $instances = $this->get_enrolment_instances();
738 $plugins = $this->get_enrolment_plugins(false);
739 $inames = $this->get_enrolment_instance_names();
740 foreach ($userenrolments as &$ue) {
741 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
742 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
743 $ue->enrolmentinstancename
= $inames[$ue->enrolmentinstance
->id
];
745 return $userenrolments;
749 * Gets the groups this user belongs to
754 public function get_user_groups($userid) {
755 return groups_get_all_groups($this->course
->id
, $userid, 0, 'g.id');
759 * Retursn an array of params that would go into the URL to return to this
764 public function get_url_params() {
766 'id' => $this->course
->id
768 if (!empty($this->instancefilter
)) {
769 $args['ifilter'] = $this->instancefilter
;
775 * Returns the course this object is managing enrolments for
779 public function get_course() {
780 return $this->course
;
784 * Returns the course context
788 public function get_context() {
789 return $this->context
;
793 * Gets an array of other users in this course ready for display.
795 * Other users are users who have been assigned or inherited roles within this
796 * course but have not been enrolled.
798 * @param core_enrol_renderer $renderer
799 * @param moodle_url $pageurl
800 * @param string $sort
801 * @param string $direction ASC | DESC
802 * @param int $page Starting from 0
803 * @param int $perpage
806 public function get_other_users_for_display(core_enrol_renderer
$renderer, moodle_url
$pageurl, $sort, $direction, $page, $perpage) {
808 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
809 $roles = $this->get_all_roles();
811 $context = $this->get_context();
813 $extrafields = get_extra_user_fields($context);
816 foreach ($userroles as $userrole) {
817 $contextid = $userrole->contextid
;
818 unset($userrole->contextid
); // This would collide with user avatar.
819 if (!array_key_exists($userrole->id
, $users)) {
820 $users[$userrole->id
] = $this->prepare_user_for_display($userrole, $extrafields, $now);
823 $a->role
= $roles[$userrole->roleid
]->localname
;
824 $changeable = ($userrole->component
== '');
825 if ($contextid == $this->context
->id
) {
826 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
829 switch ($userrole->contextlevel
) {
830 case CONTEXT_COURSE
:
832 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
834 case CONTEXT_COURSECAT
:
835 $roletext = get_string('rolefromcategory', 'enrol', $a);
839 $roletext = get_string('rolefromsystem', 'enrol', $a);
843 $users[$userrole->id
]['roles'] = array();
844 $users[$userrole->id
]['roles'][$userrole->roleid
] = array(
846 'unchangeable' => !$changeable
853 * Gets an array of users for display, this includes minimal user information
854 * as well as minimal information on the users roles, groups, and enrolments.
856 * @param core_enrol_renderer $renderer
857 * @param moodle_url $pageurl
859 * @param string $direction ASC or DESC
861 * @param int $perpage
864 public function get_users_for_display(course_enrolment_manager
$manager, $sort, $direction, $page, $perpage) {
865 $pageurl = $manager->get_moodlepage()->url
;
866 $users = $this->get_users($sort, $direction, $page, $perpage);
869 $straddgroup = get_string('addgroup', 'group');
870 $strunenrol = get_string('unenrol', 'enrol');
871 $stredit = get_string('edit');
873 $allroles = $this->get_all_roles();
874 $assignable = $this->get_assignable_roles();
875 $allgroups = $this->get_all_groups();
876 $context = $this->get_context();
877 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
879 $url = new moodle_url($pageurl, $this->get_url_params());
880 $extrafields = get_extra_user_fields($context);
882 $enabledplugins = $this->get_enrolment_plugins(true);
884 $userdetails = array();
885 foreach ($users as $user) {
886 $details = $this->prepare_user_for_display($user, $extrafields, $now);
889 $details['roles'] = array();
890 foreach ($this->get_user_roles($user->id
) as $rid=>$rassignable) {
891 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname
, 'unchangeable'=>(!$rassignable ||
!isset($assignable[$rid])));
895 $usergroups = $this->get_user_groups($user->id
);
896 $details['groups'] = array();
897 foreach($usergroups as $gid=>$unused) {
898 $details['groups'][$gid] = $allgroups[$gid]->name
;
902 $details['enrolments'] = array();
903 foreach ($this->get_user_enrolments($user->id
) as $ue) {
904 if (!isset($enabledplugins[$ue->enrolmentinstance
->enrol
])) {
905 $details['enrolments'][$ue->id
] = array(
906 'text' => $ue->enrolmentinstancename
,
912 } else if ($ue->timestart
and $ue->timeend
) {
913 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart
), 'end'=>userdate($ue->timeend
)));
914 $periodoutside = ($ue->timestart
&& $ue->timeend
&& $now < $ue->timestart
&& $now > $ue->timeend
);
915 } else if ($ue->timestart
) {
916 $period = get_string('periodstart', 'enrol', userdate($ue->timestart
));
917 $periodoutside = ($ue->timestart
&& $now < $ue->timestart
);
918 } else if ($ue->timeend
) {
919 $period = get_string('periodend', 'enrol', userdate($ue->timeend
));
920 $periodoutside = ($ue->timeend
&& $now > $ue->timeend
);
922 // If there is no start or end show when user was enrolled.
923 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated
));
924 $periodoutside = false;
926 $details['enrolments'][$ue->id
] = array(
927 'text' => $ue->enrolmentinstancename
,
929 'dimmed' => ($periodoutside ||
$ue->status
!= ENROL_USER_ACTIVE
),
930 'actions' => $ue->enrolmentplugin
->get_user_enrolment_actions($manager, $ue)
933 $userdetails[$user->id
] = $details;
939 * Prepare a user record for display
941 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
942 * prepare user fields for display
944 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
946 * @param object $user The user record
947 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
948 * additional fields may be displayed
949 * @param int $now The time used for lastaccess calculation
950 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
951 * additional fields from $extrafields
953 private function prepare_user_for_display($user, $extrafields, $now) {
955 'userid' => $user->id
,
956 'courseid' => $this->get_course()->id
,
957 'picture' => new user_picture($user),
958 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
959 'lastseen' => get_string('never'),
961 foreach ($extrafields as $field) {
962 $details[$field] = $user->{$field};
965 if ($user->lastaccess
) {
966 $details['lastseen'] = format_time($now - $user->lastaccess
);
971 public function get_manual_enrol_buttons() {
972 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
974 foreach ($plugins as $plugin) {
975 $newbutton = $plugin->get_manual_enrol_button($this);
976 if (is_array($newbutton)) {
977 $buttons +
= $newbutton;
978 } else if ($newbutton instanceof enrol_user_button
) {
979 $buttons[] = $newbutton;
985 public function has_instance($enrolpluginname) {
986 // Make sure manual enrolments instance exists
987 foreach ($this->get_enrolment_instances() as $instance) {
988 if ($instance->enrol
== $enrolpluginname) {
996 * Returns the enrolment plugin that the course manager was being filtered to.
998 * If no filter was being applied then this function returns false.
1000 * @return enrol_plugin
1002 public function get_filtered_enrolment_plugin() {
1003 $instances = $this->get_enrolment_instances();
1004 $plugins = $this->get_enrolment_plugins(false);
1006 if (empty($this->instancefilter
) ||
!array_key_exists($this->instancefilter
, $instances)) {
1010 $instance = $instances[$this->instancefilter
];
1011 return $plugins[$instance->enrol
];
1015 * Returns and array of users + enrolment details.
1017 * Given an array of user id's this function returns and array of user enrolments for those users
1018 * as well as enough user information to display the users name and picture for each enrolment.
1020 * @global moodle_database $DB
1021 * @param array $userids
1024 public function get_users_enrolments(array $userids) {
1027 $instances = $this->get_enrolment_instances();
1028 $plugins = $this->get_enrolment_plugins(false);
1030 if (!empty($this->instancefilter
)) {
1031 $instancesql = ' = :instanceid';
1032 $instanceparams = array('instanceid' => $this->instancefilter
);
1034 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED
, 'instanceid0000');
1037 $userfields = user_picture
::fields('u');
1038 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid0000');
1040 list($sort, $sortparams) = users_order_by_sql('u');
1042 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1043 FROM {user_enrolments} ue
1044 LEFT JOIN {user} u ON u.id = ue.userid
1045 WHERE ue.enrolid $instancesql AND
1049 $rs = $DB->get_recordset_sql($sql, $idparams +
$instanceparams +
$sortparams);
1051 foreach ($rs as $ue) {
1052 $user = user_picture
::unalias($ue);
1053 $ue->id
= $ue->ueid
;
1055 if (!array_key_exists($user->id
, $users)) {
1056 $user->enrolments
= array();
1057 $users[$user->id
] = $user;
1059 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
1060 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
1061 $users[$user->id
]->enrolments
[$ue->id
] = $ue;
1069 * A button that is used to enrol users in a course
1071 * @copyright 2010 Sam Hemelryk
1072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1074 class enrol_user_button
extends single_button
{
1077 * An array containing JS YUI modules required by this button
1080 protected $jsyuimodules = array();
1083 * An array containing JS initialisation calls required by this button
1086 protected $jsinitcalls = array();
1089 * An array strings required by JS for this button
1092 protected $jsstrings = array();
1095 * Initialises the new enrol_user_button
1097 * @staticvar int $count The number of enrol user buttons already created
1098 * @param moodle_url $url
1099 * @param string $label The text to display in the button
1100 * @param string $method Either post or get
1102 public function __construct(moodle_url
$url, $label, $method = 'post') {
1105 parent
::__construct($url, $label, $method);
1106 $this->class = 'singlebutton enrolusersbutton';
1107 $this->formid
= 'enrolusersbutton-'.$count;
1111 * Adds a YUI module call that will be added to the page when the button is used.
1113 * @param string|array $modules One or more modules to require
1114 * @param string $function The JS function to call
1115 * @param array $arguments An array of arguments to pass to the function
1116 * @param string $galleryversion The YUI gallery version of any modules required
1117 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1119 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1121 $js->modules
= (array)$modules;
1122 $js->function = $function;
1123 $js->arguments
= $arguments;
1124 $js->galleryversion
= $galleryversion;
1125 $js->ondomready
= $ondomready;
1126 $this->jsyuimodules
[] = $js;
1130 * Adds a JS initialisation call to the page when the button is used.
1132 * @param string $function The function to call
1133 * @param array $extraarguments An array of arguments to pass to the function
1134 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1135 * @param array $module A module definition
1137 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1139 $js->function = $function;
1140 $js->extraarguments
= $extraarguments;
1141 $js->ondomready
= $ondomready;
1142 $js->module
= $module;
1143 $this->jsinitcalls
[] = $js;
1147 * Requires strings for JS that will be loaded when the button is used.
1149 * @param type $identifiers
1150 * @param string $component
1153 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1154 $string = new stdClass
;
1155 $string->identifiers
= (array)$identifiers;
1156 $string->component
= $component;
1158 $this->jsstrings
[] = $string;
1162 * Initialises the JS that is required by this button
1164 * @param moodle_page $page
1166 public function initialise_js(moodle_page
$page) {
1167 foreach ($this->jsyuimodules
as $js) {
1168 $page->requires
->yui_module($js->modules
, $js->function, $js->arguments
, $js->galleryversion
, $js->ondomready
);
1170 foreach ($this->jsinitcalls
as $js) {
1171 $page->requires
->js_init_call($js->function, $js->extraarguments
, $js->ondomready
, $js->module
);
1173 foreach ($this->jsstrings
as $string) {
1174 $page->requires
->strings_for_js($string->identifiers
, $string->component
, $string->a
);
1180 * User enrolment action
1182 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1185 * @copyright 2011 Sam Hemelryk
1186 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1188 class user_enrolment_action
implements renderable
{
1191 * The icon to display for the action
1197 * The title for the action
1203 * The URL to the action
1209 * An array of HTML attributes
1212 protected $attributes = array();
1216 * @param pix_icon $icon
1217 * @param string $title
1218 * @param moodle_url $url
1219 * @param array $attributes
1221 public function __construct(pix_icon
$icon, $title, $url, array $attributes = null) {
1222 $this->icon
= $icon;
1223 $this->title
= $title;
1224 $this->url
= new moodle_url($url);
1225 if (!empty($attributes)) {
1226 $this->attributes
= $attributes;
1228 $this->attributes
['title'] = $title;
1232 * Returns the icon for this action
1235 public function get_icon() {
1240 * Returns the title for this action
1243 public function get_title() {
1244 return $this->title
;
1248 * Returns the URL for this action
1249 * @return moodle_url
1251 public function get_url() {
1256 * Returns the attributes to use for this action
1259 public function get_attributes() {
1260 return $this->attributes
;
1264 class enrol_ajax_exception
extends moodle_exception
{
1267 * @param string $errorcode The name of the string from error.php to print
1268 * @param string $module name of module
1269 * @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.
1270 * @param object $a Extra words and phrases that might be required in the error string
1271 * @param string $debuginfo optional debugging information
1273 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1274 parent
::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1279 * This class is used to manage a bulk operations for enrolment plugins.
1281 * @copyright 2011 Sam Hemelryk
1282 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1284 abstract class enrol_bulk_enrolment_operation
{
1287 * The course enrolment manager
1288 * @var course_enrolment_manager
1293 * The enrolment plugin to which this operation belongs
1300 * @param course_enrolment_manager $manager
1301 * @param stdClass $plugin
1303 public function __construct(course_enrolment_manager
$manager, enrol_plugin
$plugin = null) {
1304 $this->manager
= $manager;
1305 $this->plugin
= $plugin;
1309 * Returns a moodleform used for this operation, or false if no form is required and the action
1310 * should be immediatly processed.
1312 * @param moodle_url|string $defaultaction
1313 * @param mixed $defaultcustomdata
1314 * @return enrol_bulk_enrolment_change_form|moodleform|false
1316 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1321 * Returns the title to use for this bulk operation
1325 abstract public function get_title();
1328 * Returns the identifier for this bulk operation.
1329 * This should be the same identifier used by the plugins function when returning
1330 * all of its bulk operations.
1334 abstract public function get_identifier();
1337 * Processes the bulk operation on the given users
1339 * @param course_enrolment_manager $manager
1340 * @param array $users
1341 * @param stdClass $properties
1343 abstract public function process(course_enrolment_manager
$manager, array $users, stdClass
$properties);