MDL-68430 filter_mathjaxloader: update default CDN to 2.7.8
[moodle.git] / enrol / locallib.php
blob35e61ea34bf1a223ddc612851bd5d7b364919964
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 $extrafields[] = 'maildisplay';
406 $ufields = user_picture::fields('u', $extrafields);
408 return array($ufields, $params, $wherecondition);
412 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
414 * @param string $search the search string, if any.
415 * @param string $fields the first bit of the SQL when returning some users.
416 * @param string $countfields fhe first bit of the SQL when counting the users.
417 * @param string $sql the bulk of the SQL statement.
418 * @param array $params query parameters.
419 * @param int $page which page number of the results to show.
420 * @param int $perpage number of users per page.
421 * @param int $addedenrollment number of users added to enrollment.
422 * @return array with two elememts:
423 * int total number of users matching the search.
424 * array of user objects returned by the query.
426 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
427 global $DB, $CFG;
429 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
430 $order = ' ORDER BY ' . $sort;
432 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
433 $availableusers = $DB->get_records_sql($fields . $sql . $order,
434 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
436 return array('totalusers' => $totalusers, 'users' => $availableusers);
440 * Gets an array of the users that can be enrolled in this course.
442 * @global moodle_database $DB
443 * @param int $enrolid
444 * @param string $search
445 * @param bool $searchanywhere
446 * @param int $page Defaults to 0
447 * @param int $perpage Defaults to 25
448 * @param int $addedenrollment Defaults to 0
449 * @return array Array(totalusers => int, users => array)
451 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
452 global $DB;
454 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
456 $fields = 'SELECT '.$ufields;
457 $countfields = 'SELECT COUNT(1)';
458 $sql = " FROM {user} u
459 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
460 WHERE $wherecondition
461 AND ue.id IS NULL";
462 $params['enrolid'] = $enrolid;
464 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
468 * Searches other users and returns paginated results
470 * @global moodle_database $DB
471 * @param string $search
472 * @param bool $searchanywhere
473 * @param int $page Starting at 0
474 * @param int $perpage
475 * @return array
477 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
478 global $DB, $CFG;
480 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
482 $fields = 'SELECT ' . $ufields;
483 $countfields = 'SELECT COUNT(u.id)';
484 $sql = " FROM {user} u
485 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
486 WHERE $wherecondition
487 AND ra.id IS NULL";
488 $params['contextid'] = $this->context->id;
490 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
494 * Gets an array containing some SQL to user for when selecting, params for
495 * that SQL, and the filter that was used in constructing the sql.
497 * @global moodle_database $DB
498 * @return string
500 protected function get_instance_sql() {
501 global $DB;
502 if ($this->_instancessql === null) {
503 $instances = $this->get_enrolment_instances();
504 $filter = $this->get_enrolment_filter();
505 if ($filter && array_key_exists($filter, $instances)) {
506 $sql = " = :ifilter";
507 $params = array('ifilter'=>$filter);
508 } else {
509 $filter = 0;
510 if ($instances) {
511 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
512 } else {
513 // no enabled instances, oops, we should probably say something
514 $sql = "= :never";
515 $params = array('never'=>-1);
518 $this->instancefilter = $filter;
519 $this->_instancessql = array($sql, $params, $filter);
521 return $this->_instancessql;
525 * Returns all of the enrolment instances for this course.
527 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
528 * @return array
530 public function get_enrolment_instances($onlyenabled = false) {
531 if ($this->_instances === null) {
532 $this->_instances = enrol_get_instances($this->course->id, $onlyenabled);
534 return $this->_instances;
538 * Returns the names for all of the enrolment instances for this course.
540 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
541 * @return array
543 public function get_enrolment_instance_names($onlyenabled = false) {
544 if ($this->_inames === null) {
545 $instances = $this->get_enrolment_instances($onlyenabled);
546 $plugins = $this->get_enrolment_plugins(false);
547 foreach ($instances as $key=>$instance) {
548 if (!isset($plugins[$instance->enrol])) {
549 // weird, some broken stuff in plugin
550 unset($instances[$key]);
551 continue;
553 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
556 return $this->_inames;
560 * Gets all of the enrolment plugins that are available for this course.
562 * @param bool $onlyenabled return only enabled enrol plugins
563 * @return array
565 public function get_enrolment_plugins($onlyenabled = true) {
566 if ($this->_plugins === null) {
567 $this->_plugins = enrol_get_plugins(true);
570 if ($onlyenabled) {
571 return $this->_plugins;
574 if ($this->_allplugins === null) {
575 // Make sure we have the same objects in _allplugins and _plugins.
576 $this->_allplugins = $this->_plugins;
577 foreach (enrol_get_plugins(false) as $name=>$plugin) {
578 if (!isset($this->_allplugins[$name])) {
579 $this->_allplugins[$name] = $plugin;
584 return $this->_allplugins;
588 * Gets all of the roles this course can contain.
590 * @return array
592 public function get_all_roles() {
593 if ($this->_roles === null) {
594 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
596 return $this->_roles;
600 * Gets all of the roles this course can contain.
602 * @return array
604 public function get_viewable_roles() {
605 if ($this->_visibleroles === null) {
606 $this->_visibleroles = get_viewable_roles($this->context);
608 return $this->_visibleroles;
612 * Gets all of the assignable roles for this course.
614 * @return array
616 public function get_assignable_roles($otherusers = false) {
617 if ($this->_assignableroles === null) {
618 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
621 if ($otherusers) {
622 if (!is_array($this->_assignablerolesothers)) {
623 $this->_assignablerolesothers = array();
624 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
625 foreach ($this->_assignableroles as $roleid=>$role) {
626 if (isset($courseviewroles[$roleid])) {
627 $this->_assignablerolesothers[$roleid] = $role;
631 return $this->_assignablerolesothers;
632 } else {
633 return $this->_assignableroles;
638 * Gets all of the assignable roles for this course, wrapped in an array to ensure
639 * role sort order is not lost during json deserialisation.
641 * @param boolean $otherusers whether to include the assignable roles for other users
642 * @return array
644 public function get_assignable_roles_for_json($otherusers = false) {
645 $rolesarray = array();
646 $assignable = $this->get_assignable_roles($otherusers);
647 foreach ($assignable as $id => $role) {
648 $rolesarray[] = array('id' => $id, 'name' => $role);
650 return $rolesarray;
654 * Gets all of the groups for this course.
656 * @return array
658 public function get_all_groups() {
659 if ($this->_groups === null) {
660 $this->_groups = groups_get_all_groups($this->course->id);
661 foreach ($this->_groups as $gid=>$group) {
662 $this->_groups[$gid]->name = format_string($group->name);
665 return $this->_groups;
669 * Unenrols a user from the course given the users ue entry
671 * @global moodle_database $DB
672 * @param stdClass $ue
673 * @return bool
675 public function unenrol_user($ue) {
676 global $DB;
677 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
678 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
679 $plugin->unenrol_user($instance, $ue->userid);
680 return true;
682 return false;
686 * Given a user enrolment record this method returns the plugin and enrolment
687 * instance that relate to it.
689 * @param stdClass|int $userenrolment
690 * @return array array($instance, $plugin)
692 public function get_user_enrolment_components($userenrolment) {
693 global $DB;
694 if (is_numeric($userenrolment)) {
695 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
697 $instances = $this->get_enrolment_instances();
698 $plugins = $this->get_enrolment_plugins(false);
699 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
700 return array(false, false);
702 $instance = $instances[$userenrolment->enrolid];
703 $plugin = $plugins[$instance->enrol];
704 return array($instance, $plugin);
708 * Removes an assigned role from a user.
710 * @global moodle_database $DB
711 * @param int $userid
712 * @param int $roleid
713 * @return bool
715 public function unassign_role_from_user($userid, $roleid) {
716 global $DB;
717 // Admins may unassign any role, others only those they could assign.
718 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
719 if (defined('AJAX_SCRIPT')) {
720 throw new moodle_exception('invalidrole');
722 return false;
724 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
725 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
726 foreach ($ras as $ra) {
727 if ($ra->component) {
728 if (strpos($ra->component, 'enrol_') !== 0) {
729 continue;
731 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
732 continue;
734 if ($plugin->roles_protected()) {
735 continue;
738 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
740 return true;
744 * Assigns a role to a user.
746 * @param int $roleid
747 * @param int $userid
748 * @return int|false
750 public function assign_role_to_user($roleid, $userid) {
751 require_capability('moodle/role:assign', $this->context);
752 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
753 if (defined('AJAX_SCRIPT')) {
754 throw new moodle_exception('invalidrole');
756 return false;
758 return role_assign($roleid, $userid, $this->context->id, '', NULL);
762 * Adds a user to a group
764 * @param stdClass $user
765 * @param int $groupid
766 * @return bool
768 public function add_user_to_group($user, $groupid) {
769 require_capability('moodle/course:managegroups', $this->context);
770 $group = $this->get_group($groupid);
771 if (!$group) {
772 return false;
774 return groups_add_member($group->id, $user->id);
778 * Removes a user from a group
780 * @global moodle_database $DB
781 * @param StdClass $user
782 * @param int $groupid
783 * @return bool
785 public function remove_user_from_group($user, $groupid) {
786 global $DB;
787 require_capability('moodle/course:managegroups', $this->context);
788 $group = $this->get_group($groupid);
789 if (!groups_remove_member_allowed($group, $user)) {
790 return false;
792 if (!$group) {
793 return false;
795 return groups_remove_member($group, $user);
799 * Gets the requested group
801 * @param int $groupid
802 * @return stdClass|int
804 public function get_group($groupid) {
805 $groups = $this->get_all_groups();
806 if (!array_key_exists($groupid, $groups)) {
807 return false;
809 return $groups[$groupid];
813 * Edits an enrolment
815 * @param stdClass $userenrolment
816 * @param stdClass $data
817 * @return bool
819 public function edit_enrolment($userenrolment, $data) {
820 //Only allow editing if the user has the appropriate capability
821 //Already checked in /user/index.php but checking again in case this function is called from elsewhere
822 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
823 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
824 if (!isset($data->status)) {
825 $data->status = $userenrolment->status;
827 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
828 return true;
830 return false;
834 * Returns the current enrolment filter that is being applied by this class
835 * @return string
837 public function get_enrolment_filter() {
838 return $this->instancefilter;
842 * Gets the roles assigned to this user that are applicable for this course.
844 * @param int $userid
845 * @return array
847 public function get_user_roles($userid) {
848 $roles = array();
849 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
850 $plugins = $this->get_enrolment_plugins(false);
851 foreach ($ras as $ra) {
852 if ($ra->contextid != $this->context->id) {
853 if (!array_key_exists($ra->roleid, $roles)) {
854 $roles[$ra->roleid] = null;
856 // higher ras, course always takes precedence
857 continue;
859 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
860 continue;
862 $changeable = true;
863 if ($ra->component) {
864 $changeable = false;
865 if (strpos($ra->component, 'enrol_') === 0) {
866 $plugin = substr($ra->component, 6);
867 if (isset($plugins[$plugin])) {
868 $changeable = !$plugins[$plugin]->roles_protected();
873 $roles[$ra->roleid] = $changeable;
875 return $roles;
879 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
881 * @global moodle_database $DB
882 * @param int $userid
883 * @return array
885 public function get_user_enrolments($userid) {
886 global $DB;
887 list($instancessql, $params, $filter) = $this->get_instance_sql();
888 $params['userid'] = $userid;
889 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
890 $instances = $this->get_enrolment_instances();
891 $plugins = $this->get_enrolment_plugins(false);
892 $inames = $this->get_enrolment_instance_names();
893 foreach ($userenrolments as &$ue) {
894 $ue->enrolmentinstance = $instances[$ue->enrolid];
895 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
896 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
898 return $userenrolments;
902 * Gets the groups this user belongs to
904 * @param int $userid
905 * @return array
907 public function get_user_groups($userid) {
908 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
912 * Retursn an array of params that would go into the URL to return to this
913 * exact page.
915 * @return array
917 public function get_url_params() {
918 $args = array(
919 'id' => $this->course->id
921 if (!empty($this->instancefilter)) {
922 $args['ifilter'] = $this->instancefilter;
924 if (!empty($this->rolefilter)) {
925 $args['role'] = $this->rolefilter;
927 if ($this->searchfilter !== '') {
928 $args['search'] = $this->searchfilter;
930 if (!empty($this->groupfilter)) {
931 $args['filtergroup'] = $this->groupfilter;
933 if ($this->statusfilter !== -1) {
934 $args['status'] = $this->statusfilter;
936 return $args;
940 * Returns the course this object is managing enrolments for
942 * @return stdClass
944 public function get_course() {
945 return $this->course;
949 * Returns the course context
951 * @return context
953 public function get_context() {
954 return $this->context;
958 * Gets an array of other users in this course ready for display.
960 * Other users are users who have been assigned or inherited roles within this
961 * course but have not been enrolled.
963 * @param core_enrol_renderer $renderer
964 * @param moodle_url $pageurl
965 * @param string $sort
966 * @param string $direction ASC | DESC
967 * @param int $page Starting from 0
968 * @param int $perpage
969 * @return array
971 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
973 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
974 $roles = $this->get_all_roles();
975 $plugins = $this->get_enrolment_plugins(false);
977 $context = $this->get_context();
978 $now = time();
979 $extrafields = get_extra_user_fields($context);
981 $users = array();
982 foreach ($userroles as $userrole) {
983 $contextid = $userrole->contextid;
984 unset($userrole->contextid); // This would collide with user avatar.
985 if (!array_key_exists($userrole->id, $users)) {
986 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
988 $a = new stdClass;
989 $a->role = $roles[$userrole->roleid]->localname;
990 if ($contextid == $this->context->id) {
991 $changeable = true;
992 if ($userrole->component) {
993 $changeable = false;
994 if (strpos($userrole->component, 'enrol_') === 0) {
995 $plugin = substr($userrole->component, 6);
996 if (isset($plugins[$plugin])) {
997 $changeable = !$plugins[$plugin]->roles_protected();
1001 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
1002 } else {
1003 $changeable = false;
1004 switch ($userrole->contextlevel) {
1005 case CONTEXT_COURSE :
1006 // Meta course
1007 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
1008 break;
1009 case CONTEXT_COURSECAT :
1010 $roletext = get_string('rolefromcategory', 'enrol', $a);
1011 break;
1012 case CONTEXT_SYSTEM:
1013 default:
1014 $roletext = get_string('rolefromsystem', 'enrol', $a);
1015 break;
1018 if (!isset($users[$userrole->id]['roles'])) {
1019 $users[$userrole->id]['roles'] = array();
1021 $users[$userrole->id]['roles'][$userrole->roleid] = array(
1022 'text' => $roletext,
1023 'unchangeable' => !$changeable
1026 return $users;
1030 * Gets an array of users for display, this includes minimal user information
1031 * as well as minimal information on the users roles, groups, and enrolments.
1033 * @param core_enrol_renderer $renderer
1034 * @param moodle_url $pageurl
1035 * @param int $sort
1036 * @param string $direction ASC or DESC
1037 * @param int $page
1038 * @param int $perpage
1039 * @return array
1041 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1042 $pageurl = $manager->get_moodlepage()->url;
1043 $users = $this->get_users($sort, $direction, $page, $perpage);
1045 $now = time();
1046 $straddgroup = get_string('addgroup', 'group');
1047 $strunenrol = get_string('unenrol', 'enrol');
1048 $stredit = get_string('edit');
1050 $visibleroles = $this->get_viewable_roles();
1051 $assignable = $this->get_assignable_roles();
1052 $allgroups = $this->get_all_groups();
1053 $context = $this->get_context();
1054 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1056 $url = new moodle_url($pageurl, $this->get_url_params());
1057 $extrafields = get_extra_user_fields($context);
1059 $enabledplugins = $this->get_enrolment_plugins(true);
1061 $userdetails = array();
1062 foreach ($users as $user) {
1063 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1065 // Roles
1066 $details['roles'] = array();
1067 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1068 $unchangeable = !$rassignable;
1069 if (!is_siteadmin() and !isset($assignable[$rid])) {
1070 $unchangeable = true;
1073 if (isset($visibleroles[$rid])) {
1074 $label = $visibleroles[$rid];
1075 } else {
1076 $label = get_string('novisibleroles', 'role');
1077 $unchangeable = true;
1080 $details['roles'][$rid] = array('text' => $label, 'unchangeable' => $unchangeable);
1083 // Users
1084 $usergroups = $this->get_user_groups($user->id);
1085 $details['groups'] = array();
1086 foreach($usergroups as $gid=>$unused) {
1087 $details['groups'][$gid] = $allgroups[$gid]->name;
1090 // Enrolments
1091 $details['enrolments'] = array();
1092 foreach ($this->get_user_enrolments($user->id) as $ue) {
1093 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1094 $details['enrolments'][$ue->id] = array(
1095 'text' => $ue->enrolmentinstancename,
1096 'period' => null,
1097 'dimmed' => true,
1098 'actions' => array()
1100 continue;
1101 } else if ($ue->timestart and $ue->timeend) {
1102 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1103 $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1104 } else if ($ue->timestart) {
1105 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1106 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1107 } else if ($ue->timeend) {
1108 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1109 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1110 } else {
1111 // If there is no start or end show when user was enrolled.
1112 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1113 $periodoutside = false;
1115 $details['enrolments'][$ue->id] = array(
1116 'text' => $ue->enrolmentinstancename,
1117 'period' => $period,
1118 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1119 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1122 $userdetails[$user->id] = $details;
1124 return $userdetails;
1128 * Prepare a user record for display
1130 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1131 * prepare user fields for display
1133 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1135 * @param object $user The user record
1136 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1137 * additional fields may be displayed
1138 * @param int $now The time used for lastaccess calculation
1139 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1140 * additional fields from $extrafields
1142 private function prepare_user_for_display($user, $extrafields, $now) {
1143 $details = array(
1144 'userid' => $user->id,
1145 'courseid' => $this->get_course()->id,
1146 'picture' => new user_picture($user),
1147 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1148 'lastaccess' => get_string('never'),
1149 'lastcourseaccess' => get_string('never'),
1152 foreach ($extrafields as $field) {
1153 $details[$field] = $user->{$field};
1156 // Last time user has accessed the site.
1157 if (!empty($user->lastaccess)) {
1158 $details['lastaccess'] = format_time($now - $user->lastaccess);
1161 // Last time user has accessed the course.
1162 if (!empty($user->lastcourseaccess)) {
1163 $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess);
1165 return $details;
1168 public function get_manual_enrol_buttons() {
1169 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1170 $buttons = array();
1171 foreach ($plugins as $plugin) {
1172 $newbutton = $plugin->get_manual_enrol_button($this);
1173 if (is_array($newbutton)) {
1174 $buttons += $newbutton;
1175 } else if ($newbutton instanceof enrol_user_button) {
1176 $buttons[] = $newbutton;
1179 return $buttons;
1182 public function has_instance($enrolpluginname) {
1183 // Make sure manual enrolments instance exists
1184 foreach ($this->get_enrolment_instances() as $instance) {
1185 if ($instance->enrol == $enrolpluginname) {
1186 return true;
1189 return false;
1193 * Returns the enrolment plugin that the course manager was being filtered to.
1195 * If no filter was being applied then this function returns false.
1197 * @return enrol_plugin
1199 public function get_filtered_enrolment_plugin() {
1200 $instances = $this->get_enrolment_instances();
1201 $plugins = $this->get_enrolment_plugins(false);
1203 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1204 return false;
1207 $instance = $instances[$this->instancefilter];
1208 return $plugins[$instance->enrol];
1212 * Returns and array of users + enrolment details.
1214 * Given an array of user id's this function returns and array of user enrolments for those users
1215 * as well as enough user information to display the users name and picture for each enrolment.
1217 * @global moodle_database $DB
1218 * @param array $userids
1219 * @return array
1221 public function get_users_enrolments(array $userids) {
1222 global $DB;
1224 $instances = $this->get_enrolment_instances();
1225 $plugins = $this->get_enrolment_plugins(false);
1227 if (!empty($this->instancefilter)) {
1228 $instancesql = ' = :instanceid';
1229 $instanceparams = array('instanceid' => $this->instancefilter);
1230 } else {
1231 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1234 $userfields = user_picture::fields('u');
1235 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1237 list($sort, $sortparams) = users_order_by_sql('u');
1239 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1240 FROM {user_enrolments} ue
1241 LEFT JOIN {user} u ON u.id = ue.userid
1242 WHERE ue.enrolid $instancesql AND
1243 u.id $idsql
1244 ORDER BY $sort";
1246 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1247 $users = array();
1248 foreach ($rs as $ue) {
1249 $user = user_picture::unalias($ue);
1250 $ue->id = $ue->ueid;
1251 unset($ue->ueid);
1252 if (!array_key_exists($user->id, $users)) {
1253 $user->enrolments = array();
1254 $users[$user->id] = $user;
1256 $ue->enrolmentinstance = $instances[$ue->enrolid];
1257 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1258 $users[$user->id]->enrolments[$ue->id] = $ue;
1260 $rs->close();
1261 return $users;
1266 * A button that is used to enrol users in a course
1268 * @copyright 2010 Sam Hemelryk
1269 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1271 class enrol_user_button extends single_button {
1274 * An array containing JS YUI modules required by this button
1275 * @var array
1277 protected $jsyuimodules = array();
1280 * An array containing JS initialisation calls required by this button
1281 * @var array
1283 protected $jsinitcalls = array();
1286 * An array strings required by JS for this button
1287 * @var array
1289 protected $jsstrings = array();
1292 * Initialises the new enrol_user_button
1294 * @staticvar int $count The number of enrol user buttons already created
1295 * @param moodle_url $url
1296 * @param string $label The text to display in the button
1297 * @param string $method Either post or get
1299 public function __construct(moodle_url $url, $label, $method = 'post') {
1300 static $count = 0;
1301 $count ++;
1302 parent::__construct($url, $label, $method);
1303 $this->class = 'singlebutton enrolusersbutton';
1304 $this->formid = 'enrolusersbutton-'.$count;
1308 * Adds a YUI module call that will be added to the page when the button is used.
1310 * @param string|array $modules One or more modules to require
1311 * @param string $function The JS function to call
1312 * @param array $arguments An array of arguments to pass to the function
1313 * @param string $galleryversion Deprecated: The gallery version to use
1314 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1316 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1317 if ($galleryversion != null) {
1318 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1321 $js = new stdClass;
1322 $js->modules = (array)$modules;
1323 $js->function = $function;
1324 $js->arguments = $arguments;
1325 $js->ondomready = $ondomready;
1326 $this->jsyuimodules[] = $js;
1330 * Adds a JS initialisation call to the page when the button is used.
1332 * @param string $function The function to call
1333 * @param array $extraarguments An array of arguments to pass to the function
1334 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1335 * @param array $module A module definition
1337 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1338 $js = new stdClass;
1339 $js->function = $function;
1340 $js->extraarguments = $extraarguments;
1341 $js->ondomready = $ondomready;
1342 $js->module = $module;
1343 $this->jsinitcalls[] = $js;
1347 * Requires strings for JS that will be loaded when the button is used.
1349 * @param type $identifiers
1350 * @param string $component
1351 * @param mixed $a
1353 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1354 $string = new stdClass;
1355 $string->identifiers = (array)$identifiers;
1356 $string->component = $component;
1357 $string->a = $a;
1358 $this->jsstrings[] = $string;
1362 * Initialises the JS that is required by this button
1364 * @param moodle_page $page
1366 public function initialise_js(moodle_page $page) {
1367 foreach ($this->jsyuimodules as $js) {
1368 $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1370 foreach ($this->jsinitcalls as $js) {
1371 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1373 foreach ($this->jsstrings as $string) {
1374 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1380 * User enrolment action
1382 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1383 * a user enrolment.
1385 * @copyright 2011 Sam Hemelryk
1386 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1388 class user_enrolment_action implements renderable {
1391 * The icon to display for the action
1392 * @var pix_icon
1394 protected $icon;
1397 * The title for the action
1398 * @var string
1400 protected $title;
1403 * The URL to the action
1404 * @var moodle_url
1406 protected $url;
1409 * An array of HTML attributes
1410 * @var array
1412 protected $attributes = array();
1415 * Constructor
1416 * @param pix_icon $icon
1417 * @param string $title
1418 * @param moodle_url $url
1419 * @param array $attributes
1421 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1422 $this->icon = $icon;
1423 $this->title = $title;
1424 $this->url = new moodle_url($url);
1425 if (!empty($attributes)) {
1426 $this->attributes = $attributes;
1428 $this->attributes['title'] = $title;
1432 * Returns the icon for this action
1433 * @return pix_icon
1435 public function get_icon() {
1436 return $this->icon;
1440 * Returns the title for this action
1441 * @return string
1443 public function get_title() {
1444 return $this->title;
1448 * Returns the URL for this action
1449 * @return moodle_url
1451 public function get_url() {
1452 return $this->url;
1456 * Returns the attributes to use for this action
1457 * @return array
1459 public function get_attributes() {
1460 return $this->attributes;
1464 class enrol_ajax_exception extends moodle_exception {
1466 * Constructor
1467 * @param string $errorcode The name of the string from error.php to print
1468 * @param string $module name of module
1469 * @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.
1470 * @param object $a Extra words and phrases that might be required in the error string
1471 * @param string $debuginfo optional debugging information
1473 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1474 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1479 * This class is used to manage a bulk operations for enrolment plugins.
1481 * @copyright 2011 Sam Hemelryk
1482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1484 abstract class enrol_bulk_enrolment_operation {
1487 * The course enrolment manager
1488 * @var course_enrolment_manager
1490 protected $manager;
1493 * The enrolment plugin to which this operation belongs
1494 * @var enrol_plugin
1496 protected $plugin;
1499 * Contructor
1500 * @param course_enrolment_manager $manager
1501 * @param stdClass $plugin
1503 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1504 $this->manager = $manager;
1505 $this->plugin = $plugin;
1509 * Returns a moodleform used for this operation, or false if no form is required and the action
1510 * should be immediatly processed.
1512 * @param moodle_url|string $defaultaction
1513 * @param mixed $defaultcustomdata
1514 * @return enrol_bulk_enrolment_change_form|moodleform|false
1516 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1517 return false;
1521 * Returns the title to use for this bulk operation
1523 * @return string
1525 abstract public function get_title();
1528 * Returns the identifier for this bulk operation.
1529 * This should be the same identifier used by the plugins function when returning
1530 * all of its bulk operations.
1532 * @return string
1534 abstract public function get_identifier();
1537 * Processes the bulk operation on the given users
1539 * @param course_enrolment_manager $manager
1540 * @param array $users
1541 * @param stdClass $properties
1543 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);