MDL-35603 backup: fix coding style issues
[moodle.git] / enrol / locallib.php
blob3f6a50622fbc14a55cd5ed7d2bea276d8f760f30
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This file contains the course_enrolment_manager class which is used to interface
20 * with the functions that exist in enrollib.php in relation to a single course.
22 * @package core
23 * @subpackage enrol
24 * @copyright 2010 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 /**
31 * This class provides a targeted tied together means of interfacing the enrolment
32 * tasks together with a course.
34 * It is provided as a convenience more than anything else.
36 * @copyright 2010 Sam Hemelryk
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 class course_enrolment_manager {
41 /**
42 * The course context
43 * @var stdClass
45 protected $context;
46 /**
47 * The course we are managing enrolments for
48 * @var stdClass
50 protected $course = null;
51 /**
52 * Limits the focus of the manager to one enrolment plugin instance
53 * @var string
55 protected $instancefilter = null;
57 /**
58 * The total number of users enrolled in the course
59 * Populated by course_enrolment_manager::get_total_users
60 * @var int
62 protected $totalusers = null;
63 /**
64 * An array of users currently enrolled in the course
65 * Populated by course_enrolment_manager::get_users
66 * @var array
68 protected $users = array();
70 /**
71 * An array of users who have roles within this course but who have not
72 * been enrolled in the course
73 * @var array
75 protected $otherusers = array();
77 /**
78 * The total number of users who hold a role within the course but who
79 * arn't enrolled.
80 * @var int
82 protected $totalotherusers = null;
84 /**
85 * The current moodle_page object
86 * @var moodle_page
88 protected $moodlepage = null;
90 /**#@+
91 * These variables are used to cache the information this class uses
92 * please never use these directly instead use their get_ counterparts.
93 * @access private
94 * @var array
96 private $_instancessql = null;
97 private $_instances = null;
98 private $_inames = null;
99 private $_plugins = null;
100 private $_allplugins = null;
101 private $_roles = null;
102 private $_assignableroles = null;
103 private $_assignablerolesothers = null;
104 private $_groups = null;
105 /**#@-*/
108 * Constructs the course enrolment manager
110 * @param moodle_page $moodlepage
111 * @param stdClass $course
112 * @param string $instancefilter
114 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null) {
115 $this->moodlepage = $moodlepage;
116 $this->context = context_course::instance($course->id);
117 $this->course = $course;
118 $this->instancefilter = $instancefilter;
122 * Returns the current moodle page
123 * @return moodle_page
125 public function get_moodlepage() {
126 return $this->moodlepage;
130 * Returns the total number of enrolled users in the course.
132 * If a filter was specificed this will be the total number of users enrolled
133 * in this course by means of that instance.
135 * @global moodle_database $DB
136 * @return int
138 public function get_total_users() {
139 global $DB;
140 if ($this->totalusers === null) {
141 list($instancessql, $params, $filter) = $this->get_instance_sql();
142 $sqltotal = "SELECT COUNT(DISTINCT u.id)
143 FROM {user} u
144 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
145 JOIN {enrol} e ON (e.id = ue.enrolid)";
146 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
148 return $this->totalusers;
152 * Returns the total number of enrolled users in the course.
154 * If a filter was specificed this will be the total number of users enrolled
155 * in this course by means of that instance.
157 * @global moodle_database $DB
158 * @return int
160 public function get_total_other_users() {
161 global $DB;
162 if ($this->totalotherusers === null) {
163 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
164 $params['courseid'] = $this->course->id;
165 $sql = "SELECT COUNT(DISTINCT u.id)
166 FROM {role_assignments} ra
167 JOIN {user} u ON u.id = ra.userid
168 JOIN {context} ctx ON ra.contextid = ctx.id
169 LEFT JOIN (
170 SELECT ue.id, ue.userid
171 FROM {user_enrolments} ue
172 LEFT JOIN {enrol} e ON e.id=ue.enrolid
173 WHERE e.courseid = :courseid
174 ) ue ON ue.userid=u.id
175 WHERE ctx.id $ctxcondition AND
176 ue.id IS NULL";
177 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
179 return $this->totalotherusers;
183 * Gets all of the users enrolled in this course.
185 * If a filter was specified this will be the users who were enrolled
186 * in this course by means of that instance.
188 * @global moodle_database $DB
189 * @param string $sort
190 * @param string $direction ASC or DESC
191 * @param int $page First page should be 0
192 * @param int $perpage Defaults to 25
193 * @return array
195 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
196 global $DB;
197 if ($direction !== 'ASC') {
198 $direction = 'DESC';
200 $key = md5("$sort-$direction-$page-$perpage");
201 if (!array_key_exists($key, $this->users)) {
202 list($instancessql, $params, $filter) = $this->get_instance_sql();
203 $extrafields = get_extra_user_fields($this->get_context());
204 $extrafields[] = 'lastaccess';
205 $ufields = user_picture::fields('u', $extrafields);
206 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
207 FROM {user} u
208 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
209 JOIN {enrol} e ON (e.id = ue.enrolid)
210 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
211 if ($sort === 'firstname') {
212 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
213 } else if ($sort === 'lastname') {
214 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
215 } else if ($sort === 'email') {
216 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
217 } else if ($sort === 'lastseen') {
218 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
220 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
222 return $this->users[$key];
226 * Gets and array of other users.
228 * Other users are users who have been assigned roles or inherited roles
229 * within this course but who have not been enrolled in the course
231 * @global moodle_database $DB
232 * @param string $sort
233 * @param string $direction
234 * @param int $page
235 * @param int $perpage
236 * @return array
238 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
239 global $DB;
240 if ($direction !== 'ASC') {
241 $direction = 'DESC';
243 $key = md5("$sort-$direction-$page-$perpage");
244 if (!array_key_exists($key, $this->otherusers)) {
245 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
246 $params['courseid'] = $this->course->id;
247 $params['cid'] = $this->course->id;
248 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
249 FROM {role_assignments} ra
250 JOIN {user} u ON u.id = ra.userid
251 JOIN {context} ctx ON ra.contextid = ctx.id
252 LEFT JOIN (
253 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
254 FROM {user_enrolments} ue
255 LEFT JOIN {enrol} e ON e.id=ue.enrolid
256 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
257 WHERE e.courseid = :courseid
258 ) ue ON ue.userid=u.id
259 WHERE ctx.id $ctxcondition AND
260 ue.id IS NULL
261 ORDER BY u.$sort $direction, ctx.depth DESC";
262 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
264 return $this->otherusers[$key];
268 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
270 * @param string $search the search term, if any.
271 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
272 * @return array with three elements:
273 * string list of fields to SELECT,
274 * string contents of SQL WHERE clause,
275 * array query params. Note that the SQL snippets use named parameters.
277 protected function get_basic_search_conditions($search, $searchanywhere) {
278 global $DB, $CFG;
280 // Add some additional sensible conditions
281 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
282 $params = array('guestid' => $CFG->siteguest);
283 if (!empty($search)) {
284 $conditions = get_extra_user_fields($this->get_context());
285 $conditions[] = 'u.firstname';
286 $conditions[] = 'u.lastname';
287 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
288 if ($searchanywhere) {
289 $searchparam = '%' . $search . '%';
290 } else {
291 $searchparam = $search . '%';
293 $i = 0;
294 foreach ($conditions as $key => $condition) {
295 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
296 $params["con{$i}00"] = $searchparam;
297 $i++;
299 $tests[] = '(' . implode(' OR ', $conditions) . ')';
301 $wherecondition = implode(' AND ', $tests);
303 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
304 $extrafields[] = 'username';
305 $extrafields[] = 'lastaccess';
306 $ufields = user_picture::fields('u', $extrafields);
308 return array($ufields, $params, $wherecondition);
312 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
314 * @param string $search the search string, if any.
315 * @param string $fields the first bit of the SQL when returning some users.
316 * @param string $countfields fhe first bit of the SQL when counting the users.
317 * @param string $sql the bulk of the SQL statement.
318 * @param array $params query parameters.
319 * @param int $page which page number of the results to show.
320 * @param int $perpage number of users per page.
321 * @param int $addedenrollment number of users added to enrollment.
322 * @return array with two elememts:
323 * int total number of users matching the search.
324 * array of user objects returned by the query.
326 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
327 global $DB, $CFG;
329 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
330 $order = ' ORDER BY ' . $sort;
332 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
333 $availableusers = $DB->get_records_sql($fields . $sql . $order,
334 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
336 return array('totalusers' => $totalusers, 'users' => $availableusers);
340 * Gets an array of the users that can be enrolled in this course.
342 * @global moodle_database $DB
343 * @param int $enrolid
344 * @param string $search
345 * @param bool $searchanywhere
346 * @param int $page Defaults to 0
347 * @param int $perpage Defaults to 25
348 * @param int $addedenrollment Defaults to 0
349 * @return array Array(totalusers => int, users => array)
351 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
352 global $DB;
354 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
356 $fields = 'SELECT '.$ufields;
357 $countfields = 'SELECT COUNT(1)';
358 $sql = " FROM {user} u
359 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
360 WHERE $wherecondition
361 AND ue.id IS NULL";
362 $params['enrolid'] = $enrolid;
364 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
368 * Searches other users and returns paginated results
370 * @global moodle_database $DB
371 * @param string $search
372 * @param bool $searchanywhere
373 * @param int $page Starting at 0
374 * @param int $perpage
375 * @return array
377 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
378 global $DB, $CFG;
380 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
382 $fields = 'SELECT ' . $ufields;
383 $countfields = 'SELECT COUNT(u.id)';
384 $sql = " FROM {user} u
385 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
386 WHERE $wherecondition
387 AND ra.id IS NULL";
388 $params['contextid'] = $this->context->id;
390 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
394 * Gets an array containing some SQL to user for when selecting, params for
395 * that SQL, and the filter that was used in constructing the sql.
397 * @global moodle_database $DB
398 * @return string
400 protected function get_instance_sql() {
401 global $DB;
402 if ($this->_instancessql === null) {
403 $instances = $this->get_enrolment_instances();
404 $filter = $this->get_enrolment_filter();
405 if ($filter && array_key_exists($filter, $instances)) {
406 $sql = " = :ifilter";
407 $params = array('ifilter'=>$filter);
408 } else {
409 $filter = 0;
410 if ($instances) {
411 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
412 } else {
413 // no enabled instances, oops, we should probably say something
414 $sql = "= :never";
415 $params = array('never'=>-1);
418 $this->instancefilter = $filter;
419 $this->_instancessql = array($sql, $params, $filter);
421 return $this->_instancessql;
425 * Returns all of the enrolment instances for this course.
427 * NOTE: since 2.4 it includes instances of disabled plugins too.
429 * @return array
431 public function get_enrolment_instances() {
432 if ($this->_instances === null) {
433 $this->_instances = enrol_get_instances($this->course->id, false);
435 return $this->_instances;
439 * Returns the names for all of the enrolment instances for this course.
441 * NOTE: since 2.4 it includes instances of disabled plugins too.
443 * @return array
445 public function get_enrolment_instance_names() {
446 if ($this->_inames === null) {
447 $instances = $this->get_enrolment_instances();
448 $plugins = $this->get_enrolment_plugins(false);
449 foreach ($instances as $key=>$instance) {
450 if (!isset($plugins[$instance->enrol])) {
451 // weird, some broken stuff in plugin
452 unset($instances[$key]);
453 continue;
455 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
458 return $this->_inames;
462 * Gets all of the enrolment plugins that are active for this course.
464 * @param bool $onlyenabled return only enabled enrol plugins
465 * @return array
467 public function get_enrolment_plugins($onlyenabled = true) {
468 if ($this->_plugins === null) {
469 $this->_plugins = enrol_get_plugins(true);
472 if ($onlyenabled) {
473 return $this->_plugins;
476 if ($this->_allplugins === null) {
477 // Make sure we have the same objects in _allplugins and _plugins.
478 $this->_allplugins = $this->_plugins;
479 foreach (enrol_get_plugins(false) as $name=>$plugin) {
480 if (!isset($this->_allplugins[$name])) {
481 $this->_allplugins[$name] = $plugin;
486 return $this->_allplugins;
490 * Gets all of the roles this course can contain.
492 * @return array
494 public function get_all_roles() {
495 if ($this->_roles === null) {
496 $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
498 return $this->_roles;
502 * Gets all of the assignable roles for this course.
504 * @return array
506 public function get_assignable_roles($otherusers = false) {
507 if ($this->_assignableroles === null) {
508 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
511 if ($otherusers) {
512 if (!is_array($this->_assignablerolesothers)) {
513 $this->_assignablerolesothers = array();
514 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
515 foreach ($this->_assignableroles as $roleid=>$role) {
516 if (isset($courseviewroles[$roleid])) {
517 $this->_assignablerolesothers[$roleid] = $role;
521 return $this->_assignablerolesothers;
522 } else {
523 return $this->_assignableroles;
528 * Gets all of the groups for this course.
530 * @return array
532 public function get_all_groups() {
533 if ($this->_groups === null) {
534 $this->_groups = groups_get_all_groups($this->course->id);
535 foreach ($this->_groups as $gid=>$group) {
536 $this->_groups[$gid]->name = format_string($group->name);
539 return $this->_groups;
543 * Unenrols a user from the course given the users ue entry
545 * @global moodle_database $DB
546 * @param stdClass $ue
547 * @return bool
549 public function unenrol_user($ue) {
550 global $DB;
551 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
552 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
553 $plugin->unenrol_user($instance, $ue->userid);
554 return true;
556 return false;
560 * Given a user enrolment record this method returns the plugin and enrolment
561 * instance that relate to it.
563 * @param stdClass|int $userenrolment
564 * @return array array($instance, $plugin)
566 public function get_user_enrolment_components($userenrolment) {
567 global $DB;
568 if (is_numeric($userenrolment)) {
569 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
571 $instances = $this->get_enrolment_instances();
572 $plugins = $this->get_enrolment_plugins(false);
573 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
574 return array(false, false);
576 $instance = $instances[$userenrolment->enrolid];
577 $plugin = $plugins[$instance->enrol];
578 return array($instance, $plugin);
582 * Removes an assigned role from a user.
584 * @global moodle_database $DB
585 * @param int $userid
586 * @param int $roleid
587 * @return bool
589 public function unassign_role_from_user($userid, $roleid) {
590 global $DB;
591 // Admins may unassign any role, others only those they could assign.
592 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
593 if (defined('AJAX_SCRIPT')) {
594 throw new moodle_exception('invalidrole');
596 return false;
598 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
599 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
600 foreach ($ras as $ra) {
601 if ($ra->component) {
602 if (strpos($ra->component, 'enrol_') !== 0) {
603 continue;
605 if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
606 continue;
608 if ($plugin->roles_protected()) {
609 continue;
612 role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
614 return true;
618 * Assigns a role to a user.
620 * @param int $roleid
621 * @param int $userid
622 * @return int|false
624 public function assign_role_to_user($roleid, $userid) {
625 require_capability('moodle/role:assign', $this->context);
626 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
627 if (defined('AJAX_SCRIPT')) {
628 throw new moodle_exception('invalidrole');
630 return false;
632 return role_assign($roleid, $userid, $this->context->id, '', NULL);
636 * Adds a user to a group
638 * @param stdClass $user
639 * @param int $groupid
640 * @return bool
642 public function add_user_to_group($user, $groupid) {
643 require_capability('moodle/course:managegroups', $this->context);
644 $group = $this->get_group($groupid);
645 if (!$group) {
646 return false;
648 return groups_add_member($group->id, $user->id);
652 * Removes a user from a group
654 * @global moodle_database $DB
655 * @param StdClass $user
656 * @param int $groupid
657 * @return bool
659 public function remove_user_from_group($user, $groupid) {
660 global $DB;
661 require_capability('moodle/course:managegroups', $this->context);
662 $group = $this->get_group($groupid);
663 if (!groups_remove_member_allowed($group, $user)) {
664 return false;
666 if (!$group) {
667 return false;
669 return groups_remove_member($group, $user);
673 * Gets the requested group
675 * @param int $groupid
676 * @return stdClass|int
678 public function get_group($groupid) {
679 $groups = $this->get_all_groups();
680 if (!array_key_exists($groupid, $groups)) {
681 return false;
683 return $groups[$groupid];
687 * Edits an enrolment
689 * @param stdClass $userenrolment
690 * @param stdClass $data
691 * @return bool
693 public function edit_enrolment($userenrolment, $data) {
694 //Only allow editing if the user has the appropriate capability
695 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
696 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
697 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
698 if (!isset($data->status)) {
699 $data->status = $userenrolment->status;
701 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
702 return true;
704 return false;
708 * Returns the current enrolment filter that is being applied by this class
709 * @return string
711 public function get_enrolment_filter() {
712 return $this->instancefilter;
716 * Gets the roles assigned to this user that are applicable for this course.
718 * @param int $userid
719 * @return array
721 public function get_user_roles($userid) {
722 $roles = array();
723 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
724 $plugins = $this->get_enrolment_plugins(false);
725 foreach ($ras as $ra) {
726 if ($ra->contextid != $this->context->id) {
727 if (!array_key_exists($ra->roleid, $roles)) {
728 $roles[$ra->roleid] = null;
730 // higher ras, course always takes precedence
731 continue;
733 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
734 continue;
736 $changeable = true;
737 if ($ra->component) {
738 $changeable = false;
739 if (strpos($ra->component, 'enrol_') === 0) {
740 $plugin = substr($ra->component, 6);
741 if (isset($plugins[$plugin])) {
742 $changeable = !$plugins[$plugin]->roles_protected();
747 $roles[$ra->roleid] = $changeable;
749 return $roles;
753 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
755 * @global moodle_database $DB
756 * @param int $userid
757 * @return array
759 public function get_user_enrolments($userid) {
760 global $DB;
761 list($instancessql, $params, $filter) = $this->get_instance_sql();
762 $params['userid'] = $userid;
763 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
764 $instances = $this->get_enrolment_instances();
765 $plugins = $this->get_enrolment_plugins(false);
766 $inames = $this->get_enrolment_instance_names();
767 foreach ($userenrolments as &$ue) {
768 $ue->enrolmentinstance = $instances[$ue->enrolid];
769 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
770 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
772 return $userenrolments;
776 * Gets the groups this user belongs to
778 * @param int $userid
779 * @return array
781 public function get_user_groups($userid) {
782 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
786 * Retursn an array of params that would go into the URL to return to this
787 * exact page.
789 * @return array
791 public function get_url_params() {
792 $args = array(
793 'id' => $this->course->id
795 if (!empty($this->instancefilter)) {
796 $args['ifilter'] = $this->instancefilter;
798 return $args;
802 * Returns the course this object is managing enrolments for
804 * @return stdClass
806 public function get_course() {
807 return $this->course;
811 * Returns the course context
813 * @return stdClass
815 public function get_context() {
816 return $this->context;
820 * Gets an array of other users in this course ready for display.
822 * Other users are users who have been assigned or inherited roles within this
823 * course but have not been enrolled.
825 * @param core_enrol_renderer $renderer
826 * @param moodle_url $pageurl
827 * @param string $sort
828 * @param string $direction ASC | DESC
829 * @param int $page Starting from 0
830 * @param int $perpage
831 * @return array
833 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
835 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
836 $roles = $this->get_all_roles();
837 $plugins = $this->get_enrolment_plugins(false);
839 $context = $this->get_context();
840 $now = time();
841 $extrafields = get_extra_user_fields($context);
843 $users = array();
844 foreach ($userroles as $userrole) {
845 $contextid = $userrole->contextid;
846 unset($userrole->contextid); // This would collide with user avatar.
847 if (!array_key_exists($userrole->id, $users)) {
848 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
850 $a = new stdClass;
851 $a->role = $roles[$userrole->roleid]->localname;
852 if ($contextid == $this->context->id) {
853 $changeable = true;
854 if ($userrole->component) {
855 $changeable = false;
856 if (strpos($userrole->component, 'enrol_') === 0) {
857 $plugin = substr($userrole->component, 6);
858 if (isset($plugins[$plugin])) {
859 $changeable = !$plugin[$plugin]->roles_protected();
863 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
864 } else {
865 $changeable = false;
866 switch ($userrole->contextlevel) {
867 case CONTEXT_COURSE :
868 // Meta course
869 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
870 break;
871 case CONTEXT_COURSECAT :
872 $roletext = get_string('rolefromcategory', 'enrol', $a);
873 break;
874 case CONTEXT_SYSTEM:
875 default:
876 $roletext = get_string('rolefromsystem', 'enrol', $a);
877 break;
880 if (!isset($users[$userrole->id]['roles'])) {
881 $users[$userrole->id]['roles'] = array();
883 $users[$userrole->id]['roles'][$userrole->roleid] = array(
884 'text' => $roletext,
885 'unchangeable' => !$changeable
888 return $users;
892 * Gets an array of users for display, this includes minimal user information
893 * as well as minimal information on the users roles, groups, and enrolments.
895 * @param core_enrol_renderer $renderer
896 * @param moodle_url $pageurl
897 * @param int $sort
898 * @param string $direction ASC or DESC
899 * @param int $page
900 * @param int $perpage
901 * @return array
903 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
904 $pageurl = $manager->get_moodlepage()->url;
905 $users = $this->get_users($sort, $direction, $page, $perpage);
907 $now = time();
908 $straddgroup = get_string('addgroup', 'group');
909 $strunenrol = get_string('unenrol', 'enrol');
910 $stredit = get_string('edit');
912 $allroles = $this->get_all_roles();
913 $assignable = $this->get_assignable_roles();
914 $allgroups = $this->get_all_groups();
915 $context = $this->get_context();
916 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
918 $url = new moodle_url($pageurl, $this->get_url_params());
919 $extrafields = get_extra_user_fields($context);
921 $enabledplugins = $this->get_enrolment_plugins(true);
923 $userdetails = array();
924 foreach ($users as $user) {
925 $details = $this->prepare_user_for_display($user, $extrafields, $now);
927 // Roles
928 $details['roles'] = array();
929 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
930 $unchangeable = !$rassignable;
931 if (!is_siteadmin() and !isset($assignable[$rid])) {
932 $unchangeable = true;
934 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>$unchangeable);
937 // Users
938 $usergroups = $this->get_user_groups($user->id);
939 $details['groups'] = array();
940 foreach($usergroups as $gid=>$unused) {
941 $details['groups'][$gid] = $allgroups[$gid]->name;
944 // Enrolments
945 $details['enrolments'] = array();
946 foreach ($this->get_user_enrolments($user->id) as $ue) {
947 if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
948 $details['enrolments'][$ue->id] = array(
949 'text' => $ue->enrolmentinstancename,
950 'period' => null,
951 'dimmed' => true,
952 'actions' => array()
954 continue;
955 } else if ($ue->timestart and $ue->timeend) {
956 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
957 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
958 } else if ($ue->timestart) {
959 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
960 $periodoutside = ($ue->timestart && $now < $ue->timestart);
961 } else if ($ue->timeend) {
962 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
963 $periodoutside = ($ue->timeend && $now > $ue->timeend);
964 } else {
965 // If there is no start or end show when user was enrolled.
966 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
967 $periodoutside = false;
969 $details['enrolments'][$ue->id] = array(
970 'text' => $ue->enrolmentinstancename,
971 'period' => $period,
972 'dimmed' => ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
973 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
976 $userdetails[$user->id] = $details;
978 return $userdetails;
982 * Prepare a user record for display
984 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
985 * prepare user fields for display
987 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
989 * @param object $user The user record
990 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
991 * additional fields may be displayed
992 * @param int $now The time used for lastaccess calculation
993 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
994 * additional fields from $extrafields
996 private function prepare_user_for_display($user, $extrafields, $now) {
997 $details = array(
998 'userid' => $user->id,
999 'courseid' => $this->get_course()->id,
1000 'picture' => new user_picture($user),
1001 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1002 'lastseen' => get_string('never'),
1004 foreach ($extrafields as $field) {
1005 $details[$field] = $user->{$field};
1008 if ($user->lastaccess) {
1009 $details['lastseen'] = format_time($now - $user->lastaccess);
1011 return $details;
1014 public function get_manual_enrol_buttons() {
1015 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1016 $buttons = array();
1017 foreach ($plugins as $plugin) {
1018 $newbutton = $plugin->get_manual_enrol_button($this);
1019 if (is_array($newbutton)) {
1020 $buttons += $newbutton;
1021 } else if ($newbutton instanceof enrol_user_button) {
1022 $buttons[] = $newbutton;
1025 return $buttons;
1028 public function has_instance($enrolpluginname) {
1029 // Make sure manual enrolments instance exists
1030 foreach ($this->get_enrolment_instances() as $instance) {
1031 if ($instance->enrol == $enrolpluginname) {
1032 return true;
1035 return false;
1039 * Returns the enrolment plugin that the course manager was being filtered to.
1041 * If no filter was being applied then this function returns false.
1043 * @return enrol_plugin
1045 public function get_filtered_enrolment_plugin() {
1046 $instances = $this->get_enrolment_instances();
1047 $plugins = $this->get_enrolment_plugins(false);
1049 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1050 return false;
1053 $instance = $instances[$this->instancefilter];
1054 return $plugins[$instance->enrol];
1058 * Returns and array of users + enrolment details.
1060 * Given an array of user id's this function returns and array of user enrolments for those users
1061 * as well as enough user information to display the users name and picture for each enrolment.
1063 * @global moodle_database $DB
1064 * @param array $userids
1065 * @return array
1067 public function get_users_enrolments(array $userids) {
1068 global $DB;
1070 $instances = $this->get_enrolment_instances();
1071 $plugins = $this->get_enrolment_plugins(false);
1073 if (!empty($this->instancefilter)) {
1074 $instancesql = ' = :instanceid';
1075 $instanceparams = array('instanceid' => $this->instancefilter);
1076 } else {
1077 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1080 $userfields = user_picture::fields('u');
1081 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1083 list($sort, $sortparams) = users_order_by_sql('u');
1085 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1086 FROM {user_enrolments} ue
1087 LEFT JOIN {user} u ON u.id = ue.userid
1088 WHERE ue.enrolid $instancesql AND
1089 u.id $idsql
1090 ORDER BY $sort";
1092 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1093 $users = array();
1094 foreach ($rs as $ue) {
1095 $user = user_picture::unalias($ue);
1096 $ue->id = $ue->ueid;
1097 unset($ue->ueid);
1098 if (!array_key_exists($user->id, $users)) {
1099 $user->enrolments = array();
1100 $users[$user->id] = $user;
1102 $ue->enrolmentinstance = $instances[$ue->enrolid];
1103 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1104 $users[$user->id]->enrolments[$ue->id] = $ue;
1106 $rs->close();
1107 return $users;
1112 * A button that is used to enrol users in a course
1114 * @copyright 2010 Sam Hemelryk
1115 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1117 class enrol_user_button extends single_button {
1120 * An array containing JS YUI modules required by this button
1121 * @var array
1123 protected $jsyuimodules = array();
1126 * An array containing JS initialisation calls required by this button
1127 * @var array
1129 protected $jsinitcalls = array();
1132 * An array strings required by JS for this button
1133 * @var array
1135 protected $jsstrings = array();
1138 * Initialises the new enrol_user_button
1140 * @staticvar int $count The number of enrol user buttons already created
1141 * @param moodle_url $url
1142 * @param string $label The text to display in the button
1143 * @param string $method Either post or get
1145 public function __construct(moodle_url $url, $label, $method = 'post') {
1146 static $count = 0;
1147 $count ++;
1148 parent::__construct($url, $label, $method);
1149 $this->class = 'singlebutton enrolusersbutton';
1150 $this->formid = 'enrolusersbutton-'.$count;
1154 * Adds a YUI module call that will be added to the page when the button is used.
1156 * @param string|array $modules One or more modules to require
1157 * @param string $function The JS function to call
1158 * @param array $arguments An array of arguments to pass to the function
1159 * @param string $galleryversion The YUI gallery version of any modules required
1160 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1162 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1163 $js = new stdClass;
1164 $js->modules = (array)$modules;
1165 $js->function = $function;
1166 $js->arguments = $arguments;
1167 $js->galleryversion = $galleryversion;
1168 $js->ondomready = $ondomready;
1169 $this->jsyuimodules[] = $js;
1173 * Adds a JS initialisation call to the page when the button is used.
1175 * @param string $function The function to call
1176 * @param array $extraarguments An array of arguments to pass to the function
1177 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1178 * @param array $module A module definition
1180 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1181 $js = new stdClass;
1182 $js->function = $function;
1183 $js->extraarguments = $extraarguments;
1184 $js->ondomready = $ondomready;
1185 $js->module = $module;
1186 $this->jsinitcalls[] = $js;
1190 * Requires strings for JS that will be loaded when the button is used.
1192 * @param type $identifiers
1193 * @param string $component
1194 * @param mixed $a
1196 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1197 $string = new stdClass;
1198 $string->identifiers = (array)$identifiers;
1199 $string->component = $component;
1200 $string->a = $a;
1201 $this->jsstrings[] = $string;
1205 * Initialises the JS that is required by this button
1207 * @param moodle_page $page
1209 public function initialise_js(moodle_page $page) {
1210 foreach ($this->jsyuimodules as $js) {
1211 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1213 foreach ($this->jsinitcalls as $js) {
1214 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1216 foreach ($this->jsstrings as $string) {
1217 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1223 * User enrolment action
1225 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1226 * a user enrolment.
1228 * @copyright 2011 Sam Hemelryk
1229 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1231 class user_enrolment_action implements renderable {
1234 * The icon to display for the action
1235 * @var pix_icon
1237 protected $icon;
1240 * The title for the action
1241 * @var string
1243 protected $title;
1246 * The URL to the action
1247 * @var moodle_url
1249 protected $url;
1252 * An array of HTML attributes
1253 * @var array
1255 protected $attributes = array();
1258 * Constructor
1259 * @param pix_icon $icon
1260 * @param string $title
1261 * @param moodle_url $url
1262 * @param array $attributes
1264 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1265 $this->icon = $icon;
1266 $this->title = $title;
1267 $this->url = new moodle_url($url);
1268 if (!empty($attributes)) {
1269 $this->attributes = $attributes;
1271 $this->attributes['title'] = $title;
1275 * Returns the icon for this action
1276 * @return pix_icon
1278 public function get_icon() {
1279 return $this->icon;
1283 * Returns the title for this action
1284 * @return string
1286 public function get_title() {
1287 return $this->title;
1291 * Returns the URL for this action
1292 * @return moodle_url
1294 public function get_url() {
1295 return $this->url;
1299 * Returns the attributes to use for this action
1300 * @return array
1302 public function get_attributes() {
1303 return $this->attributes;
1307 class enrol_ajax_exception extends moodle_exception {
1309 * Constructor
1310 * @param string $errorcode The name of the string from error.php to print
1311 * @param string $module name of module
1312 * @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.
1313 * @param object $a Extra words and phrases that might be required in the error string
1314 * @param string $debuginfo optional debugging information
1316 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1317 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1322 * This class is used to manage a bulk operations for enrolment plugins.
1324 * @copyright 2011 Sam Hemelryk
1325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1327 abstract class enrol_bulk_enrolment_operation {
1330 * The course enrolment manager
1331 * @var course_enrolment_manager
1333 protected $manager;
1336 * The enrolment plugin to which this operation belongs
1337 * @var enrol_plugin
1339 protected $plugin;
1342 * Contructor
1343 * @param course_enrolment_manager $manager
1344 * @param stdClass $plugin
1346 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1347 $this->manager = $manager;
1348 $this->plugin = $plugin;
1352 * Returns a moodleform used for this operation, or false if no form is required and the action
1353 * should be immediatly processed.
1355 * @param moodle_url|string $defaultaction
1356 * @param mixed $defaultcustomdata
1357 * @return enrol_bulk_enrolment_change_form|moodleform|false
1359 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1360 return false;
1364 * Returns the title to use for this bulk operation
1366 * @return string
1368 abstract public function get_title();
1371 * Returns the identifier for this bulk operation.
1372 * This should be the same identifier used by the plugins function when returning
1373 * all of its bulk operations.
1375 * @return string
1377 abstract public function get_identifier();
1380 * Processes the bulk operation on the given users
1382 * @param course_enrolment_manager $manager
1383 * @param array $users
1384 * @param stdClass $properties
1386 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);