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 * @param int $addedenrollment number of users added to enrollment.
322 * @return array with two elememts:
323 * int total number of users matching the search.
324 * array of user objects returned by the query.
326 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
329 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
330 $order = ' ORDER BY ' . $sort;
332 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
333 $availableusers = $DB->get_records_sql($fields . $sql . $order,
334 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
336 return array('totalusers' => $totalusers, 'users' => $availableusers);
340 * Gets an array of the users that can be enrolled in this course.
342 * @global moodle_database $DB
343 * @param int $enrolid
344 * @param string $search
345 * @param bool $searchanywhere
346 * @param int $page Defaults to 0
347 * @param int $perpage Defaults to 25
348 * @param int $addedenrollment Defaults to 0
349 * @return array Array(totalusers => int, users => array)
351 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
354 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
356 $fields = 'SELECT '.$ufields;
357 $countfields = 'SELECT COUNT(1)';
358 $sql = " FROM {user} u
359 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
360 WHERE $wherecondition
362 $params['enrolid'] = $enrolid;
364 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
368 * Searches other users and returns paginated results
370 * @global moodle_database $DB
371 * @param string $search
372 * @param bool $searchanywhere
373 * @param int $page Starting at 0
374 * @param int $perpage
377 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
380 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
382 $fields = 'SELECT ' . $ufields;
383 $countfields = 'SELECT COUNT(u.id)';
384 $sql = " FROM {user} u
385 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
386 WHERE $wherecondition
388 $params['contextid'] = $this->context
->id
;
390 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
394 * Gets an array containing some SQL to user for when selecting, params for
395 * that SQL, and the filter that was used in constructing the sql.
397 * @global moodle_database $DB
400 protected function get_instance_sql() {
402 if ($this->_instancessql
=== null) {
403 $instances = $this->get_enrolment_instances();
404 $filter = $this->get_enrolment_filter();
405 if ($filter && array_key_exists($filter, $instances)) {
406 $sql = " = :ifilter";
407 $params = array('ifilter'=>$filter);
411 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED
);
413 // no enabled instances, oops, we should probably say something
415 $params = array('never'=>-1);
418 $this->instancefilter
= $filter;
419 $this->_instancessql
= array($sql, $params, $filter);
421 return $this->_instancessql
;
425 * Returns all of the enrolment instances for this course.
427 * NOTE: since 2.4 it includes instances of disabled plugins too.
431 public function get_enrolment_instances() {
432 if ($this->_instances
=== null) {
433 $this->_instances
= enrol_get_instances($this->course
->id
, false);
435 return $this->_instances
;
439 * Returns the names for all of the enrolment instances for this course.
441 * NOTE: since 2.4 it includes instances of disabled plugins too.
445 public function get_enrolment_instance_names() {
446 if ($this->_inames
=== null) {
447 $instances = $this->get_enrolment_instances();
448 $plugins = $this->get_enrolment_plugins(false);
449 foreach ($instances as $key=>$instance) {
450 if (!isset($plugins[$instance->enrol
])) {
451 // weird, some broken stuff in plugin
452 unset($instances[$key]);
455 $this->_inames
[$key] = $plugins[$instance->enrol
]->get_instance_name($instance);
458 return $this->_inames
;
462 * Gets all of the enrolment plugins that are active for this course.
464 * @param bool $onlyenabled return only enabled enrol plugins
467 public function get_enrolment_plugins($onlyenabled = true) {
468 if ($this->_plugins
=== null) {
469 $this->_plugins
= enrol_get_plugins(true);
473 return $this->_plugins
;
476 if ($this->_allplugins
=== null) {
477 // Make sure we have the same objects in _allplugins and _plugins.
478 $this->_allplugins
= $this->_plugins
;
479 foreach (enrol_get_plugins(false) as $name=>$plugin) {
480 if (!isset($this->_allplugins
[$name])) {
481 $this->_allplugins
[$name] = $plugin;
486 return $this->_allplugins
;
490 * Gets all of the roles this course can contain.
494 public function get_all_roles() {
495 if ($this->_roles
=== null) {
496 $this->_roles
= role_fix_names(get_all_roles($this->context
), $this->context
);
498 return $this->_roles
;
502 * Gets all of the assignable roles for this course.
506 public function get_assignable_roles($otherusers = false) {
507 if ($this->_assignableroles
=== null) {
508 $this->_assignableroles
= get_assignable_roles($this->context
, ROLENAME_ALIAS
, false); // verifies unassign access control too
512 if (!is_array($this->_assignablerolesothers
)) {
513 $this->_assignablerolesothers
= array();
514 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context
, 'moodle/course:view');
515 foreach ($this->_assignableroles
as $roleid=>$role) {
516 if (isset($courseviewroles[$roleid])) {
517 $this->_assignablerolesothers
[$roleid] = $role;
521 return $this->_assignablerolesothers
;
523 return $this->_assignableroles
;
528 * Gets all of the groups for this course.
532 public function get_all_groups() {
533 if ($this->_groups
=== null) {
534 $this->_groups
= groups_get_all_groups($this->course
->id
);
535 foreach ($this->_groups
as $gid=>$group) {
536 $this->_groups
[$gid]->name
= format_string($group->name
);
539 return $this->_groups
;
543 * Unenrols a user from the course given the users ue entry
545 * @global moodle_database $DB
546 * @param stdClass $ue
549 public function unenrol_user($ue) {
551 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
552 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context
)) {
553 $plugin->unenrol_user($instance, $ue->userid
);
560 * Given a user enrolment record this method returns the plugin and enrolment
561 * instance that relate to it.
563 * @param stdClass|int $userenrolment
564 * @return array array($instance, $plugin)
566 public function get_user_enrolment_components($userenrolment) {
568 if (is_numeric($userenrolment)) {
569 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
571 $instances = $this->get_enrolment_instances();
572 $plugins = $this->get_enrolment_plugins(false);
573 if (!$userenrolment ||
!isset($instances[$userenrolment->enrolid
])) {
574 return array(false, false);
576 $instance = $instances[$userenrolment->enrolid
];
577 $plugin = $plugins[$instance->enrol
];
578 return array($instance, $plugin);
582 * Removes an assigned role from a user.
584 * @global moodle_database $DB
589 public function unassign_role_from_user($userid, $roleid) {
591 require_capability('moodle/role:assign', $this->context
);
592 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
594 role_unassign($roleid, $user->id
, $this->context
->id
, '', NULL);
595 } catch (Exception
$e) {
596 if (defined('AJAX_SCRIPT')) {
605 * Assigns a role to a user.
611 public function assign_role_to_user($roleid, $userid) {
612 require_capability('moodle/role:assign', $this->context
);
613 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
614 if (defined('AJAX_SCRIPT')) {
615 throw new moodle_exception('invalidrole');
619 return role_assign($roleid, $userid, $this->context
->id
, '', NULL);
623 * Adds a user to a group
625 * @param stdClass $user
626 * @param int $groupid
629 public function add_user_to_group($user, $groupid) {
630 require_capability('moodle/course:managegroups', $this->context
);
631 $group = $this->get_group($groupid);
635 return groups_add_member($group->id
, $user->id
);
639 * Removes a user from a group
641 * @global moodle_database $DB
642 * @param StdClass $user
643 * @param int $groupid
646 public function remove_user_from_group($user, $groupid) {
648 require_capability('moodle/course:managegroups', $this->context
);
649 $group = $this->get_group($groupid);
650 if (!groups_remove_member_allowed($group, $user)) {
656 return groups_remove_member($group, $user);
660 * Gets the requested group
662 * @param int $groupid
663 * @return stdClass|int
665 public function get_group($groupid) {
666 $groups = $this->get_all_groups();
667 if (!array_key_exists($groupid, $groups)) {
670 return $groups[$groupid];
676 * @param stdClass $userenrolment
677 * @param stdClass $data
680 public function edit_enrolment($userenrolment, $data) {
681 //Only allow editing if the user has the appropriate capability
682 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
683 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
684 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context
)) {
685 if (!isset($data->status
)) {
686 $data->status
= $userenrolment->status
;
688 $plugin->update_user_enrol($instance, $userenrolment->userid
, $data->status
, $data->timestart
, $data->timeend
);
695 * Returns the current enrolment filter that is being applied by this class
698 public function get_enrolment_filter() {
699 return $this->instancefilter
;
703 * Gets the roles assigned to this user that are applicable for this course.
708 public function get_user_roles($userid) {
710 $ras = get_user_roles($this->context
, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
711 foreach ($ras as $ra) {
712 if ($ra->contextid
!= $this->context
->id
) {
713 if (!array_key_exists($ra->roleid
, $roles)) {
714 $roles[$ra->roleid
] = null;
716 // higher ras, course always takes precedence
719 if (array_key_exists($ra->roleid
, $roles) && $roles[$ra->roleid
] === false) {
722 $roles[$ra->roleid
] = ($ra->itemid
== 0 and $ra->component
=== '');
728 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
730 * @global moodle_database $DB
734 public function get_user_enrolments($userid) {
736 list($instancessql, $params, $filter) = $this->get_instance_sql();
737 $params['userid'] = $userid;
738 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
739 $instances = $this->get_enrolment_instances();
740 $plugins = $this->get_enrolment_plugins(false);
741 $inames = $this->get_enrolment_instance_names();
742 foreach ($userenrolments as &$ue) {
743 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
744 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
745 $ue->enrolmentinstancename
= $inames[$ue->enrolmentinstance
->id
];
747 return $userenrolments;
751 * Gets the groups this user belongs to
756 public function get_user_groups($userid) {
757 return groups_get_all_groups($this->course
->id
, $userid, 0, 'g.id');
761 * Retursn an array of params that would go into the URL to return to this
766 public function get_url_params() {
768 'id' => $this->course
->id
770 if (!empty($this->instancefilter
)) {
771 $args['ifilter'] = $this->instancefilter
;
777 * Returns the course this object is managing enrolments for
781 public function get_course() {
782 return $this->course
;
786 * Returns the course context
790 public function get_context() {
791 return $this->context
;
795 * Gets an array of other users in this course ready for display.
797 * Other users are users who have been assigned or inherited roles within this
798 * course but have not been enrolled.
800 * @param core_enrol_renderer $renderer
801 * @param moodle_url $pageurl
802 * @param string $sort
803 * @param string $direction ASC | DESC
804 * @param int $page Starting from 0
805 * @param int $perpage
808 public function get_other_users_for_display(core_enrol_renderer
$renderer, moodle_url
$pageurl, $sort, $direction, $page, $perpage) {
810 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
811 $roles = $this->get_all_roles();
813 $context = $this->get_context();
815 $extrafields = get_extra_user_fields($context);
818 foreach ($userroles as $userrole) {
819 $contextid = $userrole->contextid
;
820 unset($userrole->contextid
); // This would collide with user avatar.
821 if (!array_key_exists($userrole->id
, $users)) {
822 $users[$userrole->id
] = $this->prepare_user_for_display($userrole, $extrafields, $now);
825 $a->role
= $roles[$userrole->roleid
]->localname
;
826 $changeable = ($userrole->component
== '');
827 if ($contextid == $this->context
->id
) {
828 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
831 switch ($userrole->contextlevel
) {
832 case CONTEXT_COURSE
:
834 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
836 case CONTEXT_COURSECAT
:
837 $roletext = get_string('rolefromcategory', 'enrol', $a);
841 $roletext = get_string('rolefromsystem', 'enrol', $a);
845 if (!isset($users[$userrole->id
]['roles'])) {
846 $users[$userrole->id
]['roles'] = array();
848 $users[$userrole->id
]['roles'][$userrole->roleid
] = array(
850 'unchangeable' => !$changeable
857 * Gets an array of users for display, this includes minimal user information
858 * as well as minimal information on the users roles, groups, and enrolments.
860 * @param core_enrol_renderer $renderer
861 * @param moodle_url $pageurl
863 * @param string $direction ASC or DESC
865 * @param int $perpage
868 public function get_users_for_display(course_enrolment_manager
$manager, $sort, $direction, $page, $perpage) {
869 $pageurl = $manager->get_moodlepage()->url
;
870 $users = $this->get_users($sort, $direction, $page, $perpage);
873 $straddgroup = get_string('addgroup', 'group');
874 $strunenrol = get_string('unenrol', 'enrol');
875 $stredit = get_string('edit');
877 $allroles = $this->get_all_roles();
878 $assignable = $this->get_assignable_roles();
879 $allgroups = $this->get_all_groups();
880 $context = $this->get_context();
881 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
883 $url = new moodle_url($pageurl, $this->get_url_params());
884 $extrafields = get_extra_user_fields($context);
886 $enabledplugins = $this->get_enrolment_plugins(true);
888 $userdetails = array();
889 foreach ($users as $user) {
890 $details = $this->prepare_user_for_display($user, $extrafields, $now);
893 $details['roles'] = array();
894 foreach ($this->get_user_roles($user->id
) as $rid=>$rassignable) {
895 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname
, 'unchangeable'=>(!$rassignable ||
!isset($assignable[$rid])));
899 $usergroups = $this->get_user_groups($user->id
);
900 $details['groups'] = array();
901 foreach($usergroups as $gid=>$unused) {
902 $details['groups'][$gid] = $allgroups[$gid]->name
;
906 $details['enrolments'] = array();
907 foreach ($this->get_user_enrolments($user->id
) as $ue) {
908 if (!isset($enabledplugins[$ue->enrolmentinstance
->enrol
])) {
909 $details['enrolments'][$ue->id
] = array(
910 'text' => $ue->enrolmentinstancename
,
916 } else if ($ue->timestart
and $ue->timeend
) {
917 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart
), 'end'=>userdate($ue->timeend
)));
918 $periodoutside = ($ue->timestart
&& $ue->timeend
&& $now < $ue->timestart
&& $now > $ue->timeend
);
919 } else if ($ue->timestart
) {
920 $period = get_string('periodstart', 'enrol', userdate($ue->timestart
));
921 $periodoutside = ($ue->timestart
&& $now < $ue->timestart
);
922 } else if ($ue->timeend
) {
923 $period = get_string('periodend', 'enrol', userdate($ue->timeend
));
924 $periodoutside = ($ue->timeend
&& $now > $ue->timeend
);
926 // If there is no start or end show when user was enrolled.
927 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated
));
928 $periodoutside = false;
930 $details['enrolments'][$ue->id
] = array(
931 'text' => $ue->enrolmentinstancename
,
933 'dimmed' => ($periodoutside or $ue->status
!= ENROL_USER_ACTIVE
or $ue->enrolmentinstance
->status
!= ENROL_INSTANCE_ENABLED
),
934 'actions' => $ue->enrolmentplugin
->get_user_enrolment_actions($manager, $ue)
937 $userdetails[$user->id
] = $details;
943 * Prepare a user record for display
945 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
946 * prepare user fields for display
948 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
950 * @param object $user The user record
951 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
952 * additional fields may be displayed
953 * @param int $now The time used for lastaccess calculation
954 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
955 * additional fields from $extrafields
957 private function prepare_user_for_display($user, $extrafields, $now) {
959 'userid' => $user->id
,
960 'courseid' => $this->get_course()->id
,
961 'picture' => new user_picture($user),
962 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
963 'lastseen' => get_string('never'),
965 foreach ($extrafields as $field) {
966 $details[$field] = $user->{$field};
969 if ($user->lastaccess
) {
970 $details['lastseen'] = format_time($now - $user->lastaccess
);
975 public function get_manual_enrol_buttons() {
976 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
978 foreach ($plugins as $plugin) {
979 $newbutton = $plugin->get_manual_enrol_button($this);
980 if (is_array($newbutton)) {
981 $buttons +
= $newbutton;
982 } else if ($newbutton instanceof enrol_user_button
) {
983 $buttons[] = $newbutton;
989 public function has_instance($enrolpluginname) {
990 // Make sure manual enrolments instance exists
991 foreach ($this->get_enrolment_instances() as $instance) {
992 if ($instance->enrol
== $enrolpluginname) {
1000 * Returns the enrolment plugin that the course manager was being filtered to.
1002 * If no filter was being applied then this function returns false.
1004 * @return enrol_plugin
1006 public function get_filtered_enrolment_plugin() {
1007 $instances = $this->get_enrolment_instances();
1008 $plugins = $this->get_enrolment_plugins(false);
1010 if (empty($this->instancefilter
) ||
!array_key_exists($this->instancefilter
, $instances)) {
1014 $instance = $instances[$this->instancefilter
];
1015 return $plugins[$instance->enrol
];
1019 * Returns and array of users + enrolment details.
1021 * Given an array of user id's this function returns and array of user enrolments for those users
1022 * as well as enough user information to display the users name and picture for each enrolment.
1024 * @global moodle_database $DB
1025 * @param array $userids
1028 public function get_users_enrolments(array $userids) {
1031 $instances = $this->get_enrolment_instances();
1032 $plugins = $this->get_enrolment_plugins(false);
1034 if (!empty($this->instancefilter
)) {
1035 $instancesql = ' = :instanceid';
1036 $instanceparams = array('instanceid' => $this->instancefilter
);
1038 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED
, 'instanceid0000');
1041 $userfields = user_picture
::fields('u');
1042 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid0000');
1044 list($sort, $sortparams) = users_order_by_sql('u');
1046 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1047 FROM {user_enrolments} ue
1048 LEFT JOIN {user} u ON u.id = ue.userid
1049 WHERE ue.enrolid $instancesql AND
1053 $rs = $DB->get_recordset_sql($sql, $idparams +
$instanceparams +
$sortparams);
1055 foreach ($rs as $ue) {
1056 $user = user_picture
::unalias($ue);
1057 $ue->id
= $ue->ueid
;
1059 if (!array_key_exists($user->id
, $users)) {
1060 $user->enrolments
= array();
1061 $users[$user->id
] = $user;
1063 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
1064 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
1065 $users[$user->id
]->enrolments
[$ue->id
] = $ue;
1073 * A button that is used to enrol users in a course
1075 * @copyright 2010 Sam Hemelryk
1076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1078 class enrol_user_button
extends single_button
{
1081 * An array containing JS YUI modules required by this button
1084 protected $jsyuimodules = array();
1087 * An array containing JS initialisation calls required by this button
1090 protected $jsinitcalls = array();
1093 * An array strings required by JS for this button
1096 protected $jsstrings = array();
1099 * Initialises the new enrol_user_button
1101 * @staticvar int $count The number of enrol user buttons already created
1102 * @param moodle_url $url
1103 * @param string $label The text to display in the button
1104 * @param string $method Either post or get
1106 public function __construct(moodle_url
$url, $label, $method = 'post') {
1109 parent
::__construct($url, $label, $method);
1110 $this->class = 'singlebutton enrolusersbutton';
1111 $this->formid
= 'enrolusersbutton-'.$count;
1115 * Adds a YUI module call that will be added to the page when the button is used.
1117 * @param string|array $modules One or more modules to require
1118 * @param string $function The JS function to call
1119 * @param array $arguments An array of arguments to pass to the function
1120 * @param string $galleryversion The YUI gallery version of any modules required
1121 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1123 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1125 $js->modules
= (array)$modules;
1126 $js->function = $function;
1127 $js->arguments
= $arguments;
1128 $js->galleryversion
= $galleryversion;
1129 $js->ondomready
= $ondomready;
1130 $this->jsyuimodules
[] = $js;
1134 * Adds a JS initialisation call to the page when the button is used.
1136 * @param string $function The function to call
1137 * @param array $extraarguments An array of arguments to pass to the function
1138 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1139 * @param array $module A module definition
1141 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1143 $js->function = $function;
1144 $js->extraarguments
= $extraarguments;
1145 $js->ondomready
= $ondomready;
1146 $js->module
= $module;
1147 $this->jsinitcalls
[] = $js;
1151 * Requires strings for JS that will be loaded when the button is used.
1153 * @param type $identifiers
1154 * @param string $component
1157 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1158 $string = new stdClass
;
1159 $string->identifiers
= (array)$identifiers;
1160 $string->component
= $component;
1162 $this->jsstrings
[] = $string;
1166 * Initialises the JS that is required by this button
1168 * @param moodle_page $page
1170 public function initialise_js(moodle_page
$page) {
1171 foreach ($this->jsyuimodules
as $js) {
1172 $page->requires
->yui_module($js->modules
, $js->function, $js->arguments
, $js->galleryversion
, $js->ondomready
);
1174 foreach ($this->jsinitcalls
as $js) {
1175 $page->requires
->js_init_call($js->function, $js->extraarguments
, $js->ondomready
, $js->module
);
1177 foreach ($this->jsstrings
as $string) {
1178 $page->requires
->strings_for_js($string->identifiers
, $string->component
, $string->a
);
1184 * User enrolment action
1186 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1189 * @copyright 2011 Sam Hemelryk
1190 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1192 class user_enrolment_action
implements renderable
{
1195 * The icon to display for the action
1201 * The title for the action
1207 * The URL to the action
1213 * An array of HTML attributes
1216 protected $attributes = array();
1220 * @param pix_icon $icon
1221 * @param string $title
1222 * @param moodle_url $url
1223 * @param array $attributes
1225 public function __construct(pix_icon
$icon, $title, $url, array $attributes = null) {
1226 $this->icon
= $icon;
1227 $this->title
= $title;
1228 $this->url
= new moodle_url($url);
1229 if (!empty($attributes)) {
1230 $this->attributes
= $attributes;
1232 $this->attributes
['title'] = $title;
1236 * Returns the icon for this action
1239 public function get_icon() {
1244 * Returns the title for this action
1247 public function get_title() {
1248 return $this->title
;
1252 * Returns the URL for this action
1253 * @return moodle_url
1255 public function get_url() {
1260 * Returns the attributes to use for this action
1263 public function get_attributes() {
1264 return $this->attributes
;
1268 class enrol_ajax_exception
extends moodle_exception
{
1271 * @param string $errorcode The name of the string from error.php to print
1272 * @param string $module name of module
1273 * @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.
1274 * @param object $a Extra words and phrases that might be required in the error string
1275 * @param string $debuginfo optional debugging information
1277 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1278 parent
::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1283 * This class is used to manage a bulk operations for enrolment plugins.
1285 * @copyright 2011 Sam Hemelryk
1286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1288 abstract class enrol_bulk_enrolment_operation
{
1291 * The course enrolment manager
1292 * @var course_enrolment_manager
1297 * The enrolment plugin to which this operation belongs
1304 * @param course_enrolment_manager $manager
1305 * @param stdClass $plugin
1307 public function __construct(course_enrolment_manager
$manager, enrol_plugin
$plugin = null) {
1308 $this->manager
= $manager;
1309 $this->plugin
= $plugin;
1313 * Returns a moodleform used for this operation, or false if no form is required and the action
1314 * should be immediatly processed.
1316 * @param moodle_url|string $defaultaction
1317 * @param mixed $defaultcustomdata
1318 * @return enrol_bulk_enrolment_change_form|moodleform|false
1320 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1325 * Returns the title to use for this bulk operation
1329 abstract public function get_title();
1332 * Returns the identifier for this bulk operation.
1333 * This should be the same identifier used by the plugins function when returning
1334 * all of its bulk operations.
1338 abstract public function get_identifier();
1341 * Processes the bulk operation on the given users
1343 * @param course_enrolment_manager $manager
1344 * @param array $users
1345 * @param stdClass $properties
1347 abstract public function process(course_enrolment_manager
$manager, array $users, stdClass
$properties);