Merge branch 'MDL-39518-24' of git://github.com/damyon/moodle into MOODLE_24_STABLE
[moodle.git] / enrol / locallib.php
blob250c39a2f9e484f68dd606c79c2386e0d0f4c443
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
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.
22 * @package core
23 * @subpackage enrol
24 * @copyright 2010 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 /**
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 {
41 /**
42 * The course context
43 * @var stdClass
45 protected $context;
46 /**
47 * The course we are managing enrolments for
48 * @var stdClass
50 protected $course = null;
51 /**
52 * Limits the focus of the manager to one enrolment plugin instance
53 * @var string
55 protected $instancefilter = null;
57 /**
58 * The total number of users enrolled in the course
59 * Populated by course_enrolment_manager::get_total_users
60 * @var int
62 protected $totalusers = null;
63 /**
64 * An array of users currently enrolled in the course
65 * Populated by course_enrolment_manager::get_users
66 * @var array
68 protected $users = array();
70 /**
71 * An array of users who have roles within this course but who have not
72 * been enrolled in the course
73 * @var array
75 protected $otherusers = array();
77 /**
78 * The total number of users who hold a role within the course but who
79 * arn't enrolled.
80 * @var int
82 protected $totalotherusers = null;
84 /**
85 * The current moodle_page object
86 * @var moodle_page
88 protected $moodlepage = null;
90 /**#@+
91 * These variables are used to cache the information this class uses
92 * please never use these directly instead use their get_ counterparts.
93 * @access private
94 * @var array
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;
105 /**#@-*/
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
136 * @return int
138 public function get_total_users() {
139 global $DB;
140 if ($this->totalusers === null) {
141 list($instancessql, $params, $filter) = $this->get_instance_sql();
142 $sqltotal = "SELECT COUNT(DISTINCT u.id)
143 FROM {user} u
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
158 * @return int
160 public function get_total_other_users() {
161 global $DB;
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
169 LEFT JOIN (
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
176 ue.id IS NULL";
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
193 * @return array
195 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
196 global $DB;
197 if ($direction !== 'ASC') {
198 $direction = 'DESC';
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
207 FROM {user} u
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
234 * @param int $page
235 * @param int $perpage
236 * @return array
238 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
239 global $DB;
240 if ($direction !== 'ASC') {
241 $direction = 'DESC';
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
252 LEFT JOIN (
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
260 ue.id IS NULL
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) {
278 global $DB, $CFG;
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 . '%';
290 } else {
291 $searchparam = $search . '%';
293 $i = 0;
294 foreach ($conditions as $key => $condition) {
295 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
296 $params["con{$i}00"] = $searchparam;
297 $i++;
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) {
327 global $DB, $CFG;
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) {
352 global $DB;
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
361 AND ue.id IS NULL";
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
375 * @return array
377 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
378 global $DB, $CFG;
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
387 AND ra.id IS NULL";
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
398 * @return string
400 protected function get_instance_sql() {
401 global $DB;
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);
408 } else {
409 $filter = 0;
410 if ($instances) {
411 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
412 } else {
413 // no enabled instances, oops, we should probably say something
414 $sql = "= :never";
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.
429 * @return array
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.
443 * @return array
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]);
453 continue;
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
465 * @return array
467 public function get_enrolment_plugins($onlyenabled = true) {
468 if ($this->_plugins === null) {
469 $this->_plugins = enrol_get_plugins(true);
472 if ($onlyenabled) {
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.
492 * @return array
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.
504 * @return array
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
511 if ($otherusers) {
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;
522 } else {
523 return $this->_assignableroles;
528 * Gets all of the groups for this course.
530 * @return array
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
547 * @return bool
549 public function unenrol_user($ue) {
550 global $DB;
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);
554 return true;
556 return false;
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) {
567 global $DB;
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
585 * @param int $userid
586 * @param int $roleid
587 * @return bool
589 public function unassign_role_from_user($userid, $roleid) {
590 global $DB;
591 require_capability('moodle/role:assign', $this->context);
592 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
593 try {
594 role_unassign($roleid, $user->id, $this->context->id, '', NULL);
595 } catch (Exception $e) {
596 if (defined('AJAX_SCRIPT')) {
597 throw $e;
599 return false;
601 return true;
605 * Assigns a role to a user.
607 * @param int $roleid
608 * @param int $userid
609 * @return int|false
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');
617 return false;
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
627 * @return bool
629 public function add_user_to_group($user, $groupid) {
630 require_capability('moodle/course:managegroups', $this->context);
631 $group = $this->get_group($groupid);
632 if (!$group) {
633 return false;
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
644 * @return bool
646 public function remove_user_from_group($user, $groupid) {
647 global $DB;
648 require_capability('moodle/course:managegroups', $this->context);
649 $group = $this->get_group($groupid);
650 if (!groups_remove_member_allowed($group, $user)) {
651 return false;
653 if (!$group) {
654 return false;
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)) {
668 return false;
670 return $groups[$groupid];
674 * Edits an enrolment
676 * @param stdClass $userenrolment
677 * @param stdClass $data
678 * @return bool
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);
689 return true;
691 return false;
695 * Returns the current enrolment filter that is being applied by this class
696 * @return string
698 public function get_enrolment_filter() {
699 return $this->instancefilter;
703 * Gets the roles assigned to this user that are applicable for this course.
705 * @param int $userid
706 * @return array
708 public function get_user_roles($userid) {
709 $roles = array();
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
717 continue;
719 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
720 continue;
722 $roles[$ra->roleid] = ($ra->itemid == 0 and $ra->component === '');
724 return $roles;
728 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
730 * @global moodle_database $DB
731 * @param int $userid
732 * @return array
734 public function get_user_enrolments($userid) {
735 global $DB;
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
753 * @param int $userid
754 * @return array
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
762 * exact page.
764 * @return array
766 public function get_url_params() {
767 $args = array(
768 'id' => $this->course->id
770 if (!empty($this->instancefilter)) {
771 $args['ifilter'] = $this->instancefilter;
773 return $args;
777 * Returns the course this object is managing enrolments for
779 * @return stdClass
781 public function get_course() {
782 return $this->course;
786 * Returns the course context
788 * @return stdClass
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
806 * @return array
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();
814 $now = time();
815 $extrafields = get_extra_user_fields($context);
817 $users = array();
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);
824 $a = new stdClass;
825 $a->role = $roles[$userrole->roleid]->localname;
826 $changeable = ($userrole->component == '');
827 if ($contextid == $this->context->id) {
828 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
829 } else {
830 $changeable = false;
831 switch ($userrole->contextlevel) {
832 case CONTEXT_COURSE :
833 // Meta course
834 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
835 break;
836 case CONTEXT_COURSECAT :
837 $roletext = get_string('rolefromcategory', 'enrol', $a);
838 break;
839 case CONTEXT_SYSTEM:
840 default:
841 $roletext = get_string('rolefromsystem', 'enrol', $a);
842 break;
845 if (!isset($users[$userrole->id]['roles'])) {
846 $users[$userrole->id]['roles'] = array();
848 $users[$userrole->id]['roles'][$userrole->roleid] = array(
849 'text' => $roletext,
850 'unchangeable' => !$changeable
853 return $users;
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
862 * @param int $sort
863 * @param string $direction ASC or DESC
864 * @param int $page
865 * @param int $perpage
866 * @return array
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);
872 $now = time();
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);
892 // Roles
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])));
898 // Users
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;
905 // Enrolments
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,
911 'period' => null,
912 'dimmed' => true,
913 'actions' => array()
915 continue;
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);
925 } else {
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,
932 'period' => $period,
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;
939 return $userdetails;
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) {
958 $details = array(
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);
972 return $details;
975 public function get_manual_enrol_buttons() {
976 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
977 $buttons = array();
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;
986 return $buttons;
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) {
993 return true;
996 return false;
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)) {
1011 return false;
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
1026 * @return array
1028 public function get_users_enrolments(array $userids) {
1029 global $DB;
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);
1037 } else {
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
1050 u.id $idsql
1051 ORDER BY $sort";
1053 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1054 $users = array();
1055 foreach ($rs as $ue) {
1056 $user = user_picture::unalias($ue);
1057 $ue->id = $ue->ueid;
1058 unset($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;
1067 $rs->close();
1068 return $users;
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
1082 * @var array
1084 protected $jsyuimodules = array();
1087 * An array containing JS initialisation calls required by this button
1088 * @var array
1090 protected $jsinitcalls = array();
1093 * An array strings required by JS for this button
1094 * @var array
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') {
1107 static $count = 0;
1108 $count ++;
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) {
1124 $js = new stdClass;
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) {
1142 $js = new stdClass;
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
1155 * @param mixed $a
1157 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1158 $string = new stdClass;
1159 $string->identifiers = (array)$identifiers;
1160 $string->component = $component;
1161 $string->a = $a;
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
1187 * a user enrolment.
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
1196 * @var pix_icon
1198 protected $icon;
1201 * The title for the action
1202 * @var string
1204 protected $title;
1207 * The URL to the action
1208 * @var moodle_url
1210 protected $url;
1213 * An array of HTML attributes
1214 * @var array
1216 protected $attributes = array();
1219 * Constructor
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
1237 * @return pix_icon
1239 public function get_icon() {
1240 return $this->icon;
1244 * Returns the title for this action
1245 * @return string
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() {
1256 return $this->url;
1260 * Returns the attributes to use for this action
1261 * @return array
1263 public function get_attributes() {
1264 return $this->attributes;
1268 class enrol_ajax_exception extends moodle_exception {
1270 * Constructor
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
1294 protected $manager;
1297 * The enrolment plugin to which this operation belongs
1298 * @var enrol_plugin
1300 protected $plugin;
1303 * Contructor
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) {
1321 return false;
1325 * Returns the title to use for this bulk operation
1327 * @return string
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.
1336 * @return string
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);