Moodle release 2.8rc1
[moodle.git] / enrol / locallib.php
blob433f6851ad6d6fa019dde7e7a0d9d9f0ae8177cc
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 = '';
64 /**
65 * Limits the focus of the manager to users in specified group
66 * @var int
68 protected $groupfilter = 0;
69 /**
70 * Limits the focus of the manager to users who match status active/inactive
71 * @var int
73 protected $statusfilter = -1;
75 /**
76 * The total number of users enrolled in the course
77 * Populated by course_enrolment_manager::get_total_users
78 * @var int
80 protected $totalusers = null;
81 /**
82 * An array of users currently enrolled in the course
83 * Populated by course_enrolment_manager::get_users
84 * @var array
86 protected $users = array();
88 /**
89 * An array of users who have roles within this course but who have not
90 * been enrolled in the course
91 * @var array
93 protected $otherusers = array();
95 /**
96 * The total number of users who hold a role within the course but who
97 * arn't enrolled.
98 * @var int
100 protected $totalotherusers = null;
103 * The current moodle_page object
104 * @var moodle_page
106 protected $moodlepage = null;
108 /**#@+
109 * These variables are used to cache the information this class uses
110 * please never use these directly instead use their get_ counterparts.
111 * @access private
112 * @var array
114 private $_instancessql = null;
115 private $_instances = null;
116 private $_inames = null;
117 private $_plugins = null;
118 private $_allplugins = null;
119 private $_roles = null;
120 private $_assignableroles = null;
121 private $_assignablerolesothers = null;
122 private $_groups = null;
123 /**#@-*/
126 * Constructs the course enrolment manager
128 * @param moodle_page $moodlepage
129 * @param stdClass $course
130 * @param string $instancefilter
131 * @param int $rolefilter If non-zero, filters to users with specified role
132 * @param string $searchfilter If non-blank, filters to users with search text
133 * @param int $groupfilter if non-zero, filter users with specified group
134 * @param int $statusfilter if not -1, filter users with active/inactive enrollment.
136 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
137 $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
138 $this->moodlepage = $moodlepage;
139 $this->context = context_course::instance($course->id);
140 $this->course = $course;
141 $this->instancefilter = $instancefilter;
142 $this->rolefilter = $rolefilter;
143 $this->searchfilter = $searchfilter;
144 $this->groupfilter = $groupfilter;
145 $this->statusfilter = $statusfilter;
149 * Returns the current moodle page
150 * @return moodle_page
152 public function get_moodlepage() {
153 return $this->moodlepage;
157 * Returns the total number of enrolled users in the course.
159 * If a filter was specificed this will be the total number of users enrolled
160 * in this course by means of that instance.
162 * @global moodle_database $DB
163 * @return int
165 public function get_total_users() {
166 global $DB;
167 if ($this->totalusers === null) {
168 list($instancessql, $params, $filter) = $this->get_instance_sql();
169 list($filtersql, $moreparams) = $this->get_filter_sql();
170 $params += $moreparams;
171 $sqltotal = "SELECT COUNT(DISTINCT u.id)
172 FROM {user} u
173 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
174 JOIN {enrol} e ON (e.id = ue.enrolid)
175 LEFT JOIN {groups_members} gm ON u.id = gm.userid
176 WHERE $filtersql";
177 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
179 return $this->totalusers;
183 * Returns the total number of enrolled users in the course.
185 * If a filter was specificed this will be the total number of users enrolled
186 * in this course by means of that instance.
188 * @global moodle_database $DB
189 * @return int
191 public function get_total_other_users() {
192 global $DB;
193 if ($this->totalotherusers === null) {
194 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
195 $params['courseid'] = $this->course->id;
196 $sql = "SELECT COUNT(DISTINCT u.id)
197 FROM {role_assignments} ra
198 JOIN {user} u ON u.id = ra.userid
199 JOIN {context} ctx ON ra.contextid = ctx.id
200 LEFT JOIN (
201 SELECT ue.id, ue.userid
202 FROM {user_enrolments} ue
203 LEFT JOIN {enrol} e ON e.id=ue.enrolid
204 WHERE e.courseid = :courseid
205 ) ue ON ue.userid=u.id
206 WHERE ctx.id $ctxcondition AND
207 ue.id IS NULL";
208 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
210 return $this->totalotherusers;
214 * Gets all of the users enrolled in this course.
216 * If a filter was specified this will be the users who were enrolled
217 * in this course by means of that instance. If role or search filters were
218 * specified then these will also be applied.
220 * @global moodle_database $DB
221 * @param string $sort
222 * @param string $direction ASC or DESC
223 * @param int $page First page should be 0
224 * @param int $perpage Defaults to 25
225 * @return array
227 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
228 global $DB;
229 if ($direction !== 'ASC') {
230 $direction = 'DESC';
232 $key = md5("$sort-$direction-$page-$perpage");
233 if (!array_key_exists($key, $this->users)) {
234 list($instancessql, $params, $filter) = $this->get_instance_sql();
235 list($filtersql, $moreparams) = $this->get_filter_sql();
236 $params += $moreparams;
237 $extrafields = get_extra_user_fields($this->get_context());
238 $extrafields[] = 'lastaccess';
239 $ufields = user_picture::fields('u', $extrafields);
240 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
241 FROM {user} u
242 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
243 JOIN {enrol} e ON (e.id = ue.enrolid)
244 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)
245 LEFT JOIN {groups_members} gm ON u.id = gm.userid
246 WHERE $filtersql
247 ORDER BY u.$sort $direction";
248 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
250 return $this->users[$key];
254 * Obtains WHERE clause to filter results by defined search and role filter
255 * (instance filter is handled separately in JOIN clause, see
256 * get_instance_sql).
258 * @return array Two-element array with SQL and params for WHERE clause
260 protected function get_filter_sql() {
261 global $DB;
263 // Search condition.
264 $extrafields = get_extra_user_fields($this->get_context());
265 list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
267 // Role condition.
268 if ($this->rolefilter) {
269 // Get context SQL.
270 $contextids = $this->context->get_parent_context_ids();
271 $contextids[] = $this->context->id;
272 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
273 $params += $contextparams;
275 // Role check condition.
276 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
277 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
278 $params['roleid'] = $this->rolefilter;
281 // Group condition.
282 if ($this->groupfilter) {
283 $sql .= " AND gm.groupid = :groupid";
284 $params['groupid'] = $this->groupfilter;
287 // Status condition.
288 if ($this->statusfilter === ENROL_USER_ACTIVE) {
289 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
290 AND (ue.timeend = 0 OR ue.timeend > :now2)";
291 $now = round(time(), -2); // rounding helps caching in DB
292 $params += array('enabled' => ENROL_INSTANCE_ENABLED,
293 'active' => ENROL_USER_ACTIVE,
294 'now1' => $now,
295 'now2' => $now);
296 } else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
297 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
298 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
299 $now = round(time(), -2); // rounding helps caching in DB
300 $params += array('disabled' => ENROL_INSTANCE_DISABLED,
301 'inactive' => ENROL_USER_SUSPENDED,
302 'now1' => $now,
303 'now2' => $now);
306 return array($sql, $params);
310 * Gets and array of other users.
312 * Other users are users who have been assigned roles or inherited roles
313 * within this course but who have not been enrolled in the course
315 * @global moodle_database $DB
316 * @param string $sort
317 * @param string $direction
318 * @param int $page
319 * @param int $perpage
320 * @return array
322 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
323 global $DB;
324 if ($direction !== 'ASC') {
325 $direction = 'DESC';
327 $key = md5("$sort-$direction-$page-$perpage");
328 if (!array_key_exists($key, $this->otherusers)) {
329 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
330 $params['courseid'] = $this->course->id;
331 $params['cid'] = $this->course->id;
332 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
333 FROM {role_assignments} ra
334 JOIN {user} u ON u.id = ra.userid
335 JOIN {context} ctx ON ra.contextid = ctx.id
336 LEFT JOIN (
337 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
338 FROM {user_enrolments} ue
339 LEFT JOIN {enrol} e ON e.id=ue.enrolid
340 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
341 WHERE e.courseid = :courseid
342 ) ue ON ue.userid=u.id
343 WHERE ctx.id $ctxcondition AND
344 ue.id IS NULL
345 ORDER BY u.$sort $direction, ctx.depth DESC";
346 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
348 return $this->otherusers[$key];
352 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
354 * @param string $search the search term, if any.
355 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
356 * @return array with three elements:
357 * string list of fields to SELECT,
358 * string contents of SQL WHERE clause,
359 * array query params. Note that the SQL snippets use named parameters.
361 protected function get_basic_search_conditions($search, $searchanywhere) {
362 global $DB, $CFG;
364 // Add some additional sensible conditions
365 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
366 $params = array('guestid' => $CFG->siteguest);
367 if (!empty($search)) {
368 $conditions = get_extra_user_fields($this->get_context());
369 $conditions[] = 'u.firstname';
370 $conditions[] = 'u.lastname';
371 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
372 if ($searchanywhere) {
373 $searchparam = '%' . $search . '%';
374 } else {
375 $searchparam = $search . '%';
377 $i = 0;
378 foreach ($conditions as $key => $condition) {
379 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
380 $params["con{$i}00"] = $searchparam;
381 $i++;
383 $tests[] = '(' . implode(' OR ', $conditions) . ')';
385 $wherecondition = implode(' AND ', $tests);
387 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
388 $extrafields[] = 'username';
389 $extrafields[] = 'lastaccess';
390 $ufields = user_picture::fields('u', $extrafields);
392 return array($ufields, $params, $wherecondition);
396 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
398 * @param string $search the search string, if any.
399 * @param string $fields the first bit of the SQL when returning some users.
400 * @param string $countfields fhe first bit of the SQL when counting the users.
401 * @param string $sql the bulk of the SQL statement.
402 * @param array $params query parameters.
403 * @param int $page which page number of the results to show.
404 * @param int $perpage number of users per page.
405 * @param int $addedenrollment number of users added to enrollment.
406 * @return array with two elememts:
407 * int total number of users matching the search.
408 * array of user objects returned by the query.
410 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
411 global $DB, $CFG;
413 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
414 $order = ' ORDER BY ' . $sort;
416 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
417 $availableusers = $DB->get_records_sql($fields . $sql . $order,
418 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
420 return array('totalusers' => $totalusers, 'users' => $availableusers);
424 * Gets an array of the users that can be enrolled in this course.
426 * @global moodle_database $DB
427 * @param int $enrolid
428 * @param string $search
429 * @param bool $searchanywhere
430 * @param int $page Defaults to 0
431 * @param int $perpage Defaults to 25
432 * @param int $addedenrollment Defaults to 0
433 * @return array Array(totalusers => int, users => array)
435 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
436 global $DB;
438 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
440 $fields = 'SELECT '.$ufields;
441 $countfields = 'SELECT COUNT(1)';
442 $sql = " FROM {user} u
443 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
444 WHERE $wherecondition
445 AND ue.id IS NULL";
446 $params['enrolid'] = $enrolid;
448 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
452 * Searches other users and returns paginated results
454 * @global moodle_database $DB
455 * @param string $search
456 * @param bool $searchanywhere
457 * @param int $page Starting at 0
458 * @param int $perpage
459 * @return array
461 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
462 global $DB, $CFG;
464 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
466 $fields = 'SELECT ' . $ufields;
467 $countfields = 'SELECT COUNT(u.id)';
468 $sql = " FROM {user} u
469 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
470 WHERE $wherecondition
471 AND ra.id IS NULL";
472 $params['contextid'] = $this->context->id;
474 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
478 * Gets an array containing some SQL to user for when selecting, params for
479 * that SQL, and the filter that was used in constructing the sql.
481 * @global moodle_database $DB
482 * @return string
484 protected function get_instance_sql() {
485 global $DB;
486 if ($this->_instancessql === null) {
487 $instances = $this->get_enrolment_instances();
488 $filter = $this->get_enrolment_filter();
489 if ($filter && array_key_exists($filter, $instances)) {
490 $sql = " = :ifilter";
491 $params = array('ifilter'=>$filter);
492 } else {
493 $filter = 0;
494 if ($instances) {
495 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
496 } else {
497 // no enabled instances, oops, we should probably say something
498 $sql = "= :never";
499 $params = array('never'=>-1);
502 $this->instancefilter = $filter;
503 $this->_instancessql = array($sql, $params, $filter);
505 return $this->_instancessql;
509 * Returns all of the enrolment instances for this course.
511 * NOTE: since 2.4 it includes instances of disabled plugins too.
513 * @return array
515 public function get_enrolment_instances() {
516 if ($this->_instances === null) {
517 $this->_instances = enrol_get_instances($this->course->id, false);
519 return $this->_instances;
523 * Returns the names for all of the enrolment instances for this course.
525 * NOTE: since 2.4 it includes instances of disabled plugins too.
527 * @return array
529 public function get_enrolment_instance_names() {
530 if ($this->_inames === null) {
531 $instances = $this->get_enrolment_instances();
532 $plugins = $this->get_enrolment_plugins(false);
533 foreach ($instances as $key=>$instance) {
534 if (!isset($plugins[$instance->enrol])) {
535 // weird, some broken stuff in plugin
536 unset($instances[$key]);
537 continue;
539 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
542 return $this->_inames;
546 * Gets all of the enrolment plugins that are active for this course.
548 * @param bool $onlyenabled return only enabled enrol plugins
549 * @return array
551 public function get_enrolment_plugins($onlyenabled = true) {
552 if ($this->_plugins === null) {
553 $this->_plugins = enrol_get_plugins(true);
556 if ($onlyenabled) {
557 return $this->_plugins;
560 if ($this->_allplugins === null) {
561 // Make sure we have the same objects in _allplugins and _plugins.
562 $this->_allplugins = $this->_plugins;
563 foreach (enrol_get_plugins(false) as $name=>$plugin) {
564 if (!isset($this->_allplugins[$name])) {
565 $this->_allplugins[$name] = $plugin;
570 return $this->_allplugins;
574 * Gets all of the roles this course can contain.
576 * @return array
578 public function get_all_roles() {
579 if ($this->_roles === null) {
580 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
582 return $this->_roles;
586 * Gets all of the assignable roles for this course.
588 * @return array
590 public function get_assignable_roles($otherusers = false) {
591 if ($this->_assignableroles === null) {
592 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
595 if ($otherusers) {
596 if (!is_array($this->_assignablerolesothers)) {
597 $this->_assignablerolesothers = array();
598 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
599 foreach ($this->_assignableroles as $roleid=>$role) {
600 if (isset($courseviewroles[$roleid])) {
601 $this->_assignablerolesothers[$roleid] = $role;
605 return $this->_assignablerolesothers;
606 } else {
607 return $this->_assignableroles;
612 * Gets all of the groups for this course.
614 * @return array
616 public function get_all_groups() {
617 if ($this->_groups === null) {
618 $this->_groups = groups_get_all_groups($this->course->id);
619 foreach ($this->_groups as $gid=>$group) {
620 $this->_groups[$gid]->name = format_string($group->name);
623 return $this->_groups;
627 * Unenrols a user from the course given the users ue entry
629 * @global moodle_database $DB
630 * @param stdClass $ue
631 * @return bool
633 public function unenrol_user($ue) {
634 global $DB;
635 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
636 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
637 $plugin->unenrol_user($instance, $ue->userid);
638 return true;
640 return false;
644 * Given a user enrolment record this method returns the plugin and enrolment
645 * instance that relate to it.
647 * @param stdClass|int $userenrolment
648 * @return array array($instance, $plugin)
650 public function get_user_enrolment_components($userenrolment) {
651 global $DB;
652 if (is_numeric($userenrolment)) {
653 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
655 $instances = $this->get_enrolment_instances();
656 $plugins = $this->get_enrolment_plugins(false);
657 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
658 return array(false, false);
660 $instance = $instances[$userenrolment->enrolid];
661 $plugin = $plugins[$instance->enrol];
662 return array($instance, $plugin);
666 * Removes an assigned role from a user.
668 * @global moodle_database $DB
669 * @param int $userid
670 * @param int $roleid
671 * @return bool
673 public function unassign_role_from_user($userid, $roleid) {
674 global $DB;
675 // Admins may unassign any role, others only those they could assign.
676 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
677 if (defined('AJAX_SCRIPT')) {
678 throw new moodle_exception('invalidrole');
680 return false;
682 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
683 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
684 foreach ($ras as $ra) {
685 if ($ra->component) {
686 if (strpos($ra->component, 'enrol_') !== 0) {
687 continue;
689 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
690 continue;
692 if ($plugin->roles_protected()) {
693 continue;
696 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
698 return true;
702 * Assigns a role to a user.
704 * @param int $roleid
705 * @param int $userid
706 * @return int|false
708 public function assign_role_to_user($roleid, $userid) {
709 require_capability('moodle/role:assign', $this->context);
710 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
711 if (defined('AJAX_SCRIPT')) {
712 throw new moodle_exception('invalidrole');
714 return false;
716 return role_assign($roleid, $userid, $this->context->id, '', NULL);
720 * Adds a user to a group
722 * @param stdClass $user
723 * @param int $groupid
724 * @return bool
726 public function add_user_to_group($user, $groupid) {
727 require_capability('moodle/course:managegroups', $this->context);
728 $group = $this->get_group($groupid);
729 if (!$group) {
730 return false;
732 return groups_add_member($group->id, $user->id);
736 * Removes a user from a group
738 * @global moodle_database $DB
739 * @param StdClass $user
740 * @param int $groupid
741 * @return bool
743 public function remove_user_from_group($user, $groupid) {
744 global $DB;
745 require_capability('moodle/course:managegroups', $this->context);
746 $group = $this->get_group($groupid);
747 if (!groups_remove_member_allowed($group, $user)) {
748 return false;
750 if (!$group) {
751 return false;
753 return groups_remove_member($group, $user);
757 * Gets the requested group
759 * @param int $groupid
760 * @return stdClass|int
762 public function get_group($groupid) {
763 $groups = $this->get_all_groups();
764 if (!array_key_exists($groupid, $groups)) {
765 return false;
767 return $groups[$groupid];
771 * Edits an enrolment
773 * @param stdClass $userenrolment
774 * @param stdClass $data
775 * @return bool
777 public function edit_enrolment($userenrolment, $data) {
778 //Only allow editing if the user has the appropriate capability
779 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
780 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
781 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
782 if (!isset($data->status)) {
783 $data->status = $userenrolment->status;
785 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
786 return true;
788 return false;
792 * Returns the current enrolment filter that is being applied by this class
793 * @return string
795 public function get_enrolment_filter() {
796 return $this->instancefilter;
800 * Gets the roles assigned to this user that are applicable for this course.
802 * @param int $userid
803 * @return array
805 public function get_user_roles($userid) {
806 $roles = array();
807 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
808 $plugins = $this->get_enrolment_plugins(false);
809 foreach ($ras as $ra) {
810 if ($ra->contextid != $this->context->id) {
811 if (!array_key_exists($ra->roleid, $roles)) {
812 $roles[$ra->roleid] = null;
814 // higher ras, course always takes precedence
815 continue;
817 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
818 continue;
820 $changeable = true;
821 if ($ra->component) {
822 $changeable = false;
823 if (strpos($ra->component, 'enrol_') === 0) {
824 $plugin = substr($ra->component, 6);
825 if (isset($plugins[$plugin])) {
826 $changeable = !$plugins[$plugin]->roles_protected();
831 $roles[$ra->roleid] = $changeable;
833 return $roles;
837 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
839 * @global moodle_database $DB
840 * @param int $userid
841 * @return array
843 public function get_user_enrolments($userid) {
844 global $DB;
845 list($instancessql, $params, $filter) = $this->get_instance_sql();
846 $params['userid'] = $userid;
847 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
848 $instances = $this->get_enrolment_instances();
849 $plugins = $this->get_enrolment_plugins(false);
850 $inames = $this->get_enrolment_instance_names();
851 foreach ($userenrolments as &$ue) {
852 $ue->enrolmentinstance = $instances[$ue->enrolid];
853 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
854 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
856 return $userenrolments;
860 * Gets the groups this user belongs to
862 * @param int $userid
863 * @return array
865 public function get_user_groups($userid) {
866 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
870 * Retursn an array of params that would go into the URL to return to this
871 * exact page.
873 * @return array
875 public function get_url_params() {
876 $args = array(
877 'id' => $this->course->id
879 if (!empty($this->instancefilter)) {
880 $args['ifilter'] = $this->instancefilter;
882 if (!empty($this->rolefilter)) {
883 $args['role'] = $this->rolefilter;
885 if ($this->searchfilter !== '') {
886 $args['search'] = $this->searchfilter;
888 if (!empty($this->groupfilter)) {
889 $args['group'] = $this->groupfilter;
891 if ($this->statusfilter !== -1) {
892 $args['status'] = $this->statusfilter;
894 return $args;
898 * Returns the course this object is managing enrolments for
900 * @return stdClass
902 public function get_course() {
903 return $this->course;
907 * Returns the course context
909 * @return stdClass
911 public function get_context() {
912 return $this->context;
916 * Gets an array of other users in this course ready for display.
918 * Other users are users who have been assigned or inherited roles within this
919 * course but have not been enrolled.
921 * @param core_enrol_renderer $renderer
922 * @param moodle_url $pageurl
923 * @param string $sort
924 * @param string $direction ASC | DESC
925 * @param int $page Starting from 0
926 * @param int $perpage
927 * @return array
929 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
931 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
932 $roles = $this->get_all_roles();
933 $plugins = $this->get_enrolment_plugins(false);
935 $context = $this->get_context();
936 $now = time();
937 $extrafields = get_extra_user_fields($context);
939 $users = array();
940 foreach ($userroles as $userrole) {
941 $contextid = $userrole->contextid;
942 unset($userrole->contextid); // This would collide with user avatar.
943 if (!array_key_exists($userrole->id, $users)) {
944 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
946 $a = new stdClass;
947 $a->role = $roles[$userrole->roleid]->localname;
948 if ($contextid == $this->context->id) {
949 $changeable = true;
950 if ($userrole->component) {
951 $changeable = false;
952 if (strpos($userrole->component, 'enrol_') === 0) {
953 $plugin = substr($userrole->component, 6);
954 if (isset($plugins[$plugin])) {
955 $changeable = !$plugins[$plugin]->roles_protected();
959 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
960 } else {
961 $changeable = false;
962 switch ($userrole->contextlevel) {
963 case CONTEXT_COURSE :
964 // Meta course
965 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
966 break;
967 case CONTEXT_COURSECAT :
968 $roletext = get_string('rolefromcategory', 'enrol', $a);
969 break;
970 case CONTEXT_SYSTEM:
971 default:
972 $roletext = get_string('rolefromsystem', 'enrol', $a);
973 break;
976 if (!isset($users[$userrole->id]['roles'])) {
977 $users[$userrole->id]['roles'] = array();
979 $users[$userrole->id]['roles'][$userrole->roleid] = array(
980 'text' => $roletext,
981 'unchangeable' => !$changeable
984 return $users;
988 * Gets an array of users for display, this includes minimal user information
989 * as well as minimal information on the users roles, groups, and enrolments.
991 * @param core_enrol_renderer $renderer
992 * @param moodle_url $pageurl
993 * @param int $sort
994 * @param string $direction ASC or DESC
995 * @param int $page
996 * @param int $perpage
997 * @return array
999 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1000 $pageurl = $manager->get_moodlepage()->url;
1001 $users = $this->get_users($sort, $direction, $page, $perpage);
1003 $now = time();
1004 $straddgroup = get_string('addgroup', 'group');
1005 $strunenrol = get_string('unenrol', 'enrol');
1006 $stredit = get_string('edit');
1008 $allroles = $this->get_all_roles();
1009 $assignable = $this->get_assignable_roles();
1010 $allgroups = $this->get_all_groups();
1011 $context = $this->get_context();
1012 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1014 $url = new moodle_url($pageurl, $this->get_url_params());
1015 $extrafields = get_extra_user_fields($context);
1017 $enabledplugins = $this->get_enrolment_plugins(true);
1019 $userdetails = array();
1020 foreach ($users as $user) {
1021 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1023 // Roles
1024 $details['roles'] = array();
1025 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1026 $unchangeable = !$rassignable;
1027 if (!is_siteadmin() and !isset($assignable[$rid])) {
1028 $unchangeable = true;
1030 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>$unchangeable);
1033 // Users
1034 $usergroups = $this->get_user_groups($user->id);
1035 $details['groups'] = array();
1036 foreach($usergroups as $gid=>$unused) {
1037 $details['groups'][$gid] = $allgroups[$gid]->name;
1040 // Enrolments
1041 $details['enrolments'] = array();
1042 foreach ($this->get_user_enrolments($user->id) as $ue) {
1043 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1044 $details['enrolments'][$ue->id] = array(
1045 'text' => $ue->enrolmentinstancename,
1046 'period' => null,
1047 'dimmed' => true,
1048 'actions' => array()
1050 continue;
1051 } else if ($ue->timestart and $ue->timeend) {
1052 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1053 $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1054 } else if ($ue->timestart) {
1055 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1056 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1057 } else if ($ue->timeend) {
1058 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1059 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1060 } else {
1061 // If there is no start or end show when user was enrolled.
1062 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1063 $periodoutside = false;
1065 $details['enrolments'][$ue->id] = array(
1066 'text' => $ue->enrolmentinstancename,
1067 'period' => $period,
1068 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1069 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1072 $userdetails[$user->id] = $details;
1074 return $userdetails;
1078 * Prepare a user record for display
1080 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1081 * prepare user fields for display
1083 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1085 * @param object $user The user record
1086 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1087 * additional fields may be displayed
1088 * @param int $now The time used for lastaccess calculation
1089 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
1090 * additional fields from $extrafields
1092 private function prepare_user_for_display($user, $extrafields, $now) {
1093 $details = array(
1094 'userid' => $user->id,
1095 'courseid' => $this->get_course()->id,
1096 'picture' => new user_picture($user),
1097 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1098 'lastseen' => get_string('never'),
1099 'lastcourseaccess' => get_string('never'),
1101 foreach ($extrafields as $field) {
1102 $details[$field] = $user->{$field};
1105 // Last time user has accessed the site.
1106 if ($user->lastaccess) {
1107 $details['lastseen'] = format_time($now - $user->lastaccess);
1110 // Last time user has accessed the course.
1111 if ($user->lastseen) {
1112 $details['lastcourseaccess'] = format_time($now - $user->lastseen);
1114 return $details;
1117 public function get_manual_enrol_buttons() {
1118 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1119 $buttons = array();
1120 foreach ($plugins as $plugin) {
1121 $newbutton = $plugin->get_manual_enrol_button($this);
1122 if (is_array($newbutton)) {
1123 $buttons += $newbutton;
1124 } else if ($newbutton instanceof enrol_user_button) {
1125 $buttons[] = $newbutton;
1128 return $buttons;
1131 public function has_instance($enrolpluginname) {
1132 // Make sure manual enrolments instance exists
1133 foreach ($this->get_enrolment_instances() as $instance) {
1134 if ($instance->enrol == $enrolpluginname) {
1135 return true;
1138 return false;
1142 * Returns the enrolment plugin that the course manager was being filtered to.
1144 * If no filter was being applied then this function returns false.
1146 * @return enrol_plugin
1148 public function get_filtered_enrolment_plugin() {
1149 $instances = $this->get_enrolment_instances();
1150 $plugins = $this->get_enrolment_plugins(false);
1152 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1153 return false;
1156 $instance = $instances[$this->instancefilter];
1157 return $plugins[$instance->enrol];
1161 * Returns and array of users + enrolment details.
1163 * Given an array of user id's this function returns and array of user enrolments for those users
1164 * as well as enough user information to display the users name and picture for each enrolment.
1166 * @global moodle_database $DB
1167 * @param array $userids
1168 * @return array
1170 public function get_users_enrolments(array $userids) {
1171 global $DB;
1173 $instances = $this->get_enrolment_instances();
1174 $plugins = $this->get_enrolment_plugins(false);
1176 if (!empty($this->instancefilter)) {
1177 $instancesql = ' = :instanceid';
1178 $instanceparams = array('instanceid' => $this->instancefilter);
1179 } else {
1180 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1183 $userfields = user_picture::fields('u');
1184 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1186 list($sort, $sortparams) = users_order_by_sql('u');
1188 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1189 FROM {user_enrolments} ue
1190 LEFT JOIN {user} u ON u.id = ue.userid
1191 WHERE ue.enrolid $instancesql AND
1192 u.id $idsql
1193 ORDER BY $sort";
1195 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1196 $users = array();
1197 foreach ($rs as $ue) {
1198 $user = user_picture::unalias($ue);
1199 $ue->id = $ue->ueid;
1200 unset($ue->ueid);
1201 if (!array_key_exists($user->id, $users)) {
1202 $user->enrolments = array();
1203 $users[$user->id] = $user;
1205 $ue->enrolmentinstance = $instances[$ue->enrolid];
1206 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1207 $users[$user->id]->enrolments[$ue->id] = $ue;
1209 $rs->close();
1210 return $users;
1215 * A button that is used to enrol users in a course
1217 * @copyright 2010 Sam Hemelryk
1218 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1220 class enrol_user_button extends single_button {
1223 * An array containing JS YUI modules required by this button
1224 * @var array
1226 protected $jsyuimodules = array();
1229 * An array containing JS initialisation calls required by this button
1230 * @var array
1232 protected $jsinitcalls = array();
1235 * An array strings required by JS for this button
1236 * @var array
1238 protected $jsstrings = array();
1241 * Initialises the new enrol_user_button
1243 * @staticvar int $count The number of enrol user buttons already created
1244 * @param moodle_url $url
1245 * @param string $label The text to display in the button
1246 * @param string $method Either post or get
1248 public function __construct(moodle_url $url, $label, $method = 'post') {
1249 static $count = 0;
1250 $count ++;
1251 parent::__construct($url, $label, $method);
1252 $this->class = 'singlebutton enrolusersbutton';
1253 $this->formid = 'enrolusersbutton-'.$count;
1257 * Adds a YUI module call that will be added to the page when the button is used.
1259 * @param string|array $modules One or more modules to require
1260 * @param string $function The JS function to call
1261 * @param array $arguments An array of arguments to pass to the function
1262 * @param string $galleryversion Deprecated: The gallery version to use
1263 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1265 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1266 if ($galleryversion != null) {
1267 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1270 $js = new stdClass;
1271 $js->modules = (array)$modules;
1272 $js->function = $function;
1273 $js->arguments = $arguments;
1274 $js->ondomready = $ondomready;
1275 $this->jsyuimodules[] = $js;
1279 * Adds a JS initialisation call to the page when the button is used.
1281 * @param string $function The function to call
1282 * @param array $extraarguments An array of arguments to pass to the function
1283 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1284 * @param array $module A module definition
1286 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1287 $js = new stdClass;
1288 $js->function = $function;
1289 $js->extraarguments = $extraarguments;
1290 $js->ondomready = $ondomready;
1291 $js->module = $module;
1292 $this->jsinitcalls[] = $js;
1296 * Requires strings for JS that will be loaded when the button is used.
1298 * @param type $identifiers
1299 * @param string $component
1300 * @param mixed $a
1302 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1303 $string = new stdClass;
1304 $string->identifiers = (array)$identifiers;
1305 $string->component = $component;
1306 $string->a = $a;
1307 $this->jsstrings[] = $string;
1311 * Initialises the JS that is required by this button
1313 * @param moodle_page $page
1315 public function initialise_js(moodle_page $page) {
1316 foreach ($this->jsyuimodules as $js) {
1317 $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1319 foreach ($this->jsinitcalls as $js) {
1320 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1322 foreach ($this->jsstrings as $string) {
1323 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1329 * User enrolment action
1331 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1332 * a user enrolment.
1334 * @copyright 2011 Sam Hemelryk
1335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1337 class user_enrolment_action implements renderable {
1340 * The icon to display for the action
1341 * @var pix_icon
1343 protected $icon;
1346 * The title for the action
1347 * @var string
1349 protected $title;
1352 * The URL to the action
1353 * @var moodle_url
1355 protected $url;
1358 * An array of HTML attributes
1359 * @var array
1361 protected $attributes = array();
1364 * Constructor
1365 * @param pix_icon $icon
1366 * @param string $title
1367 * @param moodle_url $url
1368 * @param array $attributes
1370 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1371 $this->icon = $icon;
1372 $this->title = $title;
1373 $this->url = new moodle_url($url);
1374 if (!empty($attributes)) {
1375 $this->attributes = $attributes;
1377 $this->attributes['title'] = $title;
1381 * Returns the icon for this action
1382 * @return pix_icon
1384 public function get_icon() {
1385 return $this->icon;
1389 * Returns the title for this action
1390 * @return string
1392 public function get_title() {
1393 return $this->title;
1397 * Returns the URL for this action
1398 * @return moodle_url
1400 public function get_url() {
1401 return $this->url;
1405 * Returns the attributes to use for this action
1406 * @return array
1408 public function get_attributes() {
1409 return $this->attributes;
1413 class enrol_ajax_exception extends moodle_exception {
1415 * Constructor
1416 * @param string $errorcode The name of the string from error.php to print
1417 * @param string $module name of module
1418 * @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.
1419 * @param object $a Extra words and phrases that might be required in the error string
1420 * @param string $debuginfo optional debugging information
1422 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1423 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1428 * This class is used to manage a bulk operations for enrolment plugins.
1430 * @copyright 2011 Sam Hemelryk
1431 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1433 abstract class enrol_bulk_enrolment_operation {
1436 * The course enrolment manager
1437 * @var course_enrolment_manager
1439 protected $manager;
1442 * The enrolment plugin to which this operation belongs
1443 * @var enrol_plugin
1445 protected $plugin;
1448 * Contructor
1449 * @param course_enrolment_manager $manager
1450 * @param stdClass $plugin
1452 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1453 $this->manager = $manager;
1454 $this->plugin = $plugin;
1458 * Returns a moodleform used for this operation, or false if no form is required and the action
1459 * should be immediatly processed.
1461 * @param moodle_url|string $defaultaction
1462 * @param mixed $defaultcustomdata
1463 * @return enrol_bulk_enrolment_change_form|moodleform|false
1465 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1466 return false;
1470 * Returns the title to use for this bulk operation
1472 * @return string
1474 abstract public function get_title();
1477 * Returns the identifier for this bulk operation.
1478 * This should be the same identifier used by the plugins function when returning
1479 * all of its bulk operations.
1481 * @return string
1483 abstract public function get_identifier();
1486 * Processes the bulk operation on the given users
1488 * @param course_enrolment_manager $manager
1489 * @param array $users
1490 * @param stdClass $properties
1492 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);