MDL-50246 quiz: Add selected questions to quiz btn disabled 0 selected
[moodle.git] / enrol / locallib.php
blob0447951ff4feb90e4a02af0127a6f04c28b3f180
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 $conditions[] = 'u.firstname';
384 $conditions[] = 'u.lastname';
385 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
386 if ($searchanywhere) {
387 $searchparam = '%' . $search . '%';
388 } else {
389 $searchparam = $search . '%';
391 $i = 0;
392 foreach ($conditions as $key => $condition) {
393 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
394 $params["con{$i}00"] = $searchparam;
395 $i++;
397 $tests[] = '(' . implode(' OR ', $conditions) . ')';
399 $wherecondition = implode(' AND ', $tests);
401 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
402 $extrafields[] = 'username';
403 $extrafields[] = 'lastaccess';
404 $ufields = user_picture::fields('u', $extrafields);
406 return array($ufields, $params, $wherecondition);
410 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
412 * @param string $search the search string, if any.
413 * @param string $fields the first bit of the SQL when returning some users.
414 * @param string $countfields fhe first bit of the SQL when counting the users.
415 * @param string $sql the bulk of the SQL statement.
416 * @param array $params query parameters.
417 * @param int $page which page number of the results to show.
418 * @param int $perpage number of users per page.
419 * @param int $addedenrollment number of users added to enrollment.
420 * @return array with two elememts:
421 * int total number of users matching the search.
422 * array of user objects returned by the query.
424 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
425 global $DB, $CFG;
427 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
428 $order = ' ORDER BY ' . $sort;
430 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
431 $availableusers = $DB->get_records_sql($fields . $sql . $order,
432 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
434 return array('totalusers' => $totalusers, 'users' => $availableusers);
438 * Gets an array of the users that can be enrolled in this course.
440 * @global moodle_database $DB
441 * @param int $enrolid
442 * @param string $search
443 * @param bool $searchanywhere
444 * @param int $page Defaults to 0
445 * @param int $perpage Defaults to 25
446 * @param int $addedenrollment Defaults to 0
447 * @return array Array(totalusers => int, users => array)
449 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
450 global $DB;
452 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
454 $fields = 'SELECT '.$ufields;
455 $countfields = 'SELECT COUNT(1)';
456 $sql = " FROM {user} u
457 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
458 WHERE $wherecondition
459 AND ue.id IS NULL";
460 $params['enrolid'] = $enrolid;
462 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
466 * Searches other users and returns paginated results
468 * @global moodle_database $DB
469 * @param string $search
470 * @param bool $searchanywhere
471 * @param int $page Starting at 0
472 * @param int $perpage
473 * @return array
475 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
476 global $DB, $CFG;
478 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
480 $fields = 'SELECT ' . $ufields;
481 $countfields = 'SELECT COUNT(u.id)';
482 $sql = " FROM {user} u
483 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
484 WHERE $wherecondition
485 AND ra.id IS NULL";
486 $params['contextid'] = $this->context->id;
488 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
492 * Gets an array containing some SQL to user for when selecting, params for
493 * that SQL, and the filter that was used in constructing the sql.
495 * @global moodle_database $DB
496 * @return string
498 protected function get_instance_sql() {
499 global $DB;
500 if ($this->_instancessql === null) {
501 $instances = $this->get_enrolment_instances();
502 $filter = $this->get_enrolment_filter();
503 if ($filter && array_key_exists($filter, $instances)) {
504 $sql = " = :ifilter";
505 $params = array('ifilter'=>$filter);
506 } else {
507 $filter = 0;
508 if ($instances) {
509 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
510 } else {
511 // no enabled instances, oops, we should probably say something
512 $sql = "= :never";
513 $params = array('never'=>-1);
516 $this->instancefilter = $filter;
517 $this->_instancessql = array($sql, $params, $filter);
519 return $this->_instancessql;
523 * Returns all of the enrolment instances for this course.
525 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
526 * @return array
528 public function get_enrolment_instances($onlyenabled = false) {
529 if ($this->_instances === null) {
530 $this->_instances = enrol_get_instances($this->course->id, $onlyenabled);
532 return $this->_instances;
536 * Returns the names for all of the enrolment instances for this course.
538 * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
539 * @return array
541 public function get_enrolment_instance_names($onlyenabled = false) {
542 if ($this->_inames === null) {
543 $instances = $this->get_enrolment_instances($onlyenabled);
544 $plugins = $this->get_enrolment_plugins(false);
545 foreach ($instances as $key=>$instance) {
546 if (!isset($plugins[$instance->enrol])) {
547 // weird, some broken stuff in plugin
548 unset($instances[$key]);
549 continue;
551 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
554 return $this->_inames;
558 * Gets all of the enrolment plugins that are available for this course.
560 * @param bool $onlyenabled return only enabled enrol plugins
561 * @return array
563 public function get_enrolment_plugins($onlyenabled = true) {
564 if ($this->_plugins === null) {
565 $this->_plugins = enrol_get_plugins(true);
568 if ($onlyenabled) {
569 return $this->_plugins;
572 if ($this->_allplugins === null) {
573 // Make sure we have the same objects in _allplugins and _plugins.
574 $this->_allplugins = $this->_plugins;
575 foreach (enrol_get_plugins(false) as $name=>$plugin) {
576 if (!isset($this->_allplugins[$name])) {
577 $this->_allplugins[$name] = $plugin;
582 return $this->_allplugins;
586 * Gets all of the roles this course can contain.
588 * @return array
590 public function get_all_roles() {
591 if ($this->_roles === null) {
592 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
594 return $this->_roles;
598 * Gets all of the roles this course can contain.
600 * @return array
602 public function get_viewable_roles() {
603 if ($this->_visibleroles === null) {
604 $this->_visibleroles = get_viewable_roles($this->context);
606 return $this->_visibleroles;
610 * Gets all of the assignable roles for this course.
612 * @return array
614 public function get_assignable_roles($otherusers = false) {
615 if ($this->_assignableroles === null) {
616 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
619 if ($otherusers) {
620 if (!is_array($this->_assignablerolesothers)) {
621 $this->_assignablerolesothers = array();
622 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
623 foreach ($this->_assignableroles as $roleid=>$role) {
624 if (isset($courseviewroles[$roleid])) {
625 $this->_assignablerolesothers[$roleid] = $role;
629 return $this->_assignablerolesothers;
630 } else {
631 return $this->_assignableroles;
636 * Gets all of the assignable roles for this course, wrapped in an array to ensure
637 * role sort order is not lost during json deserialisation.
639 * @param boolean $otherusers whether to include the assignable roles for other users
640 * @return array
642 public function get_assignable_roles_for_json($otherusers = false) {
643 $rolesarray = array();
644 $assignable = $this->get_assignable_roles($otherusers);
645 foreach ($assignable as $id => $role) {
646 $rolesarray[] = array('id' => $id, 'name' => $role);
648 return $rolesarray;
652 * Gets all of the groups for this course.
654 * @return array
656 public function get_all_groups() {
657 if ($this->_groups === null) {
658 $this->_groups = groups_get_all_groups($this->course->id);
659 foreach ($this->_groups as $gid=>$group) {
660 $this->_groups[$gid]->name = format_string($group->name);
663 return $this->_groups;
667 * Unenrols a user from the course given the users ue entry
669 * @global moodle_database $DB
670 * @param stdClass $ue
671 * @return bool
673 public function unenrol_user($ue) {
674 global $DB;
675 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
676 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
677 $plugin->unenrol_user($instance, $ue->userid);
678 return true;
680 return false;
684 * Given a user enrolment record this method returns the plugin and enrolment
685 * instance that relate to it.
687 * @param stdClass|int $userenrolment
688 * @return array array($instance, $plugin)
690 public function get_user_enrolment_components($userenrolment) {
691 global $DB;
692 if (is_numeric($userenrolment)) {
693 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
695 $instances = $this->get_enrolment_instances();
696 $plugins = $this->get_enrolment_plugins(false);
697 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
698 return array(false, false);
700 $instance = $instances[$userenrolment->enrolid];
701 $plugin = $plugins[$instance->enrol];
702 return array($instance, $plugin);
706 * Removes an assigned role from a user.
708 * @global moodle_database $DB
709 * @param int $userid
710 * @param int $roleid
711 * @return bool
713 public function unassign_role_from_user($userid, $roleid) {
714 global $DB;
715 // Admins may unassign any role, others only those they could assign.
716 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
717 if (defined('AJAX_SCRIPT')) {
718 throw new moodle_exception('invalidrole');
720 return false;
722 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
723 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
724 foreach ($ras as $ra) {
725 if ($ra->component) {
726 if (strpos($ra->component, 'enrol_') !== 0) {
727 continue;
729 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
730 continue;
732 if ($plugin->roles_protected()) {
733 continue;
736 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
738 return true;
742 * Assigns a role to a user.
744 * @param int $roleid
745 * @param int $userid
746 * @return int|false
748 public function assign_role_to_user($roleid, $userid) {
749 require_capability('moodle/role:assign', $this->context);
750 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
751 if (defined('AJAX_SCRIPT')) {
752 throw new moodle_exception('invalidrole');
754 return false;
756 return role_assign($roleid, $userid, $this->context->id, '', NULL);
760 * Adds a user to a group
762 * @param stdClass $user
763 * @param int $groupid
764 * @return bool
766 public function add_user_to_group($user, $groupid) {
767 require_capability('moodle/course:managegroups', $this->context);
768 $group = $this->get_group($groupid);
769 if (!$group) {
770 return false;
772 return groups_add_member($group->id, $user->id);
776 * Removes a user from a group
778 * @global moodle_database $DB
779 * @param StdClass $user
780 * @param int $groupid
781 * @return bool
783 public function remove_user_from_group($user, $groupid) {
784 global $DB;
785 require_capability('moodle/course:managegroups', $this->context);
786 $group = $this->get_group($groupid);
787 if (!groups_remove_member_allowed($group, $user)) {
788 return false;
790 if (!$group) {
791 return false;
793 return groups_remove_member($group, $user);
797 * Gets the requested group
799 * @param int $groupid
800 * @return stdClass|int
802 public function get_group($groupid) {
803 $groups = $this->get_all_groups();
804 if (!array_key_exists($groupid, $groups)) {
805 return false;
807 return $groups[$groupid];
811 * Edits an enrolment
813 * @param stdClass $userenrolment
814 * @param stdClass $data
815 * @return bool
817 public function edit_enrolment($userenrolment, $data) {
818 //Only allow editing if the user has the appropriate capability
819 //Already checked in /user/index.php but checking again in case this function is called from elsewhere
820 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
821 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
822 if (!isset($data->status)) {
823 $data->status = $userenrolment->status;
825 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
826 return true;
828 return false;
832 * Returns the current enrolment filter that is being applied by this class
833 * @return string
835 public function get_enrolment_filter() {
836 return $this->instancefilter;
840 * Gets the roles assigned to this user that are applicable for this course.
842 * @param int $userid
843 * @return array
845 public function get_user_roles($userid) {
846 $roles = array();
847 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
848 $plugins = $this->get_enrolment_plugins(false);
849 foreach ($ras as $ra) {
850 if ($ra->contextid != $this->context->id) {
851 if (!array_key_exists($ra->roleid, $roles)) {
852 $roles[$ra->roleid] = null;
854 // higher ras, course always takes precedence
855 continue;
857 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
858 continue;
860 $changeable = true;
861 if ($ra->component) {
862 $changeable = false;
863 if (strpos($ra->component, 'enrol_') === 0) {
864 $plugin = substr($ra->component, 6);
865 if (isset($plugins[$plugin])) {
866 $changeable = !$plugins[$plugin]->roles_protected();
871 $roles[$ra->roleid] = $changeable;
873 return $roles;
877 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
879 * @global moodle_database $DB
880 * @param int $userid
881 * @return array
883 public function get_user_enrolments($userid) {
884 global $DB;
885 list($instancessql, $params, $filter) = $this->get_instance_sql();
886 $params['userid'] = $userid;
887 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
888 $instances = $this->get_enrolment_instances();
889 $plugins = $this->get_enrolment_plugins(false);
890 $inames = $this->get_enrolment_instance_names();
891 foreach ($userenrolments as &$ue) {
892 $ue->enrolmentinstance = $instances[$ue->enrolid];
893 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
894 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
896 return $userenrolments;
900 * Gets the groups this user belongs to
902 * @param int $userid
903 * @return array
905 public function get_user_groups($userid) {
906 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
910 * Retursn an array of params that would go into the URL to return to this
911 * exact page.
913 * @return array
915 public function get_url_params() {
916 $args = array(
917 'id' => $this->course->id
919 if (!empty($this->instancefilter)) {
920 $args['ifilter'] = $this->instancefilter;
922 if (!empty($this->rolefilter)) {
923 $args['role'] = $this->rolefilter;
925 if ($this->searchfilter !== '') {
926 $args['search'] = $this->searchfilter;
928 if (!empty($this->groupfilter)) {
929 $args['filtergroup'] = $this->groupfilter;
931 if ($this->statusfilter !== -1) {
932 $args['status'] = $this->statusfilter;
934 return $args;
938 * Returns the course this object is managing enrolments for
940 * @return stdClass
942 public function get_course() {
943 return $this->course;
947 * Returns the course context
949 * @return context
951 public function get_context() {
952 return $this->context;
956 * Gets an array of other users in this course ready for display.
958 * Other users are users who have been assigned or inherited roles within this
959 * course but have not been enrolled.
961 * @param core_enrol_renderer $renderer
962 * @param moodle_url $pageurl
963 * @param string $sort
964 * @param string $direction ASC | DESC
965 * @param int $page Starting from 0
966 * @param int $perpage
967 * @return array
969 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
971 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
972 $roles = $this->get_all_roles();
973 $plugins = $this->get_enrolment_plugins(false);
975 $context = $this->get_context();
976 $now = time();
977 $extrafields = get_extra_user_fields($context);
979 $users = array();
980 foreach ($userroles as $userrole) {
981 $contextid = $userrole->contextid;
982 unset($userrole->contextid); // This would collide with user avatar.
983 if (!array_key_exists($userrole->id, $users)) {
984 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
986 $a = new stdClass;
987 $a->role = $roles[$userrole->roleid]->localname;
988 if ($contextid == $this->context->id) {
989 $changeable = true;
990 if ($userrole->component) {
991 $changeable = false;
992 if (strpos($userrole->component, 'enrol_') === 0) {
993 $plugin = substr($userrole->component, 6);
994 if (isset($plugins[$plugin])) {
995 $changeable = !$plugins[$plugin]->roles_protected();
999 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
1000 } else {
1001 $changeable = false;
1002 switch ($userrole->contextlevel) {
1003 case CONTEXT_COURSE :
1004 // Meta course
1005 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
1006 break;
1007 case CONTEXT_COURSECAT :
1008 $roletext = get_string('rolefromcategory', 'enrol', $a);
1009 break;
1010 case CONTEXT_SYSTEM:
1011 default:
1012 $roletext = get_string('rolefromsystem', 'enrol', $a);
1013 break;
1016 if (!isset($users[$userrole->id]['roles'])) {
1017 $users[$userrole->id]['roles'] = array();
1019 $users[$userrole->id]['roles'][$userrole->roleid] = array(
1020 'text' => $roletext,
1021 'unchangeable' => !$changeable
1024 return $users;
1028 * Gets an array of users for display, this includes minimal user information
1029 * as well as minimal information on the users roles, groups, and enrolments.
1031 * @param core_enrol_renderer $renderer
1032 * @param moodle_url $pageurl
1033 * @param int $sort
1034 * @param string $direction ASC or DESC
1035 * @param int $page
1036 * @param int $perpage
1037 * @return array
1039 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1040 $pageurl = $manager->get_moodlepage()->url;
1041 $users = $this->get_users($sort, $direction, $page, $perpage);
1043 $now = time();
1044 $straddgroup = get_string('addgroup', 'group');
1045 $strunenrol = get_string('unenrol', 'enrol');
1046 $stredit = get_string('edit');
1048 $visibleroles = $this->get_viewable_roles();
1049 $assignable = $this->get_assignable_roles();
1050 $allgroups = $this->get_all_groups();
1051 $context = $this->get_context();
1052 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1054 $url = new moodle_url($pageurl, $this->get_url_params());
1055 $extrafields = get_extra_user_fields($context);
1057 $enabledplugins = $this->get_enrolment_plugins(true);
1059 $userdetails = array();
1060 foreach ($users as $user) {
1061 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1063 // Roles
1064 $details['roles'] = array();
1065 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1066 $unchangeable = !$rassignable;
1067 if (!is_siteadmin() and !isset($assignable[$rid])) {
1068 $unchangeable = true;
1071 if (isset($visibleroles[$rid])) {
1072 $label = $visibleroles[$rid];
1073 } else {
1074 $label = get_string('novisibleroles', 'role');
1075 $unchangeable = true;
1078 $details['roles'][$rid] = array('text' => $label, 'unchangeable' => $unchangeable);
1081 // Users
1082 $usergroups = $this->get_user_groups($user->id);
1083 $details['groups'] = array();
1084 foreach($usergroups as $gid=>$unused) {
1085 $details['groups'][$gid] = $allgroups[$gid]->name;
1088 // Enrolments
1089 $details['enrolments'] = array();
1090 foreach ($this->get_user_enrolments($user->id) as $ue) {
1091 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1092 $details['enrolments'][$ue->id] = array(
1093 'text' => $ue->enrolmentinstancename,
1094 'period' => null,
1095 'dimmed' => true,
1096 'actions' => array()
1098 continue;
1099 } else if ($ue->timestart and $ue->timeend) {
1100 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1101 $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1102 } else if ($ue->timestart) {
1103 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1104 $periodoutside = ($ue->timestart && $now < $ue->timestart);
1105 } else if ($ue->timeend) {
1106 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1107 $periodoutside = ($ue->timeend && $now > $ue->timeend);
1108 } else {
1109 // If there is no start or end show when user was enrolled.
1110 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1111 $periodoutside = false;
1113 $details['enrolments'][$ue->id] = array(
1114 'text' => $ue->enrolmentinstancename,
1115 'period' => $period,
1116 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1117 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1120 $userdetails[$user->id] = $details;
1122 return $userdetails;
1126 * Prepare a user record for display
1128 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1129 * prepare user fields for display
1131 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1133 * @param object $user The user record
1134 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1135 * additional fields may be displayed
1136 * @param int $now The time used for lastaccess calculation
1137 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1138 * additional fields from $extrafields
1140 private function prepare_user_for_display($user, $extrafields, $now) {
1141 $details = array(
1142 'userid' => $user->id,
1143 'courseid' => $this->get_course()->id,
1144 'picture' => new user_picture($user),
1145 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1146 'lastaccess' => get_string('never'),
1147 'lastcourseaccess' => get_string('never'),
1150 foreach ($extrafields as $field) {
1151 $details[$field] = $user->{$field};
1154 // Last time user has accessed the site.
1155 if (!empty($user->lastaccess)) {
1156 $details['lastaccess'] = format_time($now - $user->lastaccess);
1159 // Last time user has accessed the course.
1160 if (!empty($user->lastcourseaccess)) {
1161 $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess);
1163 return $details;
1166 public function get_manual_enrol_buttons() {
1167 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1168 $buttons = array();
1169 foreach ($plugins as $plugin) {
1170 $newbutton = $plugin->get_manual_enrol_button($this);
1171 if (is_array($newbutton)) {
1172 $buttons += $newbutton;
1173 } else if ($newbutton instanceof enrol_user_button) {
1174 $buttons[] = $newbutton;
1177 return $buttons;
1180 public function has_instance($enrolpluginname) {
1181 // Make sure manual enrolments instance exists
1182 foreach ($this->get_enrolment_instances() as $instance) {
1183 if ($instance->enrol == $enrolpluginname) {
1184 return true;
1187 return false;
1191 * Returns the enrolment plugin that the course manager was being filtered to.
1193 * If no filter was being applied then this function returns false.
1195 * @return enrol_plugin
1197 public function get_filtered_enrolment_plugin() {
1198 $instances = $this->get_enrolment_instances();
1199 $plugins = $this->get_enrolment_plugins(false);
1201 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1202 return false;
1205 $instance = $instances[$this->instancefilter];
1206 return $plugins[$instance->enrol];
1210 * Returns and array of users + enrolment details.
1212 * Given an array of user id's this function returns and array of user enrolments for those users
1213 * as well as enough user information to display the users name and picture for each enrolment.
1215 * @global moodle_database $DB
1216 * @param array $userids
1217 * @return array
1219 public function get_users_enrolments(array $userids) {
1220 global $DB;
1222 $instances = $this->get_enrolment_instances();
1223 $plugins = $this->get_enrolment_plugins(false);
1225 if (!empty($this->instancefilter)) {
1226 $instancesql = ' = :instanceid';
1227 $instanceparams = array('instanceid' => $this->instancefilter);
1228 } else {
1229 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1232 $userfields = user_picture::fields('u');
1233 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1235 list($sort, $sortparams) = users_order_by_sql('u');
1237 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1238 FROM {user_enrolments} ue
1239 LEFT JOIN {user} u ON u.id = ue.userid
1240 WHERE ue.enrolid $instancesql AND
1241 u.id $idsql
1242 ORDER BY $sort";
1244 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1245 $users = array();
1246 foreach ($rs as $ue) {
1247 $user = user_picture::unalias($ue);
1248 $ue->id = $ue->ueid;
1249 unset($ue->ueid);
1250 if (!array_key_exists($user->id, $users)) {
1251 $user->enrolments = array();
1252 $users[$user->id] = $user;
1254 $ue->enrolmentinstance = $instances[$ue->enrolid];
1255 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1256 $users[$user->id]->enrolments[$ue->id] = $ue;
1258 $rs->close();
1259 return $users;
1264 * A button that is used to enrol users in a course
1266 * @copyright 2010 Sam Hemelryk
1267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1269 class enrol_user_button extends single_button {
1272 * An array containing JS YUI modules required by this button
1273 * @var array
1275 protected $jsyuimodules = array();
1278 * An array containing JS initialisation calls required by this button
1279 * @var array
1281 protected $jsinitcalls = array();
1284 * An array strings required by JS for this button
1285 * @var array
1287 protected $jsstrings = array();
1290 * Initialises the new enrol_user_button
1292 * @staticvar int $count The number of enrol user buttons already created
1293 * @param moodle_url $url
1294 * @param string $label The text to display in the button
1295 * @param string $method Either post or get
1297 public function __construct(moodle_url $url, $label, $method = 'post') {
1298 static $count = 0;
1299 $count ++;
1300 parent::__construct($url, $label, $method);
1301 $this->class = 'singlebutton enrolusersbutton';
1302 $this->formid = 'enrolusersbutton-'.$count;
1306 * Adds a YUI module call that will be added to the page when the button is used.
1308 * @param string|array $modules One or more modules to require
1309 * @param string $function The JS function to call
1310 * @param array $arguments An array of arguments to pass to the function
1311 * @param string $galleryversion Deprecated: The gallery version to use
1312 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1314 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1315 if ($galleryversion != null) {
1316 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1319 $js = new stdClass;
1320 $js->modules = (array)$modules;
1321 $js->function = $function;
1322 $js->arguments = $arguments;
1323 $js->ondomready = $ondomready;
1324 $this->jsyuimodules[] = $js;
1328 * Adds a JS initialisation call to the page when the button is used.
1330 * @param string $function The function to call
1331 * @param array $extraarguments An array of arguments to pass to the function
1332 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1333 * @param array $module A module definition
1335 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1336 $js = new stdClass;
1337 $js->function = $function;
1338 $js->extraarguments = $extraarguments;
1339 $js->ondomready = $ondomready;
1340 $js->module = $module;
1341 $this->jsinitcalls[] = $js;
1345 * Requires strings for JS that will be loaded when the button is used.
1347 * @param type $identifiers
1348 * @param string $component
1349 * @param mixed $a
1351 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1352 $string = new stdClass;
1353 $string->identifiers = (array)$identifiers;
1354 $string->component = $component;
1355 $string->a = $a;
1356 $this->jsstrings[] = $string;
1360 * Initialises the JS that is required by this button
1362 * @param moodle_page $page
1364 public function initialise_js(moodle_page $page) {
1365 foreach ($this->jsyuimodules as $js) {
1366 $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1368 foreach ($this->jsinitcalls as $js) {
1369 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1371 foreach ($this->jsstrings as $string) {
1372 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1378 * User enrolment action
1380 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1381 * a user enrolment.
1383 * @copyright 2011 Sam Hemelryk
1384 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1386 class user_enrolment_action implements renderable {
1389 * The icon to display for the action
1390 * @var pix_icon
1392 protected $icon;
1395 * The title for the action
1396 * @var string
1398 protected $title;
1401 * The URL to the action
1402 * @var moodle_url
1404 protected $url;
1407 * An array of HTML attributes
1408 * @var array
1410 protected $attributes = array();
1413 * Constructor
1414 * @param pix_icon $icon
1415 * @param string $title
1416 * @param moodle_url $url
1417 * @param array $attributes
1419 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1420 $this->icon = $icon;
1421 $this->title = $title;
1422 $this->url = new moodle_url($url);
1423 if (!empty($attributes)) {
1424 $this->attributes = $attributes;
1426 $this->attributes['title'] = $title;
1430 * Returns the icon for this action
1431 * @return pix_icon
1433 public function get_icon() {
1434 return $this->icon;
1438 * Returns the title for this action
1439 * @return string
1441 public function get_title() {
1442 return $this->title;
1446 * Returns the URL for this action
1447 * @return moodle_url
1449 public function get_url() {
1450 return $this->url;
1454 * Returns the attributes to use for this action
1455 * @return array
1457 public function get_attributes() {
1458 return $this->attributes;
1462 class enrol_ajax_exception extends moodle_exception {
1464 * Constructor
1465 * @param string $errorcode The name of the string from error.php to print
1466 * @param string $module name of module
1467 * @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.
1468 * @param object $a Extra words and phrases that might be required in the error string
1469 * @param string $debuginfo optional debugging information
1471 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1472 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1477 * This class is used to manage a bulk operations for enrolment plugins.
1479 * @copyright 2011 Sam Hemelryk
1480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1482 abstract class enrol_bulk_enrolment_operation {
1485 * The course enrolment manager
1486 * @var course_enrolment_manager
1488 protected $manager;
1491 * The enrolment plugin to which this operation belongs
1492 * @var enrol_plugin
1494 protected $plugin;
1497 * Contructor
1498 * @param course_enrolment_manager $manager
1499 * @param stdClass $plugin
1501 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1502 $this->manager = $manager;
1503 $this->plugin = $plugin;
1507 * Returns a moodleform used for this operation, or false if no form is required and the action
1508 * should be immediatly processed.
1510 * @param moodle_url|string $defaultaction
1511 * @param mixed $defaultcustomdata
1512 * @return enrol_bulk_enrolment_change_form|moodleform|false
1514 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1515 return false;
1519 * Returns the title to use for this bulk operation
1521 * @return string
1523 abstract public function get_title();
1526 * Returns the identifier for this bulk operation.
1527 * This should be the same identifier used by the plugins function when returning
1528 * all of its bulk operations.
1530 * @return string
1532 abstract public function get_identifier();
1535 * Processes the bulk operation on the given users
1537 * @param course_enrolment_manager $manager
1538 * @param array $users
1539 * @param stdClass $properties
1541 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);