MDL-61410 question: move tag sorting logic to a new function
[moodle.git] / enrol / locallib.php
blobb31792f6261ca21092ca5342bccb9483edc045e9
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 context
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 $_visibleroles = null;
121 private $_assignableroles = null;
122 private $_assignablerolesothers = null;
123 private $_groups = null;
124 /**#@-*/
127 * Constructs the course enrolment manager
129 * @param moodle_page $moodlepage
130 * @param stdClass $course
131 * @param string $instancefilter
132 * @param int $rolefilter If non-zero, filters to users with specified role
133 * @param string $searchfilter If non-blank, filters to users with search text
134 * @param int $groupfilter if non-zero, filter users with specified group
135 * @param int $statusfilter if not -1, filter users with active/inactive enrollment.
137 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
138 $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
139 $this->moodlepage = $moodlepage;
140 $this->context = context_course::instance($course->id);
141 $this->course = $course;
142 $this->instancefilter = $instancefilter;
143 $this->rolefilter = $rolefilter;
144 $this->searchfilter = $searchfilter;
145 $this->groupfilter = $groupfilter;
146 $this->statusfilter = $statusfilter;
150 * Returns the current moodle page
151 * @return moodle_page
153 public function get_moodlepage() {
154 return $this->moodlepage;
158 * Returns the total number of enrolled users in the course.
160 * If a filter was specificed this will be the total number of users enrolled
161 * in this course by means of that instance.
163 * @global moodle_database $DB
164 * @return int
166 public function get_total_users() {
167 global $DB;
168 if ($this->totalusers === null) {
169 list($instancessql, $params, $filter) = $this->get_instance_sql();
170 list($filtersql, $moreparams) = $this->get_filter_sql();
171 $params += $moreparams;
172 $sqltotal = "SELECT COUNT(DISTINCT u.id)
173 FROM {user} u
174 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
175 JOIN {enrol} e ON (e.id = ue.enrolid)";
176 if ($this->groupfilter) {
177 $sqltotal .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
178 ON (u.id = gm.userid AND g.courseid = e.courseid)";
180 $sqltotal .= "WHERE $filtersql";
181 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
183 return $this->totalusers;
187 * Returns the total number of enrolled users in the course.
189 * If a filter was specificed this will be the total number of users enrolled
190 * in this course by means of that instance.
192 * @global moodle_database $DB
193 * @return int
195 public function get_total_other_users() {
196 global $DB;
197 if ($this->totalotherusers === null) {
198 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
199 $params['courseid'] = $this->course->id;
200 $sql = "SELECT COUNT(DISTINCT u.id)
201 FROM {role_assignments} ra
202 JOIN {user} u ON u.id = ra.userid
203 JOIN {context} ctx ON ra.contextid = ctx.id
204 LEFT JOIN (
205 SELECT ue.id, ue.userid
206 FROM {user_enrolments} ue
207 LEFT JOIN {enrol} e ON e.id=ue.enrolid
208 WHERE e.courseid = :courseid
209 ) ue ON ue.userid=u.id
210 WHERE ctx.id $ctxcondition AND
211 ue.id IS NULL";
212 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
214 return $this->totalotherusers;
218 * Gets all of the users enrolled in this course.
220 * If a filter was specified this will be the users who were enrolled
221 * in this course by means of that instance. If role or search filters were
222 * specified then these will also be applied.
224 * @global moodle_database $DB
225 * @param string $sort
226 * @param string $direction ASC or DESC
227 * @param int $page First page should be 0
228 * @param int $perpage Defaults to 25
229 * @return array
231 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
232 global $DB;
233 if ($direction !== 'ASC') {
234 $direction = 'DESC';
236 $key = md5("$sort-$direction-$page-$perpage");
237 if (!array_key_exists($key, $this->users)) {
238 list($instancessql, $params, $filter) = $this->get_instance_sql();
239 list($filtersql, $moreparams) = $this->get_filter_sql();
240 $params += $moreparams;
241 $extrafields = get_extra_user_fields($this->get_context());
242 $extrafields[] = 'lastaccess';
243 $ufields = user_picture::fields('u', $extrafields);
244 $sql = "SELECT DISTINCT $ufields, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
245 FROM {user} u
246 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
247 JOIN {enrol} e ON (e.id = ue.enrolid)
248 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
249 if ($this->groupfilter) {
250 $sql .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
251 ON (u.id = gm.userid AND g.courseid = e.courseid)";
253 $sql .= "WHERE $filtersql
254 ORDER BY $sort $direction";
255 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
257 return $this->users[$key];
261 * Obtains WHERE clause to filter results by defined search and role filter
262 * (instance filter is handled separately in JOIN clause, see
263 * get_instance_sql).
265 * @return array Two-element array with SQL and params for WHERE clause
267 protected function get_filter_sql() {
268 global $DB;
270 // Search condition.
271 $extrafields = get_extra_user_fields($this->get_context());
272 list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
274 // Role condition.
275 if ($this->rolefilter) {
276 // Get context SQL.
277 $contextids = $this->context->get_parent_context_ids();
278 $contextids[] = $this->context->id;
279 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
280 $params += $contextparams;
282 // Role check condition.
283 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
284 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
285 $params['roleid'] = $this->rolefilter;
288 // Group condition.
289 if ($this->groupfilter) {
290 if ($this->groupfilter < 0) {
291 // Show users who are not in any group.
292 $sql .= " AND gm.groupid IS NULL";
293 } else {
294 $sql .= " AND gm.groupid = :groupid";
295 $params['groupid'] = $this->groupfilter;
299 // Status condition.
300 if ($this->statusfilter === ENROL_USER_ACTIVE) {
301 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
302 AND (ue.timeend = 0 OR ue.timeend > :now2)";
303 $now = round(time(), -2); // rounding helps caching in DB
304 $params += array('enabled' => ENROL_INSTANCE_ENABLED,
305 'active' => ENROL_USER_ACTIVE,
306 'now1' => $now,
307 'now2' => $now);
308 } else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
309 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
310 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
311 $now = round(time(), -2); // rounding helps caching in DB
312 $params += array('disabled' => ENROL_INSTANCE_DISABLED,
313 'inactive' => ENROL_USER_SUSPENDED,
314 'now1' => $now,
315 'now2' => $now);
318 return array($sql, $params);
322 * Gets and array of other users.
324 * Other users are users who have been assigned roles or inherited roles
325 * within this course but who have not been enrolled in the course
327 * @global moodle_database $DB
328 * @param string $sort
329 * @param string $direction
330 * @param int $page
331 * @param int $perpage
332 * @return array
334 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
335 global $DB;
336 if ($direction !== 'ASC') {
337 $direction = 'DESC';
339 $key = md5("$sort-$direction-$page-$perpage");
340 if (!array_key_exists($key, $this->otherusers)) {
341 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
342 $params['courseid'] = $this->course->id;
343 $params['cid'] = $this->course->id;
344 $extrafields = get_extra_user_fields($this->get_context());
345 $ufields = user_picture::fields('u', $extrafields);
346 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, $ufields,
347 coalesce(u.lastaccess,0) AS lastaccess
348 FROM {role_assignments} ra
349 JOIN {user} u ON u.id = ra.userid
350 JOIN {context} ctx ON ra.contextid = ctx.id
351 LEFT JOIN (
352 SELECT ue.id, ue.userid
353 FROM {user_enrolments} ue
354 JOIN {enrol} e ON e.id = ue.enrolid
355 WHERE e.courseid = :courseid
356 ) ue ON ue.userid=u.id
357 WHERE ctx.id $ctxcondition AND
358 ue.id IS NULL
359 ORDER BY $sort $direction, ctx.depth DESC";
360 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
362 return $this->otherusers[$key];
366 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
368 * @param string $search the search term, if any.
369 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
370 * @return array with three elements:
371 * string list of fields to SELECT,
372 * string contents of SQL WHERE clause,
373 * array query params. Note that the SQL snippets use named parameters.
375 protected function get_basic_search_conditions($search, $searchanywhere) {
376 global $DB, $CFG;
378 // Add some additional sensible conditions
379 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
380 $params = array('guestid' => $CFG->siteguest);
381 if (!empty($search)) {
382 $conditions = get_extra_user_fields($this->get_context());
383 foreach (get_all_user_name_fields() as $field) {
384 $conditions[] = 'u.'.$field;
386 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
387 if ($searchanywhere) {
388 $searchparam = '%' . $search . '%';
389 } else {
390 $searchparam = $search . '%';
392 $i = 0;
393 foreach ($conditions as $key => $condition) {
394 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
395 $params["con{$i}00"] = $searchparam;
396 $i++;
398 $tests[] = '(' . implode(' OR ', $conditions) . ')';
400 $wherecondition = implode(' AND ', $tests);
402 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
403 $extrafields[] = 'username';
404 $extrafields[] = 'lastaccess';
405 $ufields = user_picture::fields('u', $extrafields);
407 return array($ufields, $params, $wherecondition);
411 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
413 * @param string $search the search string, if any.
414 * @param string $fields the first bit of the SQL when returning some users.
415 * @param string $countfields fhe first bit of the SQL when counting the users.
416 * @param string $sql the bulk of the SQL statement.
417 * @param array $params query parameters.
418 * @param int $page which page number of the results to show.
419 * @param int $perpage number of users per page.
420 * @param int $addedenrollment number of users added to enrollment.
421 * @return array with two elememts:
422 * int total number of users matching the search.
423 * array of user objects returned by the query.
425 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
426 global $DB, $CFG;
428 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
429 $order = ' ORDER BY ' . $sort;
431 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
432 $availableusers = $DB->get_records_sql($fields . $sql . $order,
433 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
435 return array('totalusers' => $totalusers, 'users' => $availableusers);
439 * Gets an array of the users that can be enrolled in this course.
441 * @global moodle_database $DB
442 * @param int $enrolid
443 * @param string $search
444 * @param bool $searchanywhere
445 * @param int $page Defaults to 0
446 * @param int $perpage Defaults to 25
447 * @param int $addedenrollment Defaults to 0
448 * @return array Array(totalusers => int, users => array)
450 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
451 global $DB;
453 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
455 $fields = 'SELECT '.$ufields;
456 $countfields = 'SELECT COUNT(1)';
457 $sql = " FROM {user} u
458 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
459 WHERE $wherecondition
460 AND ue.id IS NULL";
461 $params['enrolid'] = $enrolid;
463 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
467 * Searches other users and returns paginated results
469 * @global moodle_database $DB
470 * @param string $search
471 * @param bool $searchanywhere
472 * @param int $page Starting at 0
473 * @param int $perpage
474 * @return array
476 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
477 global $DB, $CFG;
479 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
481 $fields = 'SELECT ' . $ufields;
482 $countfields = 'SELECT COUNT(u.id)';
483 $sql = " FROM {user} u
484 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
485 WHERE $wherecondition
486 AND ra.id IS NULL";
487 $params['contextid'] = $this->context->id;
489 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
493 * Gets an array containing some SQL to user for when selecting, params for
494 * that SQL, and the filter that was used in constructing the sql.
496 * @global moodle_database $DB
497 * @return string
499 protected function get_instance_sql() {
500 global $DB;
501 if ($this->_instancessql === null) {
502 $instances = $this->get_enrolment_instances();
503 $filter = $this->get_enrolment_filter();
504 if ($filter && array_key_exists($filter, $instances)) {
505 $sql = " = :ifilter";
506 $params = array('ifilter'=>$filter);
507 } else {
508 $filter = 0;
509 if ($instances) {
510 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
511 } else {
512 // no enabled instances, oops, we should probably say something
513 $sql = "= :never";
514 $params = array('never'=>-1);
517 $this->instancefilter = $filter;
518 $this->_instancessql = array($sql, $params, $filter);
520 return $this->_instancessql;
524 * Returns all of the enrolment instances for this course.
526 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
527 * @return array
529 public function get_enrolment_instances($onlyenabled = false) {
530 if ($this->_instances === null) {
531 $this->_instances = enrol_get_instances($this->course->id, $onlyenabled);
533 return $this->_instances;
537 * Returns the names for all of the enrolment instances for this course.
539 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
540 * @return array
542 public function get_enrolment_instance_names($onlyenabled = false) {
543 if ($this->_inames === null) {
544 $instances = $this->get_enrolment_instances($onlyenabled);
545 $plugins = $this->get_enrolment_plugins(false);
546 foreach ($instances as $key=>$instance) {
547 if (!isset($plugins[$instance->enrol])) {
548 // weird, some broken stuff in plugin
549 unset($instances[$key]);
550 continue;
552 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
555 return $this->_inames;
559 * Gets all of the enrolment plugins that are available for this course.
561 * @param bool $onlyenabled return only enabled enrol plugins
562 * @return array
564 public function get_enrolment_plugins($onlyenabled = true) {
565 if ($this->_plugins === null) {
566 $this->_plugins = enrol_get_plugins(true);
569 if ($onlyenabled) {
570 return $this->_plugins;
573 if ($this->_allplugins === null) {
574 // Make sure we have the same objects in _allplugins and _plugins.
575 $this->_allplugins = $this->_plugins;
576 foreach (enrol_get_plugins(false) as $name=>$plugin) {
577 if (!isset($this->_allplugins[$name])) {
578 $this->_allplugins[$name] = $plugin;
583 return $this->_allplugins;
587 * Gets all of the roles this course can contain.
589 * @return array
591 public function get_all_roles() {
592 if ($this->_roles === null) {
593 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
595 return $this->_roles;
599 * Gets all of the roles this course can contain.
601 * @return array
603 public function get_viewable_roles() {
604 if ($this->_visibleroles === null) {
605 $this->_visibleroles = get_viewable_roles($this->context);
607 return $this->_visibleroles;
611 * Gets all of the assignable roles for this course.
613 * @return array
615 public function get_assignable_roles($otherusers = false) {
616 if ($this->_assignableroles === null) {
617 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
620 if ($otherusers) {
621 if (!is_array($this->_assignablerolesothers)) {
622 $this->_assignablerolesothers = array();
623 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
624 foreach ($this->_assignableroles as $roleid=>$role) {
625 if (isset($courseviewroles[$roleid])) {
626 $this->_assignablerolesothers[$roleid] = $role;
630 return $this->_assignablerolesothers;
631 } else {
632 return $this->_assignableroles;
637 * Gets all of the assignable roles for this course, wrapped in an array to ensure
638 * role sort order is not lost during json deserialisation.
640 * @param boolean $otherusers whether to include the assignable roles for other users
641 * @return array
643 public function get_assignable_roles_for_json($otherusers = false) {
644 $rolesarray = array();
645 $assignable = $this->get_assignable_roles($otherusers);
646 foreach ($assignable as $id => $role) {
647 $rolesarray[] = array('id' => $id, 'name' => $role);
649 return $rolesarray;
653 * Gets all of the groups for this course.
655 * @return array
657 public function get_all_groups() {
658 if ($this->_groups === null) {
659 $this->_groups = groups_get_all_groups($this->course->id);
660 foreach ($this->_groups as $gid=>$group) {
661 $this->_groups[$gid]->name = format_string($group->name);
664 return $this->_groups;
668 * Unenrols a user from the course given the users ue entry
670 * @global moodle_database $DB
671 * @param stdClass $ue
672 * @return bool
674 public function unenrol_user($ue) {
675 global $DB;
676 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
677 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
678 $plugin->unenrol_user($instance, $ue->userid);
679 return true;
681 return false;
685 * Given a user enrolment record this method returns the plugin and enrolment
686 * instance that relate to it.
688 * @param stdClass|int $userenrolment
689 * @return array array($instance, $plugin)
691 public function get_user_enrolment_components($userenrolment) {
692 global $DB;
693 if (is_numeric($userenrolment)) {
694 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
696 $instances = $this->get_enrolment_instances();
697 $plugins = $this->get_enrolment_plugins(false);
698 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
699 return array(false, false);
701 $instance = $instances[$userenrolment->enrolid];
702 $plugin = $plugins[$instance->enrol];
703 return array($instance, $plugin);
707 * Removes an assigned role from a user.
709 * @global moodle_database $DB
710 * @param int $userid
711 * @param int $roleid
712 * @return bool
714 public function unassign_role_from_user($userid, $roleid) {
715 global $DB;
716 // Admins may unassign any role, others only those they could assign.
717 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
718 if (defined('AJAX_SCRIPT')) {
719 throw new moodle_exception('invalidrole');
721 return false;
723 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
724 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
725 foreach ($ras as $ra) {
726 if ($ra->component) {
727 if (strpos($ra->component, 'enrol_') !== 0) {
728 continue;
730 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
731 continue;
733 if ($plugin->roles_protected()) {
734 continue;
737 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
739 return true;
743 * Assigns a role to a user.
745 * @param int $roleid
746 * @param int $userid
747 * @return int|false
749 public function assign_role_to_user($roleid, $userid) {
750 require_capability('moodle/role:assign', $this->context);
751 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
752 if (defined('AJAX_SCRIPT')) {
753 throw new moodle_exception('invalidrole');
755 return false;
757 return role_assign($roleid, $userid, $this->context->id, '', NULL);
761 * Adds a user to a group
763 * @param stdClass $user
764 * @param int $groupid
765 * @return bool
767 public function add_user_to_group($user, $groupid) {
768 require_capability('moodle/course:managegroups', $this->context);
769 $group = $this->get_group($groupid);
770 if (!$group) {
771 return false;
773 return groups_add_member($group->id, $user->id);
777 * Removes a user from a group
779 * @global moodle_database $DB
780 * @param StdClass $user
781 * @param int $groupid
782 * @return bool
784 public function remove_user_from_group($user, $groupid) {
785 global $DB;
786 require_capability('moodle/course:managegroups', $this->context);
787 $group = $this->get_group($groupid);
788 if (!groups_remove_member_allowed($group, $user)) {
789 return false;
791 if (!$group) {
792 return false;
794 return groups_remove_member($group, $user);
798 * Gets the requested group
800 * @param int $groupid
801 * @return stdClass|int
803 public function get_group($groupid) {
804 $groups = $this->get_all_groups();
805 if (!array_key_exists($groupid, $groups)) {
806 return false;
808 return $groups[$groupid];
812 * Edits an enrolment
814 * @param stdClass $userenrolment
815 * @param stdClass $data
816 * @return bool
818 public function edit_enrolment($userenrolment, $data) {
819 //Only allow editing if the user has the appropriate capability
820 //Already checked in /user/index.php but checking again in case this function is called from elsewhere
821 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
822 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
823 if (!isset($data->status)) {
824 $data->status = $userenrolment->status;
826 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
827 return true;
829 return false;
833 * Returns the current enrolment filter that is being applied by this class
834 * @return string
836 public function get_enrolment_filter() {
837 return $this->instancefilter;
841 * Gets the roles assigned to this user that are applicable for this course.
843 * @param int $userid
844 * @return array
846 public function get_user_roles($userid) {
847 $roles = array();
848 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
849 $plugins = $this->get_enrolment_plugins(false);
850 foreach ($ras as $ra) {
851 if ($ra->contextid != $this->context->id) {
852 if (!array_key_exists($ra->roleid, $roles)) {
853 $roles[$ra->roleid] = null;
855 // higher ras, course always takes precedence
856 continue;
858 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
859 continue;
861 $changeable = true;
862 if ($ra->component) {
863 $changeable = false;
864 if (strpos($ra->component, 'enrol_') === 0) {
865 $plugin = substr($ra->component, 6);
866 if (isset($plugins[$plugin])) {
867 $changeable = !$plugins[$plugin]->roles_protected();
872 $roles[$ra->roleid] = $changeable;
874 return $roles;
878 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
880 * @global moodle_database $DB
881 * @param int $userid
882 * @return array
884 public function get_user_enrolments($userid) {
885 global $DB;
886 list($instancessql, $params, $filter) = $this->get_instance_sql();
887 $params['userid'] = $userid;
888 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
889 $instances = $this->get_enrolment_instances();
890 $plugins = $this->get_enrolment_plugins(false);
891 $inames = $this->get_enrolment_instance_names();
892 foreach ($userenrolments as &$ue) {
893 $ue->enrolmentinstance = $instances[$ue->enrolid];
894 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
895 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
897 return $userenrolments;
901 * Gets the groups this user belongs to
903 * @param int $userid
904 * @return array
906 public function get_user_groups($userid) {
907 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
911 * Retursn an array of params that would go into the URL to return to this
912 * exact page.
914 * @return array
916 public function get_url_params() {
917 $args = array(
918 'id' => $this->course->id
920 if (!empty($this->instancefilter)) {
921 $args['ifilter'] = $this->instancefilter;
923 if (!empty($this->rolefilter)) {
924 $args['role'] = $this->rolefilter;
926 if ($this->searchfilter !== '') {
927 $args['search'] = $this->searchfilter;
929 if (!empty($this->groupfilter)) {
930 $args['filtergroup'] = $this->groupfilter;
932 if ($this->statusfilter !== -1) {
933 $args['status'] = $this->statusfilter;
935 return $args;
939 * Returns the course this object is managing enrolments for
941 * @return stdClass
943 public function get_course() {
944 return $this->course;
948 * Returns the course context
950 * @return context
952 public function get_context() {
953 return $this->context;
957 * Gets an array of other users in this course ready for display.
959 * Other users are users who have been assigned or inherited roles within this
960 * course but have not been enrolled.
962 * @param core_enrol_renderer $renderer
963 * @param moodle_url $pageurl
964 * @param string $sort
965 * @param string $direction ASC | DESC
966 * @param int $page Starting from 0
967 * @param int $perpage
968 * @return array
970 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
972 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
973 $roles = $this->get_all_roles();
974 $plugins = $this->get_enrolment_plugins(false);
976 $context = $this->get_context();
977 $now = time();
978 $extrafields = get_extra_user_fields($context);
980 $users = array();
981 foreach ($userroles as $userrole) {
982 $contextid = $userrole->contextid;
983 unset($userrole->contextid); // This would collide with user avatar.
984 if (!array_key_exists($userrole->id, $users)) {
985 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
987 $a = new stdClass;
988 $a->role = $roles[$userrole->roleid]->localname;
989 if ($contextid == $this->context->id) {
990 $changeable = true;
991 if ($userrole->component) {
992 $changeable = false;
993 if (strpos($userrole->component, 'enrol_') === 0) {
994 $plugin = substr($userrole->component, 6);
995 if (isset($plugins[$plugin])) {
996 $changeable = !$plugins[$plugin]->roles_protected();
1000 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
1001 } else {
1002 $changeable = false;
1003 switch ($userrole->contextlevel) {
1004 case CONTEXT_COURSE :
1005 // Meta course
1006 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
1007 break;
1008 case CONTEXT_COURSECAT :
1009 $roletext = get_string('rolefromcategory', 'enrol', $a);
1010 break;
1011 case CONTEXT_SYSTEM:
1012 default:
1013 $roletext = get_string('rolefromsystem', 'enrol', $a);
1014 break;
1017 if (!isset($users[$userrole->id]['roles'])) {
1018 $users[$userrole->id]['roles'] = array();
1020 $users[$userrole->id]['roles'][$userrole->roleid] = array(
1021 'text' => $roletext,
1022 'unchangeable' => !$changeable
1025 return $users;
1029 * Gets an array of users for display, this includes minimal user information
1030 * as well as minimal information on the users roles, groups, and enrolments.
1032 * @param core_enrol_renderer $renderer
1033 * @param moodle_url $pageurl
1034 * @param int $sort
1035 * @param string $direction ASC or DESC
1036 * @param int $page
1037 * @param int $perpage
1038 * @return array
1040 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1041 $pageurl = $manager->get_moodlepage()->url;
1042 $users = $this->get_users($sort, $direction, $page, $perpage);
1044 $now = time();
1045 $straddgroup = get_string('addgroup', 'group');
1046 $strunenrol = get_string('unenrol', 'enrol');
1047 $stredit = get_string('edit');
1049 $visibleroles = $this->get_viewable_roles();
1050 $assignable = $this->get_assignable_roles();
1051 $allgroups = $this->get_all_groups();
1052 $context = $this->get_context();
1053 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1055 $url = new moodle_url($pageurl, $this->get_url_params());
1056 $extrafields = get_extra_user_fields($context);
1058 $enabledplugins = $this->get_enrolment_plugins(true);
1060 $userdetails = array();
1061 foreach ($users as $user) {
1062 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1064 // Roles
1065 $details['roles'] = array();
1066 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1067 $unchangeable = !$rassignable;
1068 if (!is_siteadmin() and !isset($assignable[$rid])) {
1069 $unchangeable = true;
1072 if (isset($visibleroles[$rid])) {
1073 $label = $visibleroles[$rid];
1074 } else {
1075 $label = get_string('novisibleroles', 'role');
1076 $unchangeable = true;
1079 $details['roles'][$rid] = array('text' => $label, 'unchangeable' => $unchangeable);
1082 // Users
1083 $usergroups = $this->get_user_groups($user->id);
1084 $details['groups'] = array();
1085 foreach($usergroups as $gid=>$unused) {
1086 $details['groups'][$gid] = $allgroups[$gid]->name;
1089 // Enrolments
1090 $details['enrolments'] = array();
1091 foreach ($this->get_user_enrolments($user->id) as $ue) {
1092 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1093 $details['enrolments'][$ue->id] = array(
1094 'text' => $ue->enrolmentinstancename,
1095 'period' => null,
1096 'dimmed' => true,
1097 'actions' => array()
1099 continue;
1100 } else if ($ue->timestart and $ue->timeend) {
1101 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1102 $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1103 } else if ($ue->timestart) {
1104 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1105 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1106 } else if ($ue->timeend) {
1107 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1108 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1109 } else {
1110 // If there is no start or end show when user was enrolled.
1111 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1112 $periodoutside = false;
1114 $details['enrolments'][$ue->id] = array(
1115 'text' => $ue->enrolmentinstancename,
1116 'period' => $period,
1117 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1118 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1121 $userdetails[$user->id] = $details;
1123 return $userdetails;
1127 * Prepare a user record for display
1129 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1130 * prepare user fields for display
1132 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1134 * @param object $user The user record
1135 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1136 * additional fields may be displayed
1137 * @param int $now The time used for lastaccess calculation
1138 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1139 * additional fields from $extrafields
1141 private function prepare_user_for_display($user, $extrafields, $now) {
1142 $details = array(
1143 'userid' => $user->id,
1144 'courseid' => $this->get_course()->id,
1145 'picture' => new user_picture($user),
1146 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1147 'lastaccess' => get_string('never'),
1148 'lastcourseaccess' => get_string('never'),
1151 foreach ($extrafields as $field) {
1152 $details[$field] = $user->{$field};
1155 // Last time user has accessed the site.
1156 if (!empty($user->lastaccess)) {
1157 $details['lastaccess'] = format_time($now - $user->lastaccess);
1160 // Last time user has accessed the course.
1161 if (!empty($user->lastcourseaccess)) {
1162 $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess);
1164 return $details;
1167 public function get_manual_enrol_buttons() {
1168 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1169 $buttons = array();
1170 foreach ($plugins as $plugin) {
1171 $newbutton = $plugin->get_manual_enrol_button($this);
1172 if (is_array($newbutton)) {
1173 $buttons += $newbutton;
1174 } else if ($newbutton instanceof enrol_user_button) {
1175 $buttons[] = $newbutton;
1178 return $buttons;
1181 public function has_instance($enrolpluginname) {
1182 // Make sure manual enrolments instance exists
1183 foreach ($this->get_enrolment_instances() as $instance) {
1184 if ($instance->enrol == $enrolpluginname) {
1185 return true;
1188 return false;
1192 * Returns the enrolment plugin that the course manager was being filtered to.
1194 * If no filter was being applied then this function returns false.
1196 * @return enrol_plugin
1198 public function get_filtered_enrolment_plugin() {
1199 $instances = $this->get_enrolment_instances();
1200 $plugins = $this->get_enrolment_plugins(false);
1202 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1203 return false;
1206 $instance = $instances[$this->instancefilter];
1207 return $plugins[$instance->enrol];
1211 * Returns and array of users + enrolment details.
1213 * Given an array of user id's this function returns and array of user enrolments for those users
1214 * as well as enough user information to display the users name and picture for each enrolment.
1216 * @global moodle_database $DB
1217 * @param array $userids
1218 * @return array
1220 public function get_users_enrolments(array $userids) {
1221 global $DB;
1223 $instances = $this->get_enrolment_instances();
1224 $plugins = $this->get_enrolment_plugins(false);
1226 if (!empty($this->instancefilter)) {
1227 $instancesql = ' = :instanceid';
1228 $instanceparams = array('instanceid' => $this->instancefilter);
1229 } else {
1230 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1233 $userfields = user_picture::fields('u');
1234 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1236 list($sort, $sortparams) = users_order_by_sql('u');
1238 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1239 FROM {user_enrolments} ue
1240 LEFT JOIN {user} u ON u.id = ue.userid
1241 WHERE ue.enrolid $instancesql AND
1242 u.id $idsql
1243 ORDER BY $sort";
1245 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1246 $users = array();
1247 foreach ($rs as $ue) {
1248 $user = user_picture::unalias($ue);
1249 $ue->id = $ue->ueid;
1250 unset($ue->ueid);
1251 if (!array_key_exists($user->id, $users)) {
1252 $user->enrolments = array();
1253 $users[$user->id] = $user;
1255 $ue->enrolmentinstance = $instances[$ue->enrolid];
1256 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1257 $users[$user->id]->enrolments[$ue->id] = $ue;
1259 $rs->close();
1260 return $users;
1265 * A button that is used to enrol users in a course
1267 * @copyright 2010 Sam Hemelryk
1268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1270 class enrol_user_button extends single_button {
1273 * An array containing JS YUI modules required by this button
1274 * @var array
1276 protected $jsyuimodules = array();
1279 * An array containing JS initialisation calls required by this button
1280 * @var array
1282 protected $jsinitcalls = array();
1285 * An array strings required by JS for this button
1286 * @var array
1288 protected $jsstrings = array();
1291 * Initialises the new enrol_user_button
1293 * @staticvar int $count The number of enrol user buttons already created
1294 * @param moodle_url $url
1295 * @param string $label The text to display in the button
1296 * @param string $method Either post or get
1298 public function __construct(moodle_url $url, $label, $method = 'post') {
1299 static $count = 0;
1300 $count ++;
1301 parent::__construct($url, $label, $method);
1302 $this->class = 'singlebutton enrolusersbutton';
1303 $this->formid = 'enrolusersbutton-'.$count;
1307 * Adds a YUI module call that will be added to the page when the button is used.
1309 * @param string|array $modules One or more modules to require
1310 * @param string $function The JS function to call
1311 * @param array $arguments An array of arguments to pass to the function
1312 * @param string $galleryversion Deprecated: The gallery version to use
1313 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1315 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1316 if ($galleryversion != null) {
1317 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1320 $js = new stdClass;
1321 $js->modules = (array)$modules;
1322 $js->function = $function;
1323 $js->arguments = $arguments;
1324 $js->ondomready = $ondomready;
1325 $this->jsyuimodules[] = $js;
1329 * Adds a JS initialisation call to the page when the button is used.
1331 * @param string $function The function to call
1332 * @param array $extraarguments An array of arguments to pass to the function
1333 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1334 * @param array $module A module definition
1336 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1337 $js = new stdClass;
1338 $js->function = $function;
1339 $js->extraarguments = $extraarguments;
1340 $js->ondomready = $ondomready;
1341 $js->module = $module;
1342 $this->jsinitcalls[] = $js;
1346 * Requires strings for JS that will be loaded when the button is used.
1348 * @param type $identifiers
1349 * @param string $component
1350 * @param mixed $a
1352 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1353 $string = new stdClass;
1354 $string->identifiers = (array)$identifiers;
1355 $string->component = $component;
1356 $string->a = $a;
1357 $this->jsstrings[] = $string;
1361 * Initialises the JS that is required by this button
1363 * @param moodle_page $page
1365 public function initialise_js(moodle_page $page) {
1366 foreach ($this->jsyuimodules as $js) {
1367 $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1369 foreach ($this->jsinitcalls as $js) {
1370 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1372 foreach ($this->jsstrings as $string) {
1373 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1379 * User enrolment action
1381 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1382 * a user enrolment.
1384 * @copyright 2011 Sam Hemelryk
1385 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1387 class user_enrolment_action implements renderable {
1390 * The icon to display for the action
1391 * @var pix_icon
1393 protected $icon;
1396 * The title for the action
1397 * @var string
1399 protected $title;
1402 * The URL to the action
1403 * @var moodle_url
1405 protected $url;
1408 * An array of HTML attributes
1409 * @var array
1411 protected $attributes = array();
1414 * Constructor
1415 * @param pix_icon $icon
1416 * @param string $title
1417 * @param moodle_url $url
1418 * @param array $attributes
1420 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1421 $this->icon = $icon;
1422 $this->title = $title;
1423 $this->url = new moodle_url($url);
1424 if (!empty($attributes)) {
1425 $this->attributes = $attributes;
1427 $this->attributes['title'] = $title;
1431 * Returns the icon for this action
1432 * @return pix_icon
1434 public function get_icon() {
1435 return $this->icon;
1439 * Returns the title for this action
1440 * @return string
1442 public function get_title() {
1443 return $this->title;
1447 * Returns the URL for this action
1448 * @return moodle_url
1450 public function get_url() {
1451 return $this->url;
1455 * Returns the attributes to use for this action
1456 * @return array
1458 public function get_attributes() {
1459 return $this->attributes;
1463 class enrol_ajax_exception extends moodle_exception {
1465 * Constructor
1466 * @param string $errorcode The name of the string from error.php to print
1467 * @param string $module name of module
1468 * @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.
1469 * @param object $a Extra words and phrases that might be required in the error string
1470 * @param string $debuginfo optional debugging information
1472 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1473 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1478 * This class is used to manage a bulk operations for enrolment plugins.
1480 * @copyright 2011 Sam Hemelryk
1481 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1483 abstract class enrol_bulk_enrolment_operation {
1486 * The course enrolment manager
1487 * @var course_enrolment_manager
1489 protected $manager;
1492 * The enrolment plugin to which this operation belongs
1493 * @var enrol_plugin
1495 protected $plugin;
1498 * Contructor
1499 * @param course_enrolment_manager $manager
1500 * @param stdClass $plugin
1502 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1503 $this->manager = $manager;
1504 $this->plugin = $plugin;
1508 * Returns a moodleform used for this operation, or false if no form is required and the action
1509 * should be immediatly processed.
1511 * @param moodle_url|string $defaultaction
1512 * @param mixed $defaultcustomdata
1513 * @return enrol_bulk_enrolment_change_form|moodleform|false
1515 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1516 return false;
1520 * Returns the title to use for this bulk operation
1522 * @return string
1524 abstract public function get_title();
1527 * Returns the identifier for this bulk operation.
1528 * This should be the same identifier used by the plugins function when returning
1529 * all of its bulk operations.
1531 * @return string
1533 abstract public function get_identifier();
1536 * Processes the bulk operation on the given users
1538 * @param course_enrolment_manager $manager
1539 * @param array $users
1540 * @param stdClass $properties
1542 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);