Merge branch 'MDL-38821_master' of git://github.com/dmonllao/moodle
[moodle.git] / enrol / locallib.php
blobe4ece1e672b20c85cdca4e27ed5437fa5165d004
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;
56 /**
57 * Limits the focus of the manager to users with specified role
58 * @var int
60 protected $rolefilter = 0;
61 /**
62 * Limits the focus of the manager to users who match search string
63 * @var string
65 protected $searchfilter = '';
67 /**
68 * The total number of users enrolled in the course
69 * Populated by course_enrolment_manager::get_total_users
70 * @var int
72 protected $totalusers = null;
73 /**
74 * An array of users currently enrolled in the course
75 * Populated by course_enrolment_manager::get_users
76 * @var array
78 protected $users = array();
80 /**
81 * An array of users who have roles within this course but who have not
82 * been enrolled in the course
83 * @var array
85 protected $otherusers = array();
87 /**
88 * The total number of users who hold a role within the course but who
89 * arn't enrolled.
90 * @var int
92 protected $totalotherusers = null;
94 /**
95 * The current moodle_page object
96 * @var moodle_page
98 protected $moodlepage = null;
100 /**#@+
101 * These variables are used to cache the information this class uses
102 * please never use these directly instead use their get_ counterparts.
103 * @access private
104 * @var array
106 private $_instancessql = null;
107 private $_instances = null;
108 private $_inames = null;
109 private $_plugins = null;
110 private $_allplugins = null;
111 private $_roles = null;
112 private $_assignableroles = null;
113 private $_assignablerolesothers = null;
114 private $_groups = null;
115 /**#@-*/
118 * Constructs the course enrolment manager
120 * @param moodle_page $moodlepage
121 * @param stdClass $course
122 * @param string $instancefilter
123 * @param int $rolefilter If non-zero, filters to users with specified role
124 * @param string $searchfilter If non-blank, filters to users with search text
126 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
127 $rolefilter = 0, $searchfilter = '') {
128 $this->moodlepage = $moodlepage;
129 $this->context = context_course::instance($course->id);
130 $this->course = $course;
131 $this->instancefilter = $instancefilter;
132 $this->rolefilter = $rolefilter;
133 $this->searchfilter = $searchfilter;
137 * Returns the current moodle page
138 * @return moodle_page
140 public function get_moodlepage() {
141 return $this->moodlepage;
145 * Returns the total number of enrolled users in the course.
147 * If a filter was specificed this will be the total number of users enrolled
148 * in this course by means of that instance.
150 * @global moodle_database $DB
151 * @return int
153 public function get_total_users() {
154 global $DB;
155 if ($this->totalusers === null) {
156 list($instancessql, $params, $filter) = $this->get_instance_sql();
157 list($filtersql, $moreparams) = $this->get_filter_sql();
158 $params += $moreparams;
159 $sqltotal = "SELECT COUNT(DISTINCT u.id)
160 FROM {user} u
161 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
162 JOIN {enrol} e ON (e.id = ue.enrolid)
163 WHERE $filtersql";
164 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
166 return $this->totalusers;
170 * Returns the total number of enrolled users in the course.
172 * If a filter was specificed this will be the total number of users enrolled
173 * in this course by means of that instance.
175 * @global moodle_database $DB
176 * @return int
178 public function get_total_other_users() {
179 global $DB;
180 if ($this->totalotherusers === null) {
181 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
182 $params['courseid'] = $this->course->id;
183 $sql = "SELECT COUNT(DISTINCT u.id)
184 FROM {role_assignments} ra
185 JOIN {user} u ON u.id = ra.userid
186 JOIN {context} ctx ON ra.contextid = ctx.id
187 LEFT JOIN (
188 SELECT ue.id, ue.userid
189 FROM {user_enrolments} ue
190 LEFT JOIN {enrol} e ON e.id=ue.enrolid
191 WHERE e.courseid = :courseid
192 ) ue ON ue.userid=u.id
193 WHERE ctx.id $ctxcondition AND
194 ue.id IS NULL";
195 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
197 return $this->totalotherusers;
201 * Gets all of the users enrolled in this course.
203 * If a filter was specified this will be the users who were enrolled
204 * in this course by means of that instance. If role or search filters were
205 * specified then these will also be applied.
207 * @global moodle_database $DB
208 * @param string $sort
209 * @param string $direction ASC or DESC
210 * @param int $page First page should be 0
211 * @param int $perpage Defaults to 25
212 * @return array
214 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
215 global $DB;
216 if ($direction !== 'ASC') {
217 $direction = 'DESC';
219 $key = md5("$sort-$direction-$page-$perpage");
220 if (!array_key_exists($key, $this->users)) {
221 list($instancessql, $params, $filter) = $this->get_instance_sql();
222 list($filtersql, $moreparams) = $this->get_filter_sql();
223 $params += $moreparams;
224 $extrafields = get_extra_user_fields($this->get_context());
225 $extrafields[] = 'lastaccess';
226 $ufields = user_picture::fields('u', $extrafields);
227 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
228 FROM {user} u
229 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
230 JOIN {enrol} e ON (e.id = ue.enrolid)
231 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)
232 WHERE $filtersql";
233 if ($sort === 'firstname') {
234 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
235 } else if ($sort === 'lastname') {
236 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
237 } else if ($sort === 'email') {
238 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
239 } else if ($sort === 'lastseen') {
240 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
242 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
244 return $this->users[$key];
248 * Obtains WHERE clause to filter results by defined search and role filter
249 * (instance filter is handled separately in JOIN clause, see
250 * get_instance_sql).
252 * @return array Two-element array with SQL and params for WHERE clause
254 protected function get_filter_sql() {
255 global $DB;
257 // Search condition.
258 $extrafields = get_extra_user_fields($this->get_context());
259 list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
261 // Role condition.
262 if ($this->rolefilter) {
263 // Get context SQL.
264 $contextids = $this->context->get_parent_context_ids();
265 $contextids[] = $this->context->id;
266 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
267 $params += $contextparams;
269 // Role check condition.
270 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
271 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
272 $params['roleid'] = $this->rolefilter;
275 return array($sql, $params);
279 * Gets and array of other users.
281 * Other users are users who have been assigned roles or inherited roles
282 * within this course but who have not been enrolled in the course
284 * @global moodle_database $DB
285 * @param string $sort
286 * @param string $direction
287 * @param int $page
288 * @param int $perpage
289 * @return array
291 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
292 global $DB;
293 if ($direction !== 'ASC') {
294 $direction = 'DESC';
296 $key = md5("$sort-$direction-$page-$perpage");
297 if (!array_key_exists($key, $this->otherusers)) {
298 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
299 $params['courseid'] = $this->course->id;
300 $params['cid'] = $this->course->id;
301 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
302 FROM {role_assignments} ra
303 JOIN {user} u ON u.id = ra.userid
304 JOIN {context} ctx ON ra.contextid = ctx.id
305 LEFT JOIN (
306 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
307 FROM {user_enrolments} ue
308 LEFT JOIN {enrol} e ON e.id=ue.enrolid
309 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
310 WHERE e.courseid = :courseid
311 ) ue ON ue.userid=u.id
312 WHERE ctx.id $ctxcondition AND
313 ue.id IS NULL
314 ORDER BY u.$sort $direction, ctx.depth DESC";
315 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
317 return $this->otherusers[$key];
321 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
323 * @param string $search the search term, if any.
324 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
325 * @return array with three elements:
326 * string list of fields to SELECT,
327 * string contents of SQL WHERE clause,
328 * array query params. Note that the SQL snippets use named parameters.
330 protected function get_basic_search_conditions($search, $searchanywhere) {
331 global $DB, $CFG;
333 // Add some additional sensible conditions
334 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
335 $params = array('guestid' => $CFG->siteguest);
336 if (!empty($search)) {
337 $conditions = get_extra_user_fields($this->get_context());
338 $conditions[] = 'u.firstname';
339 $conditions[] = 'u.lastname';
340 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
341 if ($searchanywhere) {
342 $searchparam = '%' . $search . '%';
343 } else {
344 $searchparam = $search . '%';
346 $i = 0;
347 foreach ($conditions as $key => $condition) {
348 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
349 $params["con{$i}00"] = $searchparam;
350 $i++;
352 $tests[] = '(' . implode(' OR ', $conditions) . ')';
354 $wherecondition = implode(' AND ', $tests);
356 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
357 $extrafields[] = 'username';
358 $extrafields[] = 'lastaccess';
359 $ufields = user_picture::fields('u', $extrafields);
361 return array($ufields, $params, $wherecondition);
365 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
367 * @param string $search the search string, if any.
368 * @param string $fields the first bit of the SQL when returning some users.
369 * @param string $countfields fhe first bit of the SQL when counting the users.
370 * @param string $sql the bulk of the SQL statement.
371 * @param array $params query parameters.
372 * @param int $page which page number of the results to show.
373 * @param int $perpage number of users per page.
374 * @param int $addedenrollment number of users added to enrollment.
375 * @return array with two elememts:
376 * int total number of users matching the search.
377 * array of user objects returned by the query.
379 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
380 global $DB, $CFG;
382 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
383 $order = ' ORDER BY ' . $sort;
385 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
386 $availableusers = $DB->get_records_sql($fields . $sql . $order,
387 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
389 return array('totalusers' => $totalusers, 'users' => $availableusers);
393 * Gets an array of the users that can be enrolled in this course.
395 * @global moodle_database $DB
396 * @param int $enrolid
397 * @param string $search
398 * @param bool $searchanywhere
399 * @param int $page Defaults to 0
400 * @param int $perpage Defaults to 25
401 * @param int $addedenrollment Defaults to 0
402 * @return array Array(totalusers => int, users => array)
404 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
405 global $DB;
407 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
409 $fields = 'SELECT '.$ufields;
410 $countfields = 'SELECT COUNT(1)';
411 $sql = " FROM {user} u
412 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
413 WHERE $wherecondition
414 AND ue.id IS NULL";
415 $params['enrolid'] = $enrolid;
417 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
421 * Searches other users and returns paginated results
423 * @global moodle_database $DB
424 * @param string $search
425 * @param bool $searchanywhere
426 * @param int $page Starting at 0
427 * @param int $perpage
428 * @return array
430 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
431 global $DB, $CFG;
433 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
435 $fields = 'SELECT ' . $ufields;
436 $countfields = 'SELECT COUNT(u.id)';
437 $sql = " FROM {user} u
438 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
439 WHERE $wherecondition
440 AND ra.id IS NULL";
441 $params['contextid'] = $this->context->id;
443 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
447 * Gets an array containing some SQL to user for when selecting, params for
448 * that SQL, and the filter that was used in constructing the sql.
450 * @global moodle_database $DB
451 * @return string
453 protected function get_instance_sql() {
454 global $DB;
455 if ($this->_instancessql === null) {
456 $instances = $this->get_enrolment_instances();
457 $filter = $this->get_enrolment_filter();
458 if ($filter && array_key_exists($filter, $instances)) {
459 $sql = " = :ifilter";
460 $params = array('ifilter'=>$filter);
461 } else {
462 $filter = 0;
463 if ($instances) {
464 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
465 } else {
466 // no enabled instances, oops, we should probably say something
467 $sql = "= :never";
468 $params = array('never'=>-1);
471 $this->instancefilter = $filter;
472 $this->_instancessql = array($sql, $params, $filter);
474 return $this->_instancessql;
478 * Returns all of the enrolment instances for this course.
480 * NOTE: since 2.4 it includes instances of disabled plugins too.
482 * @return array
484 public function get_enrolment_instances() {
485 if ($this->_instances === null) {
486 $this->_instances = enrol_get_instances($this->course->id, false);
488 return $this->_instances;
492 * Returns the names for all of the enrolment instances for this course.
494 * NOTE: since 2.4 it includes instances of disabled plugins too.
496 * @return array
498 public function get_enrolment_instance_names() {
499 if ($this->_inames === null) {
500 $instances = $this->get_enrolment_instances();
501 $plugins = $this->get_enrolment_plugins(false);
502 foreach ($instances as $key=>$instance) {
503 if (!isset($plugins[$instance->enrol])) {
504 // weird, some broken stuff in plugin
505 unset($instances[$key]);
506 continue;
508 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
511 return $this->_inames;
515 * Gets all of the enrolment plugins that are active for this course.
517 * @param bool $onlyenabled return only enabled enrol plugins
518 * @return array
520 public function get_enrolment_plugins($onlyenabled = true) {
521 if ($this->_plugins === null) {
522 $this->_plugins = enrol_get_plugins(true);
525 if ($onlyenabled) {
526 return $this->_plugins;
529 if ($this->_allplugins === null) {
530 // Make sure we have the same objects in _allplugins and _plugins.
531 $this->_allplugins = $this->_plugins;
532 foreach (enrol_get_plugins(false) as $name=>$plugin) {
533 if (!isset($this->_allplugins[$name])) {
534 $this->_allplugins[$name] = $plugin;
539 return $this->_allplugins;
543 * Gets all of the roles this course can contain.
545 * @return array
547 public function get_all_roles() {
548 if ($this->_roles === null) {
549 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
551 return $this->_roles;
555 * Gets all of the assignable roles for this course.
557 * @return array
559 public function get_assignable_roles($otherusers = false) {
560 if ($this->_assignableroles === null) {
561 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
564 if ($otherusers) {
565 if (!is_array($this->_assignablerolesothers)) {
566 $this->_assignablerolesothers = array();
567 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
568 foreach ($this->_assignableroles as $roleid=>$role) {
569 if (isset($courseviewroles[$roleid])) {
570 $this->_assignablerolesothers[$roleid] = $role;
574 return $this->_assignablerolesothers;
575 } else {
576 return $this->_assignableroles;
581 * Gets all of the groups for this course.
583 * @return array
585 public function get_all_groups() {
586 if ($this->_groups === null) {
587 $this->_groups = groups_get_all_groups($this->course->id);
588 foreach ($this->_groups as $gid=>$group) {
589 $this->_groups[$gid]->name = format_string($group->name);
592 return $this->_groups;
596 * Unenrols a user from the course given the users ue entry
598 * @global moodle_database $DB
599 * @param stdClass $ue
600 * @return bool
602 public function unenrol_user($ue) {
603 global $DB;
604 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
605 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
606 $plugin->unenrol_user($instance, $ue->userid);
607 return true;
609 return false;
613 * Given a user enrolment record this method returns the plugin and enrolment
614 * instance that relate to it.
616 * @param stdClass|int $userenrolment
617 * @return array array($instance, $plugin)
619 public function get_user_enrolment_components($userenrolment) {
620 global $DB;
621 if (is_numeric($userenrolment)) {
622 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
624 $instances = $this->get_enrolment_instances();
625 $plugins = $this->get_enrolment_plugins(false);
626 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
627 return array(false, false);
629 $instance = $instances[$userenrolment->enrolid];
630 $plugin = $plugins[$instance->enrol];
631 return array($instance, $plugin);
635 * Removes an assigned role from a user.
637 * @global moodle_database $DB
638 * @param int $userid
639 * @param int $roleid
640 * @return bool
642 public function unassign_role_from_user($userid, $roleid) {
643 global $DB;
644 // Admins may unassign any role, others only those they could assign.
645 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
646 if (defined('AJAX_SCRIPT')) {
647 throw new moodle_exception('invalidrole');
649 return false;
651 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
652 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
653 foreach ($ras as $ra) {
654 if ($ra->component) {
655 if (strpos($ra->component, 'enrol_') !== 0) {
656 continue;
658 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
659 continue;
661 if ($plugin->roles_protected()) {
662 continue;
665 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
667 return true;
671 * Assigns a role to a user.
673 * @param int $roleid
674 * @param int $userid
675 * @return int|false
677 public function assign_role_to_user($roleid, $userid) {
678 require_capability('moodle/role:assign', $this->context);
679 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
680 if (defined('AJAX_SCRIPT')) {
681 throw new moodle_exception('invalidrole');
683 return false;
685 return role_assign($roleid, $userid, $this->context->id, '', NULL);
689 * Adds a user to a group
691 * @param stdClass $user
692 * @param int $groupid
693 * @return bool
695 public function add_user_to_group($user, $groupid) {
696 require_capability('moodle/course:managegroups', $this->context);
697 $group = $this->get_group($groupid);
698 if (!$group) {
699 return false;
701 return groups_add_member($group->id, $user->id);
705 * Removes a user from a group
707 * @global moodle_database $DB
708 * @param StdClass $user
709 * @param int $groupid
710 * @return bool
712 public function remove_user_from_group($user, $groupid) {
713 global $DB;
714 require_capability('moodle/course:managegroups', $this->context);
715 $group = $this->get_group($groupid);
716 if (!groups_remove_member_allowed($group, $user)) {
717 return false;
719 if (!$group) {
720 return false;
722 return groups_remove_member($group, $user);
726 * Gets the requested group
728 * @param int $groupid
729 * @return stdClass|int
731 public function get_group($groupid) {
732 $groups = $this->get_all_groups();
733 if (!array_key_exists($groupid, $groups)) {
734 return false;
736 return $groups[$groupid];
740 * Edits an enrolment
742 * @param stdClass $userenrolment
743 * @param stdClass $data
744 * @return bool
746 public function edit_enrolment($userenrolment, $data) {
747 //Only allow editing if the user has the appropriate capability
748 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
749 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
750 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
751 if (!isset($data->status)) {
752 $data->status = $userenrolment->status;
754 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
755 return true;
757 return false;
761 * Returns the current enrolment filter that is being applied by this class
762 * @return string
764 public function get_enrolment_filter() {
765 return $this->instancefilter;
769 * Gets the roles assigned to this user that are applicable for this course.
771 * @param int $userid
772 * @return array
774 public function get_user_roles($userid) {
775 $roles = array();
776 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
777 $plugins = $this->get_enrolment_plugins(false);
778 foreach ($ras as $ra) {
779 if ($ra->contextid != $this->context->id) {
780 if (!array_key_exists($ra->roleid, $roles)) {
781 $roles[$ra->roleid] = null;
783 // higher ras, course always takes precedence
784 continue;
786 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
787 continue;
789 $changeable = true;
790 if ($ra->component) {
791 $changeable = false;
792 if (strpos($ra->component, 'enrol_') === 0) {
793 $plugin = substr($ra->component, 6);
794 if (isset($plugins[$plugin])) {
795 $changeable = !$plugins[$plugin]->roles_protected();
800 $roles[$ra->roleid] = $changeable;
802 return $roles;
806 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
808 * @global moodle_database $DB
809 * @param int $userid
810 * @return array
812 public function get_user_enrolments($userid) {
813 global $DB;
814 list($instancessql, $params, $filter) = $this->get_instance_sql();
815 $params['userid'] = $userid;
816 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
817 $instances = $this->get_enrolment_instances();
818 $plugins = $this->get_enrolment_plugins(false);
819 $inames = $this->get_enrolment_instance_names();
820 foreach ($userenrolments as &$ue) {
821 $ue->enrolmentinstance = $instances[$ue->enrolid];
822 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
823 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
825 return $userenrolments;
829 * Gets the groups this user belongs to
831 * @param int $userid
832 * @return array
834 public function get_user_groups($userid) {
835 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
839 * Retursn an array of params that would go into the URL to return to this
840 * exact page.
842 * @return array
844 public function get_url_params() {
845 $args = array(
846 'id' => $this->course->id
848 if (!empty($this->instancefilter)) {
849 $args['ifilter'] = $this->instancefilter;
851 if (!empty($this->rolefilter)) {
852 $args['role'] = $this->rolefilter;
854 if ($this->searchfilter !== '') {
855 $args['search'] = $this->searchfilter;
857 return $args;
861 * Returns the course this object is managing enrolments for
863 * @return stdClass
865 public function get_course() {
866 return $this->course;
870 * Returns the course context
872 * @return stdClass
874 public function get_context() {
875 return $this->context;
879 * Gets an array of other users in this course ready for display.
881 * Other users are users who have been assigned or inherited roles within this
882 * course but have not been enrolled.
884 * @param core_enrol_renderer $renderer
885 * @param moodle_url $pageurl
886 * @param string $sort
887 * @param string $direction ASC | DESC
888 * @param int $page Starting from 0
889 * @param int $perpage
890 * @return array
892 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
894 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
895 $roles = $this->get_all_roles();
896 $plugins = $this->get_enrolment_plugins(false);
898 $context = $this->get_context();
899 $now = time();
900 $extrafields = get_extra_user_fields($context);
902 $users = array();
903 foreach ($userroles as $userrole) {
904 $contextid = $userrole->contextid;
905 unset($userrole->contextid); // This would collide with user avatar.
906 if (!array_key_exists($userrole->id, $users)) {
907 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
909 $a = new stdClass;
910 $a->role = $roles[$userrole->roleid]->localname;
911 if ($contextid == $this->context->id) {
912 $changeable = true;
913 if ($userrole->component) {
914 $changeable = false;
915 if (strpos($userrole->component, 'enrol_') === 0) {
916 $plugin = substr($userrole->component, 6);
917 if (isset($plugins[$plugin])) {
918 $changeable = !$plugin[$plugin]->roles_protected();
922 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
923 } else {
924 $changeable = false;
925 switch ($userrole->contextlevel) {
926 case CONTEXT_COURSE :
927 // Meta course
928 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
929 break;
930 case CONTEXT_COURSECAT :
931 $roletext = get_string('rolefromcategory', 'enrol', $a);
932 break;
933 case CONTEXT_SYSTEM:
934 default:
935 $roletext = get_string('rolefromsystem', 'enrol', $a);
936 break;
939 if (!isset($users[$userrole->id]['roles'])) {
940 $users[$userrole->id]['roles'] = array();
942 $users[$userrole->id]['roles'][$userrole->roleid] = array(
943 'text' => $roletext,
944 'unchangeable' => !$changeable
947 return $users;
951 * Gets an array of users for display, this includes minimal user information
952 * as well as minimal information on the users roles, groups, and enrolments.
954 * @param core_enrol_renderer $renderer
955 * @param moodle_url $pageurl
956 * @param int $sort
957 * @param string $direction ASC or DESC
958 * @param int $page
959 * @param int $perpage
960 * @return array
962 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
963 $pageurl = $manager->get_moodlepage()->url;
964 $users = $this->get_users($sort, $direction, $page, $perpage);
966 $now = time();
967 $straddgroup = get_string('addgroup', 'group');
968 $strunenrol = get_string('unenrol', 'enrol');
969 $stredit = get_string('edit');
971 $allroles = $this->get_all_roles();
972 $assignable = $this->get_assignable_roles();
973 $allgroups = $this->get_all_groups();
974 $context = $this->get_context();
975 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
977 $url = new moodle_url($pageurl, $this->get_url_params());
978 $extrafields = get_extra_user_fields($context);
980 $enabledplugins = $this->get_enrolment_plugins(true);
982 $userdetails = array();
983 foreach ($users as $user) {
984 $details = $this->prepare_user_for_display($user, $extrafields, $now);
986 // Roles
987 $details['roles'] = array();
988 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
989 $unchangeable = !$rassignable;
990 if (!is_siteadmin() and !isset($assignable[$rid])) {
991 $unchangeable = true;
993 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>$unchangeable);
996 // Users
997 $usergroups = $this->get_user_groups($user->id);
998 $details['groups'] = array();
999 foreach($usergroups as $gid=>$unused) {
1000 $details['groups'][$gid] = $allgroups[$gid]->name;
1003 // Enrolments
1004 $details['enrolments'] = array();
1005 foreach ($this->get_user_enrolments($user->id) as $ue) {
1006 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1007 $details['enrolments'][$ue->id] = array(
1008 'text' => $ue->enrolmentinstancename,
1009 'period' => null,
1010 'dimmed' => true,
1011 'actions' => array()
1013 continue;
1014 } else if ($ue->timestart and $ue->timeend) {
1015 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1016 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
1017 } else if ($ue->timestart) {
1018 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1019 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1020 } else if ($ue->timeend) {
1021 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1022 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1023 } else {
1024 // If there is no start or end show when user was enrolled.
1025 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1026 $periodoutside = false;
1028 $details['enrolments'][$ue->id] = array(
1029 'text' => $ue->enrolmentinstancename,
1030 'period' => $period,
1031 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1032 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1035 $userdetails[$user->id] = $details;
1037 return $userdetails;
1041 * Prepare a user record for display
1043 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1044 * prepare user fields for display
1046 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1048 * @param object $user The user record
1049 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1050 * additional fields may be displayed
1051 * @param int $now The time used for lastaccess calculation
1052 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
1053 * additional fields from $extrafields
1055 private function prepare_user_for_display($user, $extrafields, $now) {
1056 $details = array(
1057 'userid' => $user->id,
1058 'courseid' => $this->get_course()->id,
1059 'picture' => new user_picture($user),
1060 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1061 'lastseen' => get_string('never'),
1063 foreach ($extrafields as $field) {
1064 $details[$field] = $user->{$field};
1067 if ($user->lastaccess) {
1068 $details['lastseen'] = format_time($now - $user->lastaccess);
1070 return $details;
1073 public function get_manual_enrol_buttons() {
1074 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1075 $buttons = array();
1076 foreach ($plugins as $plugin) {
1077 $newbutton = $plugin->get_manual_enrol_button($this);
1078 if (is_array($newbutton)) {
1079 $buttons += $newbutton;
1080 } else if ($newbutton instanceof enrol_user_button) {
1081 $buttons[] = $newbutton;
1084 return $buttons;
1087 public function has_instance($enrolpluginname) {
1088 // Make sure manual enrolments instance exists
1089 foreach ($this->get_enrolment_instances() as $instance) {
1090 if ($instance->enrol == $enrolpluginname) {
1091 return true;
1094 return false;
1098 * Returns the enrolment plugin that the course manager was being filtered to.
1100 * If no filter was being applied then this function returns false.
1102 * @return enrol_plugin
1104 public function get_filtered_enrolment_plugin() {
1105 $instances = $this->get_enrolment_instances();
1106 $plugins = $this->get_enrolment_plugins(false);
1108 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1109 return false;
1112 $instance = $instances[$this->instancefilter];
1113 return $plugins[$instance->enrol];
1117 * Returns and array of users + enrolment details.
1119 * Given an array of user id's this function returns and array of user enrolments for those users
1120 * as well as enough user information to display the users name and picture for each enrolment.
1122 * @global moodle_database $DB
1123 * @param array $userids
1124 * @return array
1126 public function get_users_enrolments(array $userids) {
1127 global $DB;
1129 $instances = $this->get_enrolment_instances();
1130 $plugins = $this->get_enrolment_plugins(false);
1132 if (!empty($this->instancefilter)) {
1133 $instancesql = ' = :instanceid';
1134 $instanceparams = array('instanceid' => $this->instancefilter);
1135 } else {
1136 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1139 $userfields = user_picture::fields('u');
1140 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1142 list($sort, $sortparams) = users_order_by_sql('u');
1144 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1145 FROM {user_enrolments} ue
1146 LEFT JOIN {user} u ON u.id = ue.userid
1147 WHERE ue.enrolid $instancesql AND
1148 u.id $idsql
1149 ORDER BY $sort";
1151 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1152 $users = array();
1153 foreach ($rs as $ue) {
1154 $user = user_picture::unalias($ue);
1155 $ue->id = $ue->ueid;
1156 unset($ue->ueid);
1157 if (!array_key_exists($user->id, $users)) {
1158 $user->enrolments = array();
1159 $users[$user->id] = $user;
1161 $ue->enrolmentinstance = $instances[$ue->enrolid];
1162 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1163 $users[$user->id]->enrolments[$ue->id] = $ue;
1165 $rs->close();
1166 return $users;
1171 * A button that is used to enrol users in a course
1173 * @copyright 2010 Sam Hemelryk
1174 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1176 class enrol_user_button extends single_button {
1179 * An array containing JS YUI modules required by this button
1180 * @var array
1182 protected $jsyuimodules = array();
1185 * An array containing JS initialisation calls required by this button
1186 * @var array
1188 protected $jsinitcalls = array();
1191 * An array strings required by JS for this button
1192 * @var array
1194 protected $jsstrings = array();
1197 * Initialises the new enrol_user_button
1199 * @staticvar int $count The number of enrol user buttons already created
1200 * @param moodle_url $url
1201 * @param string $label The text to display in the button
1202 * @param string $method Either post or get
1204 public function __construct(moodle_url $url, $label, $method = 'post') {
1205 static $count = 0;
1206 $count ++;
1207 parent::__construct($url, $label, $method);
1208 $this->class = 'singlebutton enrolusersbutton';
1209 $this->formid = 'enrolusersbutton-'.$count;
1213 * Adds a YUI module call that will be added to the page when the button is used.
1215 * @param string|array $modules One or more modules to require
1216 * @param string $function The JS function to call
1217 * @param array $arguments An array of arguments to pass to the function
1218 * @param string $galleryversion The YUI gallery version of any modules required
1219 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1221 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1222 $js = new stdClass;
1223 $js->modules = (array)$modules;
1224 $js->function = $function;
1225 $js->arguments = $arguments;
1226 $js->galleryversion = $galleryversion;
1227 $js->ondomready = $ondomready;
1228 $this->jsyuimodules[] = $js;
1232 * Adds a JS initialisation call to the page when the button is used.
1234 * @param string $function The function to call
1235 * @param array $extraarguments An array of arguments to pass to the function
1236 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1237 * @param array $module A module definition
1239 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1240 $js = new stdClass;
1241 $js->function = $function;
1242 $js->extraarguments = $extraarguments;
1243 $js->ondomready = $ondomready;
1244 $js->module = $module;
1245 $this->jsinitcalls[] = $js;
1249 * Requires strings for JS that will be loaded when the button is used.
1251 * @param type $identifiers
1252 * @param string $component
1253 * @param mixed $a
1255 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1256 $string = new stdClass;
1257 $string->identifiers = (array)$identifiers;
1258 $string->component = $component;
1259 $string->a = $a;
1260 $this->jsstrings[] = $string;
1264 * Initialises the JS that is required by this button
1266 * @param moodle_page $page
1268 public function initialise_js(moodle_page $page) {
1269 foreach ($this->jsyuimodules as $js) {
1270 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1272 foreach ($this->jsinitcalls as $js) {
1273 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1275 foreach ($this->jsstrings as $string) {
1276 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1282 * User enrolment action
1284 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1285 * a user enrolment.
1287 * @copyright 2011 Sam Hemelryk
1288 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1290 class user_enrolment_action implements renderable {
1293 * The icon to display for the action
1294 * @var pix_icon
1296 protected $icon;
1299 * The title for the action
1300 * @var string
1302 protected $title;
1305 * The URL to the action
1306 * @var moodle_url
1308 protected $url;
1311 * An array of HTML attributes
1312 * @var array
1314 protected $attributes = array();
1317 * Constructor
1318 * @param pix_icon $icon
1319 * @param string $title
1320 * @param moodle_url $url
1321 * @param array $attributes
1323 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1324 $this->icon = $icon;
1325 $this->title = $title;
1326 $this->url = new moodle_url($url);
1327 if (!empty($attributes)) {
1328 $this->attributes = $attributes;
1330 $this->attributes['title'] = $title;
1334 * Returns the icon for this action
1335 * @return pix_icon
1337 public function get_icon() {
1338 return $this->icon;
1342 * Returns the title for this action
1343 * @return string
1345 public function get_title() {
1346 return $this->title;
1350 * Returns the URL for this action
1351 * @return moodle_url
1353 public function get_url() {
1354 return $this->url;
1358 * Returns the attributes to use for this action
1359 * @return array
1361 public function get_attributes() {
1362 return $this->attributes;
1366 class enrol_ajax_exception extends moodle_exception {
1368 * Constructor
1369 * @param string $errorcode The name of the string from error.php to print
1370 * @param string $module name of module
1371 * @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.
1372 * @param object $a Extra words and phrases that might be required in the error string
1373 * @param string $debuginfo optional debugging information
1375 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1376 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1381 * This class is used to manage a bulk operations for enrolment plugins.
1383 * @copyright 2011 Sam Hemelryk
1384 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1386 abstract class enrol_bulk_enrolment_operation {
1389 * The course enrolment manager
1390 * @var course_enrolment_manager
1392 protected $manager;
1395 * The enrolment plugin to which this operation belongs
1396 * @var enrol_plugin
1398 protected $plugin;
1401 * Contructor
1402 * @param course_enrolment_manager $manager
1403 * @param stdClass $plugin
1405 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1406 $this->manager = $manager;
1407 $this->plugin = $plugin;
1411 * Returns a moodleform used for this operation, or false if no form is required and the action
1412 * should be immediatly processed.
1414 * @param moodle_url|string $defaultaction
1415 * @param mixed $defaultcustomdata
1416 * @return enrol_bulk_enrolment_change_form|moodleform|false
1418 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1419 return false;
1423 * Returns the title to use for this bulk operation
1425 * @return string
1427 abstract public function get_title();
1430 * Returns the identifier for this bulk operation.
1431 * This should be the same identifier used by the plugins function when returning
1432 * all of its bulk operations.
1434 * @return string
1436 abstract public function get_identifier();
1439 * Processes the bulk operation on the given users
1441 * @param course_enrolment_manager $manager
1442 * @param array $users
1443 * @param stdClass $properties
1445 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);