Merge branch 'MDL-39717_25' of git://github.com/dmonllao/moodle into MOODLE_25_STABLE
[moodle.git] / enrol / locallib.php
bloba2039da679ed27fcc08e09241d271fc05d61a3eb
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains the course_enrolment_manager class which is used to interface
19 * with the functions that exist in enrollib.php in relation to a single course.
21 * @package core_enrol
22 * @copyright 2010 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**
29 * This class provides a targeted tied together means of interfacing the enrolment
30 * tasks together with a course.
32 * It is provided as a convenience more than anything else.
34 * @copyright 2010 Sam Hemelryk
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class course_enrolment_manager {
39 /**
40 * The course context
41 * @var stdClass
43 protected $context;
44 /**
45 * The course we are managing enrolments for
46 * @var stdClass
48 protected $course = null;
49 /**
50 * Limits the focus of the manager to one enrolment plugin instance
51 * @var string
53 protected $instancefilter = null;
54 /**
55 * Limits the focus of the manager to users with specified role
56 * @var int
58 protected $rolefilter = 0;
59 /**
60 * Limits the focus of the manager to users who match search string
61 * @var string
63 protected $searchfilter = '';
65 /**
66 * The total number of users enrolled in the course
67 * Populated by course_enrolment_manager::get_total_users
68 * @var int
70 protected $totalusers = null;
71 /**
72 * An array of users currently enrolled in the course
73 * Populated by course_enrolment_manager::get_users
74 * @var array
76 protected $users = array();
78 /**
79 * An array of users who have roles within this course but who have not
80 * been enrolled in the course
81 * @var array
83 protected $otherusers = array();
85 /**
86 * The total number of users who hold a role within the course but who
87 * arn't enrolled.
88 * @var int
90 protected $totalotherusers = null;
92 /**
93 * The current moodle_page object
94 * @var moodle_page
96 protected $moodlepage = null;
98 /**#@+
99 * These variables are used to cache the information this class uses
100 * please never use these directly instead use their get_ counterparts.
101 * @access private
102 * @var array
104 private $_instancessql = null;
105 private $_instances = null;
106 private $_inames = null;
107 private $_plugins = null;
108 private $_allplugins = null;
109 private $_roles = null;
110 private $_assignableroles = null;
111 private $_assignablerolesothers = null;
112 private $_groups = null;
113 /**#@-*/
116 * Constructs the course enrolment manager
118 * @param moodle_page $moodlepage
119 * @param stdClass $course
120 * @param string $instancefilter
121 * @param int $rolefilter If non-zero, filters to users with specified role
122 * @param string $searchfilter If non-blank, filters to users with search text
124 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
125 $rolefilter = 0, $searchfilter = '') {
126 $this->moodlepage = $moodlepage;
127 $this->context = context_course::instance($course->id);
128 $this->course = $course;
129 $this->instancefilter = $instancefilter;
130 $this->rolefilter = $rolefilter;
131 $this->searchfilter = $searchfilter;
135 * Returns the current moodle page
136 * @return moodle_page
138 public function get_moodlepage() {
139 return $this->moodlepage;
143 * Returns the total number of enrolled users in the course.
145 * If a filter was specificed this will be the total number of users enrolled
146 * in this course by means of that instance.
148 * @global moodle_database $DB
149 * @return int
151 public function get_total_users() {
152 global $DB;
153 if ($this->totalusers === null) {
154 list($instancessql, $params, $filter) = $this->get_instance_sql();
155 list($filtersql, $moreparams) = $this->get_filter_sql();
156 $params += $moreparams;
157 $sqltotal = "SELECT COUNT(DISTINCT u.id)
158 FROM {user} u
159 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
160 JOIN {enrol} e ON (e.id = ue.enrolid)
161 WHERE $filtersql";
162 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
164 return $this->totalusers;
168 * Returns the total number of enrolled users in the course.
170 * If a filter was specificed this will be the total number of users enrolled
171 * in this course by means of that instance.
173 * @global moodle_database $DB
174 * @return int
176 public function get_total_other_users() {
177 global $DB;
178 if ($this->totalotherusers === null) {
179 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
180 $params['courseid'] = $this->course->id;
181 $sql = "SELECT COUNT(DISTINCT u.id)
182 FROM {role_assignments} ra
183 JOIN {user} u ON u.id = ra.userid
184 JOIN {context} ctx ON ra.contextid = ctx.id
185 LEFT JOIN (
186 SELECT ue.id, ue.userid
187 FROM {user_enrolments} ue
188 LEFT JOIN {enrol} e ON e.id=ue.enrolid
189 WHERE e.courseid = :courseid
190 ) ue ON ue.userid=u.id
191 WHERE ctx.id $ctxcondition AND
192 ue.id IS NULL";
193 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
195 return $this->totalotherusers;
199 * Gets all of the users enrolled in this course.
201 * If a filter was specified this will be the users who were enrolled
202 * in this course by means of that instance. If role or search filters were
203 * specified then these will also be applied.
205 * @global moodle_database $DB
206 * @param string $sort
207 * @param string $direction ASC or DESC
208 * @param int $page First page should be 0
209 * @param int $perpage Defaults to 25
210 * @return array
212 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
213 global $DB;
214 if ($direction !== 'ASC') {
215 $direction = 'DESC';
217 $key = md5("$sort-$direction-$page-$perpage");
218 if (!array_key_exists($key, $this->users)) {
219 list($instancessql, $params, $filter) = $this->get_instance_sql();
220 list($filtersql, $moreparams) = $this->get_filter_sql();
221 $params += $moreparams;
222 $extrafields = get_extra_user_fields($this->get_context());
223 $extrafields[] = 'lastaccess';
224 $ufields = user_picture::fields('u', $extrafields);
225 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
226 FROM {user} u
227 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
228 JOIN {enrol} e ON (e.id = ue.enrolid)
229 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)
230 WHERE $filtersql";
231 if ($sort === 'firstname') {
232 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
233 } else if ($sort === 'lastname') {
234 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
235 } else if ($sort === 'email') {
236 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
237 } else if ($sort === 'lastseen') {
238 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
240 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
242 return $this->users[$key];
246 * Obtains WHERE clause to filter results by defined search and role filter
247 * (instance filter is handled separately in JOIN clause, see
248 * get_instance_sql).
250 * @return array Two-element array with SQL and params for WHERE clause
252 protected function get_filter_sql() {
253 global $DB;
255 // Search condition.
256 $extrafields = get_extra_user_fields($this->get_context());
257 list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
259 // Role condition.
260 if ($this->rolefilter) {
261 // Get context SQL.
262 $contextids = $this->context->get_parent_context_ids();
263 $contextids[] = $this->context->id;
264 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
265 $params += $contextparams;
267 // Role check condition.
268 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
269 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
270 $params['roleid'] = $this->rolefilter;
273 return array($sql, $params);
277 * Gets and array of other users.
279 * Other users are users who have been assigned roles or inherited roles
280 * within this course but who have not been enrolled in the course
282 * @global moodle_database $DB
283 * @param string $sort
284 * @param string $direction
285 * @param int $page
286 * @param int $perpage
287 * @return array
289 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
290 global $DB;
291 if ($direction !== 'ASC') {
292 $direction = 'DESC';
294 $key = md5("$sort-$direction-$page-$perpage");
295 if (!array_key_exists($key, $this->otherusers)) {
296 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
297 $params['courseid'] = $this->course->id;
298 $params['cid'] = $this->course->id;
299 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
300 FROM {role_assignments} ra
301 JOIN {user} u ON u.id = ra.userid
302 JOIN {context} ctx ON ra.contextid = ctx.id
303 LEFT JOIN (
304 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
305 FROM {user_enrolments} ue
306 LEFT JOIN {enrol} e ON e.id=ue.enrolid
307 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
308 WHERE e.courseid = :courseid
309 ) ue ON ue.userid=u.id
310 WHERE ctx.id $ctxcondition AND
311 ue.id IS NULL
312 ORDER BY u.$sort $direction, ctx.depth DESC";
313 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
315 return $this->otherusers[$key];
319 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
321 * @param string $search the search term, if any.
322 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
323 * @return array with three elements:
324 * string list of fields to SELECT,
325 * string contents of SQL WHERE clause,
326 * array query params. Note that the SQL snippets use named parameters.
328 protected function get_basic_search_conditions($search, $searchanywhere) {
329 global $DB, $CFG;
331 // Add some additional sensible conditions
332 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
333 $params = array('guestid' => $CFG->siteguest);
334 if (!empty($search)) {
335 $conditions = get_extra_user_fields($this->get_context());
336 $conditions[] = 'u.firstname';
337 $conditions[] = 'u.lastname';
338 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
339 if ($searchanywhere) {
340 $searchparam = '%' . $search . '%';
341 } else {
342 $searchparam = $search . '%';
344 $i = 0;
345 foreach ($conditions as $key => $condition) {
346 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
347 $params["con{$i}00"] = $searchparam;
348 $i++;
350 $tests[] = '(' . implode(' OR ', $conditions) . ')';
352 $wherecondition = implode(' AND ', $tests);
354 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
355 $extrafields[] = 'username';
356 $extrafields[] = 'lastaccess';
357 $ufields = user_picture::fields('u', $extrafields);
359 return array($ufields, $params, $wherecondition);
363 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
365 * @param string $search the search string, if any.
366 * @param string $fields the first bit of the SQL when returning some users.
367 * @param string $countfields fhe first bit of the SQL when counting the users.
368 * @param string $sql the bulk of the SQL statement.
369 * @param array $params query parameters.
370 * @param int $page which page number of the results to show.
371 * @param int $perpage number of users per page.
372 * @param int $addedenrollment number of users added to enrollment.
373 * @return array with two elememts:
374 * int total number of users matching the search.
375 * array of user objects returned by the query.
377 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
378 global $DB, $CFG;
380 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
381 $order = ' ORDER BY ' . $sort;
383 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
384 $availableusers = $DB->get_records_sql($fields . $sql . $order,
385 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
387 return array('totalusers' => $totalusers, 'users' => $availableusers);
391 * Gets an array of the users that can be enrolled in this course.
393 * @global moodle_database $DB
394 * @param int $enrolid
395 * @param string $search
396 * @param bool $searchanywhere
397 * @param int $page Defaults to 0
398 * @param int $perpage Defaults to 25
399 * @param int $addedenrollment Defaults to 0
400 * @return array Array(totalusers => int, users => array)
402 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
403 global $DB;
405 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
407 $fields = 'SELECT '.$ufields;
408 $countfields = 'SELECT COUNT(1)';
409 $sql = " FROM {user} u
410 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
411 WHERE $wherecondition
412 AND ue.id IS NULL";
413 $params['enrolid'] = $enrolid;
415 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
419 * Searches other users and returns paginated results
421 * @global moodle_database $DB
422 * @param string $search
423 * @param bool $searchanywhere
424 * @param int $page Starting at 0
425 * @param int $perpage
426 * @return array
428 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
429 global $DB, $CFG;
431 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
433 $fields = 'SELECT ' . $ufields;
434 $countfields = 'SELECT COUNT(u.id)';
435 $sql = " FROM {user} u
436 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
437 WHERE $wherecondition
438 AND ra.id IS NULL";
439 $params['contextid'] = $this->context->id;
441 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
445 * Gets an array containing some SQL to user for when selecting, params for
446 * that SQL, and the filter that was used in constructing the sql.
448 * @global moodle_database $DB
449 * @return string
451 protected function get_instance_sql() {
452 global $DB;
453 if ($this->_instancessql === null) {
454 $instances = $this->get_enrolment_instances();
455 $filter = $this->get_enrolment_filter();
456 if ($filter && array_key_exists($filter, $instances)) {
457 $sql = " = :ifilter";
458 $params = array('ifilter'=>$filter);
459 } else {
460 $filter = 0;
461 if ($instances) {
462 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
463 } else {
464 // no enabled instances, oops, we should probably say something
465 $sql = "= :never";
466 $params = array('never'=>-1);
469 $this->instancefilter = $filter;
470 $this->_instancessql = array($sql, $params, $filter);
472 return $this->_instancessql;
476 * Returns all of the enrolment instances for this course.
478 * NOTE: since 2.4 it includes instances of disabled plugins too.
480 * @return array
482 public function get_enrolment_instances() {
483 if ($this->_instances === null) {
484 $this->_instances = enrol_get_instances($this->course->id, false);
486 return $this->_instances;
490 * Returns the names for all of the enrolment instances for this course.
492 * NOTE: since 2.4 it includes instances of disabled plugins too.
494 * @return array
496 public function get_enrolment_instance_names() {
497 if ($this->_inames === null) {
498 $instances = $this->get_enrolment_instances();
499 $plugins = $this->get_enrolment_plugins(false);
500 foreach ($instances as $key=>$instance) {
501 if (!isset($plugins[$instance->enrol])) {
502 // weird, some broken stuff in plugin
503 unset($instances[$key]);
504 continue;
506 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
509 return $this->_inames;
513 * Gets all of the enrolment plugins that are active for this course.
515 * @param bool $onlyenabled return only enabled enrol plugins
516 * @return array
518 public function get_enrolment_plugins($onlyenabled = true) {
519 if ($this->_plugins === null) {
520 $this->_plugins = enrol_get_plugins(true);
523 if ($onlyenabled) {
524 return $this->_plugins;
527 if ($this->_allplugins === null) {
528 // Make sure we have the same objects in _allplugins and _plugins.
529 $this->_allplugins = $this->_plugins;
530 foreach (enrol_get_plugins(false) as $name=>$plugin) {
531 if (!isset($this->_allplugins[$name])) {
532 $this->_allplugins[$name] = $plugin;
537 return $this->_allplugins;
541 * Gets all of the roles this course can contain.
543 * @return array
545 public function get_all_roles() {
546 if ($this->_roles === null) {
547 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
549 return $this->_roles;
553 * Gets all of the assignable roles for this course.
555 * @return array
557 public function get_assignable_roles($otherusers = false) {
558 if ($this->_assignableroles === null) {
559 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
562 if ($otherusers) {
563 if (!is_array($this->_assignablerolesothers)) {
564 $this->_assignablerolesothers = array();
565 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
566 foreach ($this->_assignableroles as $roleid=>$role) {
567 if (isset($courseviewroles[$roleid])) {
568 $this->_assignablerolesothers[$roleid] = $role;
572 return $this->_assignablerolesothers;
573 } else {
574 return $this->_assignableroles;
579 * Gets all of the groups for this course.
581 * @return array
583 public function get_all_groups() {
584 if ($this->_groups === null) {
585 $this->_groups = groups_get_all_groups($this->course->id);
586 foreach ($this->_groups as $gid=>$group) {
587 $this->_groups[$gid]->name = format_string($group->name);
590 return $this->_groups;
594 * Unenrols a user from the course given the users ue entry
596 * @global moodle_database $DB
597 * @param stdClass $ue
598 * @return bool
600 public function unenrol_user($ue) {
601 global $DB;
602 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
603 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
604 $plugin->unenrol_user($instance, $ue->userid);
605 return true;
607 return false;
611 * Given a user enrolment record this method returns the plugin and enrolment
612 * instance that relate to it.
614 * @param stdClass|int $userenrolment
615 * @return array array($instance, $plugin)
617 public function get_user_enrolment_components($userenrolment) {
618 global $DB;
619 if (is_numeric($userenrolment)) {
620 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
622 $instances = $this->get_enrolment_instances();
623 $plugins = $this->get_enrolment_plugins(false);
624 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
625 return array(false, false);
627 $instance = $instances[$userenrolment->enrolid];
628 $plugin = $plugins[$instance->enrol];
629 return array($instance, $plugin);
633 * Removes an assigned role from a user.
635 * @global moodle_database $DB
636 * @param int $userid
637 * @param int $roleid
638 * @return bool
640 public function unassign_role_from_user($userid, $roleid) {
641 global $DB;
642 // Admins may unassign any role, others only those they could assign.
643 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
644 if (defined('AJAX_SCRIPT')) {
645 throw new moodle_exception('invalidrole');
647 return false;
649 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
650 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
651 foreach ($ras as $ra) {
652 if ($ra->component) {
653 if (strpos($ra->component, 'enrol_') !== 0) {
654 continue;
656 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
657 continue;
659 if ($plugin->roles_protected()) {
660 continue;
663 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
665 return true;
669 * Assigns a role to a user.
671 * @param int $roleid
672 * @param int $userid
673 * @return int|false
675 public function assign_role_to_user($roleid, $userid) {
676 require_capability('moodle/role:assign', $this->context);
677 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
678 if (defined('AJAX_SCRIPT')) {
679 throw new moodle_exception('invalidrole');
681 return false;
683 return role_assign($roleid, $userid, $this->context->id, '', NULL);
687 * Adds a user to a group
689 * @param stdClass $user
690 * @param int $groupid
691 * @return bool
693 public function add_user_to_group($user, $groupid) {
694 require_capability('moodle/course:managegroups', $this->context);
695 $group = $this->get_group($groupid);
696 if (!$group) {
697 return false;
699 return groups_add_member($group->id, $user->id);
703 * Removes a user from a group
705 * @global moodle_database $DB
706 * @param StdClass $user
707 * @param int $groupid
708 * @return bool
710 public function remove_user_from_group($user, $groupid) {
711 global $DB;
712 require_capability('moodle/course:managegroups', $this->context);
713 $group = $this->get_group($groupid);
714 if (!groups_remove_member_allowed($group, $user)) {
715 return false;
717 if (!$group) {
718 return false;
720 return groups_remove_member($group, $user);
724 * Gets the requested group
726 * @param int $groupid
727 * @return stdClass|int
729 public function get_group($groupid) {
730 $groups = $this->get_all_groups();
731 if (!array_key_exists($groupid, $groups)) {
732 return false;
734 return $groups[$groupid];
738 * Edits an enrolment
740 * @param stdClass $userenrolment
741 * @param stdClass $data
742 * @return bool
744 public function edit_enrolment($userenrolment, $data) {
745 //Only allow editing if the user has the appropriate capability
746 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
747 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
748 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
749 if (!isset($data->status)) {
750 $data->status = $userenrolment->status;
752 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
753 return true;
755 return false;
759 * Returns the current enrolment filter that is being applied by this class
760 * @return string
762 public function get_enrolment_filter() {
763 return $this->instancefilter;
767 * Gets the roles assigned to this user that are applicable for this course.
769 * @param int $userid
770 * @return array
772 public function get_user_roles($userid) {
773 $roles = array();
774 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
775 $plugins = $this->get_enrolment_plugins(false);
776 foreach ($ras as $ra) {
777 if ($ra->contextid != $this->context->id) {
778 if (!array_key_exists($ra->roleid, $roles)) {
779 $roles[$ra->roleid] = null;
781 // higher ras, course always takes precedence
782 continue;
784 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
785 continue;
787 $changeable = true;
788 if ($ra->component) {
789 $changeable = false;
790 if (strpos($ra->component, 'enrol_') === 0) {
791 $plugin = substr($ra->component, 6);
792 if (isset($plugins[$plugin])) {
793 $changeable = !$plugins[$plugin]->roles_protected();
798 $roles[$ra->roleid] = $changeable;
800 return $roles;
804 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
806 * @global moodle_database $DB
807 * @param int $userid
808 * @return array
810 public function get_user_enrolments($userid) {
811 global $DB;
812 list($instancessql, $params, $filter) = $this->get_instance_sql();
813 $params['userid'] = $userid;
814 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
815 $instances = $this->get_enrolment_instances();
816 $plugins = $this->get_enrolment_plugins(false);
817 $inames = $this->get_enrolment_instance_names();
818 foreach ($userenrolments as &$ue) {
819 $ue->enrolmentinstance = $instances[$ue->enrolid];
820 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
821 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
823 return $userenrolments;
827 * Gets the groups this user belongs to
829 * @param int $userid
830 * @return array
832 public function get_user_groups($userid) {
833 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
837 * Retursn an array of params that would go into the URL to return to this
838 * exact page.
840 * @return array
842 public function get_url_params() {
843 $args = array(
844 'id' => $this->course->id
846 if (!empty($this->instancefilter)) {
847 $args['ifilter'] = $this->instancefilter;
849 if (!empty($this->rolefilter)) {
850 $args['role'] = $this->rolefilter;
852 if ($this->searchfilter !== '') {
853 $args['search'] = $this->searchfilter;
855 return $args;
859 * Returns the course this object is managing enrolments for
861 * @return stdClass
863 public function get_course() {
864 return $this->course;
868 * Returns the course context
870 * @return stdClass
872 public function get_context() {
873 return $this->context;
877 * Gets an array of other users in this course ready for display.
879 * Other users are users who have been assigned or inherited roles within this
880 * course but have not been enrolled.
882 * @param core_enrol_renderer $renderer
883 * @param moodle_url $pageurl
884 * @param string $sort
885 * @param string $direction ASC | DESC
886 * @param int $page Starting from 0
887 * @param int $perpage
888 * @return array
890 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
892 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
893 $roles = $this->get_all_roles();
894 $plugins = $this->get_enrolment_plugins(false);
896 $context = $this->get_context();
897 $now = time();
898 $extrafields = get_extra_user_fields($context);
900 $users = array();
901 foreach ($userroles as $userrole) {
902 $contextid = $userrole->contextid;
903 unset($userrole->contextid); // This would collide with user avatar.
904 if (!array_key_exists($userrole->id, $users)) {
905 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
907 $a = new stdClass;
908 $a->role = $roles[$userrole->roleid]->localname;
909 if ($contextid == $this->context->id) {
910 $changeable = true;
911 if ($userrole->component) {
912 $changeable = false;
913 if (strpos($userrole->component, 'enrol_') === 0) {
914 $plugin = substr($userrole->component, 6);
915 if (isset($plugins[$plugin])) {
916 $changeable = !$plugin[$plugin]->roles_protected();
920 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
921 } else {
922 $changeable = false;
923 switch ($userrole->contextlevel) {
924 case CONTEXT_COURSE :
925 // Meta course
926 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
927 break;
928 case CONTEXT_COURSECAT :
929 $roletext = get_string('rolefromcategory', 'enrol', $a);
930 break;
931 case CONTEXT_SYSTEM:
932 default:
933 $roletext = get_string('rolefromsystem', 'enrol', $a);
934 break;
937 if (!isset($users[$userrole->id]['roles'])) {
938 $users[$userrole->id]['roles'] = array();
940 $users[$userrole->id]['roles'][$userrole->roleid] = array(
941 'text' => $roletext,
942 'unchangeable' => !$changeable
945 return $users;
949 * Gets an array of users for display, this includes minimal user information
950 * as well as minimal information on the users roles, groups, and enrolments.
952 * @param core_enrol_renderer $renderer
953 * @param moodle_url $pageurl
954 * @param int $sort
955 * @param string $direction ASC or DESC
956 * @param int $page
957 * @param int $perpage
958 * @return array
960 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
961 $pageurl = $manager->get_moodlepage()->url;
962 $users = $this->get_users($sort, $direction, $page, $perpage);
964 $now = time();
965 $straddgroup = get_string('addgroup', 'group');
966 $strunenrol = get_string('unenrol', 'enrol');
967 $stredit = get_string('edit');
969 $allroles = $this->get_all_roles();
970 $assignable = $this->get_assignable_roles();
971 $allgroups = $this->get_all_groups();
972 $context = $this->get_context();
973 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
975 $url = new moodle_url($pageurl, $this->get_url_params());
976 $extrafields = get_extra_user_fields($context);
978 $enabledplugins = $this->get_enrolment_plugins(true);
980 $userdetails = array();
981 foreach ($users as $user) {
982 $details = $this->prepare_user_for_display($user, $extrafields, $now);
984 // Roles
985 $details['roles'] = array();
986 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
987 $unchangeable = !$rassignable;
988 if (!is_siteadmin() and !isset($assignable[$rid])) {
989 $unchangeable = true;
991 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>$unchangeable);
994 // Users
995 $usergroups = $this->get_user_groups($user->id);
996 $details['groups'] = array();
997 foreach($usergroups as $gid=>$unused) {
998 $details['groups'][$gid] = $allgroups[$gid]->name;
1001 // Enrolments
1002 $details['enrolments'] = array();
1003 foreach ($this->get_user_enrolments($user->id) as $ue) {
1004 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1005 $details['enrolments'][$ue->id] = array(
1006 'text' => $ue->enrolmentinstancename,
1007 'period' => null,
1008 'dimmed' => true,
1009 'actions' => array()
1011 continue;
1012 } else if ($ue->timestart and $ue->timeend) {
1013 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1014 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
1015 } else if ($ue->timestart) {
1016 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1017 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1018 } else if ($ue->timeend) {
1019 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1020 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1021 } else {
1022 // If there is no start or end show when user was enrolled.
1023 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1024 $periodoutside = false;
1026 $details['enrolments'][$ue->id] = array(
1027 'text' => $ue->enrolmentinstancename,
1028 'period' => $period,
1029 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1030 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1033 $userdetails[$user->id] = $details;
1035 return $userdetails;
1039 * Prepare a user record for display
1041 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1042 * prepare user fields for display
1044 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1046 * @param object $user The user record
1047 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1048 * additional fields may be displayed
1049 * @param int $now The time used for lastaccess calculation
1050 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
1051 * additional fields from $extrafields
1053 private function prepare_user_for_display($user, $extrafields, $now) {
1054 $details = array(
1055 'userid' => $user->id,
1056 'courseid' => $this->get_course()->id,
1057 'picture' => new user_picture($user),
1058 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1059 'lastseen' => get_string('never'),
1061 foreach ($extrafields as $field) {
1062 $details[$field] = $user->{$field};
1065 if ($user->lastaccess) {
1066 $details['lastseen'] = format_time($now - $user->lastaccess);
1068 return $details;
1071 public function get_manual_enrol_buttons() {
1072 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1073 $buttons = array();
1074 foreach ($plugins as $plugin) {
1075 $newbutton = $plugin->get_manual_enrol_button($this);
1076 if (is_array($newbutton)) {
1077 $buttons += $newbutton;
1078 } else if ($newbutton instanceof enrol_user_button) {
1079 $buttons[] = $newbutton;
1082 return $buttons;
1085 public function has_instance($enrolpluginname) {
1086 // Make sure manual enrolments instance exists
1087 foreach ($this->get_enrolment_instances() as $instance) {
1088 if ($instance->enrol == $enrolpluginname) {
1089 return true;
1092 return false;
1096 * Returns the enrolment plugin that the course manager was being filtered to.
1098 * If no filter was being applied then this function returns false.
1100 * @return enrol_plugin
1102 public function get_filtered_enrolment_plugin() {
1103 $instances = $this->get_enrolment_instances();
1104 $plugins = $this->get_enrolment_plugins(false);
1106 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1107 return false;
1110 $instance = $instances[$this->instancefilter];
1111 return $plugins[$instance->enrol];
1115 * Returns and array of users + enrolment details.
1117 * Given an array of user id's this function returns and array of user enrolments for those users
1118 * as well as enough user information to display the users name and picture for each enrolment.
1120 * @global moodle_database $DB
1121 * @param array $userids
1122 * @return array
1124 public function get_users_enrolments(array $userids) {
1125 global $DB;
1127 $instances = $this->get_enrolment_instances();
1128 $plugins = $this->get_enrolment_plugins(false);
1130 if (!empty($this->instancefilter)) {
1131 $instancesql = ' = :instanceid';
1132 $instanceparams = array('instanceid' => $this->instancefilter);
1133 } else {
1134 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1137 $userfields = user_picture::fields('u');
1138 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1140 list($sort, $sortparams) = users_order_by_sql('u');
1142 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1143 FROM {user_enrolments} ue
1144 LEFT JOIN {user} u ON u.id = ue.userid
1145 WHERE ue.enrolid $instancesql AND
1146 u.id $idsql
1147 ORDER BY $sort";
1149 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1150 $users = array();
1151 foreach ($rs as $ue) {
1152 $user = user_picture::unalias($ue);
1153 $ue->id = $ue->ueid;
1154 unset($ue->ueid);
1155 if (!array_key_exists($user->id, $users)) {
1156 $user->enrolments = array();
1157 $users[$user->id] = $user;
1159 $ue->enrolmentinstance = $instances[$ue->enrolid];
1160 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1161 $users[$user->id]->enrolments[$ue->id] = $ue;
1163 $rs->close();
1164 return $users;
1169 * A button that is used to enrol users in a course
1171 * @copyright 2010 Sam Hemelryk
1172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1174 class enrol_user_button extends single_button {
1177 * An array containing JS YUI modules required by this button
1178 * @var array
1180 protected $jsyuimodules = array();
1183 * An array containing JS initialisation calls required by this button
1184 * @var array
1186 protected $jsinitcalls = array();
1189 * An array strings required by JS for this button
1190 * @var array
1192 protected $jsstrings = array();
1195 * Initialises the new enrol_user_button
1197 * @staticvar int $count The number of enrol user buttons already created
1198 * @param moodle_url $url
1199 * @param string $label The text to display in the button
1200 * @param string $method Either post or get
1202 public function __construct(moodle_url $url, $label, $method = 'post') {
1203 static $count = 0;
1204 $count ++;
1205 parent::__construct($url, $label, $method);
1206 $this->class = 'singlebutton enrolusersbutton';
1207 $this->formid = 'enrolusersbutton-'.$count;
1211 * Adds a YUI module call that will be added to the page when the button is used.
1213 * @param string|array $modules One or more modules to require
1214 * @param string $function The JS function to call
1215 * @param array $arguments An array of arguments to pass to the function
1216 * @param string $galleryversion The YUI gallery version of any modules required
1217 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1219 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1220 $js = new stdClass;
1221 $js->modules = (array)$modules;
1222 $js->function = $function;
1223 $js->arguments = $arguments;
1224 $js->galleryversion = $galleryversion;
1225 $js->ondomready = $ondomready;
1226 $this->jsyuimodules[] = $js;
1230 * Adds a JS initialisation call to the page when the button is used.
1232 * @param string $function The function to call
1233 * @param array $extraarguments An array of arguments to pass to the function
1234 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1235 * @param array $module A module definition
1237 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1238 $js = new stdClass;
1239 $js->function = $function;
1240 $js->extraarguments = $extraarguments;
1241 $js->ondomready = $ondomready;
1242 $js->module = $module;
1243 $this->jsinitcalls[] = $js;
1247 * Requires strings for JS that will be loaded when the button is used.
1249 * @param type $identifiers
1250 * @param string $component
1251 * @param mixed $a
1253 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1254 $string = new stdClass;
1255 $string->identifiers = (array)$identifiers;
1256 $string->component = $component;
1257 $string->a = $a;
1258 $this->jsstrings[] = $string;
1262 * Initialises the JS that is required by this button
1264 * @param moodle_page $page
1266 public function initialise_js(moodle_page $page) {
1267 foreach ($this->jsyuimodules as $js) {
1268 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1270 foreach ($this->jsinitcalls as $js) {
1271 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1273 foreach ($this->jsstrings as $string) {
1274 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1280 * User enrolment action
1282 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1283 * a user enrolment.
1285 * @copyright 2011 Sam Hemelryk
1286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1288 class user_enrolment_action implements renderable {
1291 * The icon to display for the action
1292 * @var pix_icon
1294 protected $icon;
1297 * The title for the action
1298 * @var string
1300 protected $title;
1303 * The URL to the action
1304 * @var moodle_url
1306 protected $url;
1309 * An array of HTML attributes
1310 * @var array
1312 protected $attributes = array();
1315 * Constructor
1316 * @param pix_icon $icon
1317 * @param string $title
1318 * @param moodle_url $url
1319 * @param array $attributes
1321 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1322 $this->icon = $icon;
1323 $this->title = $title;
1324 $this->url = new moodle_url($url);
1325 if (!empty($attributes)) {
1326 $this->attributes = $attributes;
1328 $this->attributes['title'] = $title;
1332 * Returns the icon for this action
1333 * @return pix_icon
1335 public function get_icon() {
1336 return $this->icon;
1340 * Returns the title for this action
1341 * @return string
1343 public function get_title() {
1344 return $this->title;
1348 * Returns the URL for this action
1349 * @return moodle_url
1351 public function get_url() {
1352 return $this->url;
1356 * Returns the attributes to use for this action
1357 * @return array
1359 public function get_attributes() {
1360 return $this->attributes;
1364 class enrol_ajax_exception extends moodle_exception {
1366 * Constructor
1367 * @param string $errorcode The name of the string from error.php to print
1368 * @param string $module name of module
1369 * @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.
1370 * @param object $a Extra words and phrases that might be required in the error string
1371 * @param string $debuginfo optional debugging information
1373 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1374 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1379 * This class is used to manage a bulk operations for enrolment plugins.
1381 * @copyright 2011 Sam Hemelryk
1382 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1384 abstract class enrol_bulk_enrolment_operation {
1387 * The course enrolment manager
1388 * @var course_enrolment_manager
1390 protected $manager;
1393 * The enrolment plugin to which this operation belongs
1394 * @var enrol_plugin
1396 protected $plugin;
1399 * Contructor
1400 * @param course_enrolment_manager $manager
1401 * @param stdClass $plugin
1403 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1404 $this->manager = $manager;
1405 $this->plugin = $plugin;
1409 * Returns a moodleform used for this operation, or false if no form is required and the action
1410 * should be immediatly processed.
1412 * @param moodle_url|string $defaultaction
1413 * @param mixed $defaultcustomdata
1414 * @return enrol_bulk_enrolment_change_form|moodleform|false
1416 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1417 return false;
1421 * Returns the title to use for this bulk operation
1423 * @return string
1425 abstract public function get_title();
1428 * Returns the identifier for this bulk operation.
1429 * This should be the same identifier used by the plugins function when returning
1430 * all of its bulk operations.
1432 * @return string
1434 abstract public function get_identifier();
1437 * Processes the bulk operation on the given users
1439 * @param course_enrolment_manager $manager
1440 * @param array $users
1441 * @param stdClass $properties
1443 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);