MDL-38659 environment: fix incorrect feedback messages
[moodle.git] / enrol / locallib.php
blob095fe9545a532b76d207b1dad9d3c698292f6594
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 $_roles = null;
101 private $_assignableroles = null;
102 private $_assignablerolesothers = null;
103 private $_groups = null;
104 /**#@-*/
107 * Constructs the course enrolment manager
109 * @param moodle_page $moodlepage
110 * @param stdClass $course
111 * @param string $instancefilter
113 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null) {
114 $this->moodlepage = $moodlepage;
115 $this->context = get_context_instance(CONTEXT_COURSE, $course->id);
116 $this->course = $course;
117 $this->instancefilter = $instancefilter;
121 * Returns the current moodle page
122 * @return moodle_page
124 public function get_moodlepage() {
125 return $this->moodlepage;
129 * Returns the total number of enrolled users in the course.
131 * If a filter was specificed this will be the total number of users enrolled
132 * in this course by means of that instance.
134 * @global moodle_database $DB
135 * @return int
137 public function get_total_users() {
138 global $DB;
139 if ($this->totalusers === null) {
140 list($instancessql, $params, $filter) = $this->get_instance_sql();
141 $sqltotal = "SELECT COUNT(DISTINCT u.id)
142 FROM {user} u
143 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
144 JOIN {enrol} e ON (e.id = ue.enrolid)";
145 $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
147 return $this->totalusers;
151 * Returns the total number of enrolled users in the course.
153 * If a filter was specificed this will be the total number of users enrolled
154 * in this course by means of that instance.
156 * @global moodle_database $DB
157 * @return int
159 public function get_total_other_users() {
160 global $DB;
161 if ($this->totalotherusers === null) {
162 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
163 $params['courseid'] = $this->course->id;
164 $sql = "SELECT COUNT(DISTINCT u.id)
165 FROM {role_assignments} ra
166 JOIN {user} u ON u.id = ra.userid
167 JOIN {context} ctx ON ra.contextid = ctx.id
168 LEFT JOIN (
169 SELECT ue.id, ue.userid
170 FROM {user_enrolments} ue
171 LEFT JOIN {enrol} e ON e.id=ue.enrolid
172 WHERE e.courseid = :courseid
173 ) ue ON ue.userid=u.id
174 WHERE ctx.id $ctxcondition AND
175 ue.id IS NULL";
176 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
178 return $this->totalotherusers;
182 * Gets all of the users enrolled in this course.
184 * If a filter was specified this will be the users who were enrolled
185 * in this course by means of that instance.
187 * @global moodle_database $DB
188 * @param string $sort
189 * @param string $direction ASC or DESC
190 * @param int $page First page should be 0
191 * @param int $perpage Defaults to 25
192 * @return array
194 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
195 global $DB;
196 if ($direction !== 'ASC') {
197 $direction = 'DESC';
199 $key = md5("$sort-$direction-$page-$perpage");
200 if (!array_key_exists($key, $this->users)) {
201 list($instancessql, $params, $filter) = $this->get_instance_sql();
202 $extrafields = get_extra_user_fields($this->get_context());
203 $extrafields[] = 'lastaccess';
204 $ufields = user_picture::fields('u', $extrafields);
205 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
206 FROM {user} u
207 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
208 JOIN {enrol} e ON (e.id = ue.enrolid)
209 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
210 if ($sort === 'firstname') {
211 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
212 } else if ($sort === 'lastname') {
213 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
214 } else if ($sort === 'email') {
215 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
216 } else if ($sort === 'lastseen') {
217 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
219 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
221 return $this->users[$key];
225 * Gets and array of other users.
227 * Other users are users who have been assigned roles or inherited roles
228 * within this course but who have not been enrolled in the course
230 * @global moodle_database $DB
231 * @param string $sort
232 * @param string $direction
233 * @param int $page
234 * @param int $perpage
235 * @return array
237 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
238 global $DB;
239 if ($direction !== 'ASC') {
240 $direction = 'DESC';
242 $key = md5("$sort-$direction-$page-$perpage");
243 if (!array_key_exists($key, $this->otherusers)) {
244 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
245 $params['courseid'] = $this->course->id;
246 $params['cid'] = $this->course->id;
247 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
248 FROM {role_assignments} ra
249 JOIN {user} u ON u.id = ra.userid
250 JOIN {context} ctx ON ra.contextid = ctx.id
251 LEFT JOIN (
252 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
253 FROM {user_enrolments} ue
254 LEFT JOIN {enrol} e ON e.id=ue.enrolid
255 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
256 WHERE e.courseid = :courseid
257 ) ue ON ue.userid=u.id
258 WHERE ctx.id $ctxcondition AND
259 ue.id IS NULL
260 ORDER BY u.$sort $direction, ctx.depth DESC";
261 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
263 return $this->otherusers[$key];
267 * Gets an array of the users that can be enrolled in this course.
269 * @global moodle_database $DB
270 * @param int $enrolid
271 * @param string $search
272 * @param bool $searchanywhere
273 * @param int $page Defaults to 0
274 * @param int $perpage Defaults to 25
275 * @param int $addedenrollment Defaults to 0
276 * @return array Array(totalusers => int, users => array)
278 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
279 global $DB, $CFG;
281 // Add some additional sensible conditions
282 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
283 $params = array('guestid' => $CFG->siteguest);
284 if (!empty($search)) {
285 $conditions = get_extra_user_fields($this->get_context());
286 $conditions[] = $DB->sql_concat('u.firstname', "' '", 'u.lastname');
287 if ($searchanywhere) {
288 $searchparam = '%' . $search . '%';
289 } else {
290 $searchparam = $search . '%';
292 $i = 0;
293 foreach ($conditions as $key=>$condition) {
294 $conditions[$key] = $DB->sql_like($condition,":con{$i}00", false);
295 $params["con{$i}00"] = $searchparam;
296 $i++;
298 $tests[] = '(' . implode(' OR ', $conditions) . ')';
300 $wherecondition = implode(' AND ', $tests);
302 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
303 $extrafields[] = 'username';
304 $extrafields[] = 'lastaccess';
305 $ufields = user_picture::fields('u', $extrafields);
307 $fields = 'SELECT '.$ufields;
308 $countfields = 'SELECT COUNT(1)';
309 $sql = " FROM {user} u
310 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
311 WHERE $wherecondition
312 AND ue.id IS NULL";
313 $order = ' ORDER BY u.lastname ASC, u.firstname ASC';
314 $params['enrolid'] = $enrolid;
315 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
316 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, ($page*$perpage) - $addedenrollment, $perpage);
317 return array('totalusers'=>$totalusers, 'users'=>$availableusers);
321 * Searches other users and returns paginated results
323 * @global moodle_database $DB
324 * @param string $search
325 * @param bool $searchanywhere
326 * @param int $page Starting at 0
327 * @param int $perpage
328 * @return array
330 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
331 global $DB, $CFG;
333 // Add some additional sensible conditions
334 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
335 $params = array('guestid'=>$CFG->siteguest);
336 if (!empty($search)) {
337 $conditions = array('u.firstname','u.lastname');
338 if ($searchanywhere) {
339 $searchparam = '%' . $search . '%';
340 } else {
341 $searchparam = $search . '%';
343 $i = 0;
344 foreach ($conditions as $key=>$condition) {
345 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
346 $params["con{$i}00"] = $searchparam;
347 $i++;
349 $tests[] = '(' . implode(' OR ', $conditions) . ')';
351 $wherecondition = implode(' AND ', $tests);
353 $fields = 'SELECT '.user_picture::fields('u', array('username','lastaccess'));
354 $countfields = 'SELECT COUNT(u.id)';
355 $sql = " FROM {user} u
356 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
357 WHERE $wherecondition
358 AND ra.id IS NULL";
359 $order = ' ORDER BY lastname ASC, firstname ASC';
361 $params['contextid'] = $this->context->id;
362 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
363 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
364 return array('totalusers'=>$totalusers, 'users'=>$availableusers);
368 * Gets an array containing some SQL to user for when selecting, params for
369 * that SQL, and the filter that was used in constructing the sql.
371 * @global moodle_database $DB
372 * @return string
374 protected function get_instance_sql() {
375 global $DB;
376 if ($this->_instancessql === null) {
377 $instances = $this->get_enrolment_instances();
378 $filter = $this->get_enrolment_filter();
379 if ($filter && array_key_exists($filter, $instances)) {
380 $sql = " = :ifilter";
381 $params = array('ifilter'=>$filter);
382 } else {
383 $filter = 0;
384 if ($instances) {
385 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
386 } else {
387 // no enabled instances, oops, we should probably say something
388 $sql = "= :never";
389 $params = array('never'=>-1);
392 $this->instancefilter = $filter;
393 $this->_instancessql = array($sql, $params, $filter);
395 return $this->_instancessql;
399 * Returns all of the enrolment instances for this course.
401 * @return array
403 public function get_enrolment_instances() {
404 if ($this->_instances === null) {
405 $this->_instances = enrol_get_instances($this->course->id, true);
407 return $this->_instances;
411 * Returns the names for all of the enrolment instances for this course.
413 * @return array
415 public function get_enrolment_instance_names() {
416 if ($this->_inames === null) {
417 $instances = $this->get_enrolment_instances();
418 $plugins = $this->get_enrolment_plugins();
419 foreach ($instances as $key=>$instance) {
420 if (!isset($plugins[$instance->enrol])) {
421 // weird, some broken stuff in plugin
422 unset($instances[$key]);
423 continue;
425 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
428 return $this->_inames;
432 * Gets all of the enrolment plugins that are active for this course.
434 * @return array
436 public function get_enrolment_plugins() {
437 if ($this->_plugins === null) {
438 $this->_plugins = enrol_get_plugins(true);
440 return $this->_plugins;
444 * Gets all of the roles this course can contain.
446 * @return array
448 public function get_all_roles() {
449 if ($this->_roles === null) {
450 $this->_roles = role_fix_names(get_all_roles(), $this->context);
452 return $this->_roles;
456 * Gets all of the assignable roles for this course.
458 * @return array
460 public function get_assignable_roles($otherusers = false) {
461 if ($this->_assignableroles === null) {
462 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
465 if ($otherusers) {
466 if (!is_array($this->_assignablerolesothers)) {
467 $this->_assignablerolesothers = array();
468 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
469 foreach ($this->_assignableroles as $roleid=>$role) {
470 if (isset($courseviewroles[$roleid])) {
471 $this->_assignablerolesothers[$roleid] = $role;
475 return $this->_assignablerolesothers;
476 } else {
477 return $this->_assignableroles;
482 * Gets all of the groups for this course.
484 * @return array
486 public function get_all_groups() {
487 if ($this->_groups === null) {
488 $this->_groups = groups_get_all_groups($this->course->id);
489 foreach ($this->_groups as $gid=>$group) {
490 $this->_groups[$gid]->name = format_string($group->name);
493 return $this->_groups;
497 * Unenrols a user from the course given the users ue entry
499 * @global moodle_database $DB
500 * @param stdClass $ue
501 * @return bool
503 public function unenrol_user($ue) {
504 global $DB;
505 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
506 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
507 $plugin->unenrol_user($instance, $ue->userid);
508 return true;
510 return false;
514 * Given a user enrolment record this method returns the plugin and enrolment
515 * instance that relate to it.
517 * @param stdClass|int $userenrolment
518 * @return array array($instance, $plugin)
520 public function get_user_enrolment_components($userenrolment) {
521 global $DB;
522 if (is_numeric($userenrolment)) {
523 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
525 $instances = $this->get_enrolment_instances();
526 $plugins = $this->get_enrolment_plugins();
527 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
528 return array(false, false);
530 $instance = $instances[$userenrolment->enrolid];
531 $plugin = $plugins[$instance->enrol];
532 return array($instance, $plugin);
536 * Removes an assigned role from a user.
538 * @global moodle_database $DB
539 * @param int $userid
540 * @param int $roleid
541 * @return bool
543 public function unassign_role_from_user($userid, $roleid) {
544 global $DB;
545 require_capability('moodle/role:assign', $this->context);
546 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
547 try {
548 role_unassign($roleid, $user->id, $this->context->id, '', NULL);
549 } catch (Exception $e) {
550 if (defined('AJAX_SCRIPT')) {
551 throw $e;
553 return false;
555 return true;
559 * Assigns a role to a user.
561 * @param int $roleid
562 * @param int $userid
563 * @return int|false
565 public function assign_role_to_user($roleid, $userid) {
566 require_capability('moodle/role:assign', $this->context);
567 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
568 if (defined('AJAX_SCRIPT')) {
569 throw new moodle_exception('invalidrole');
571 return false;
573 return role_assign($roleid, $userid, $this->context->id, '', NULL);
577 * Adds a user to a group
579 * @param stdClass $user
580 * @param int $groupid
581 * @return bool
583 public function add_user_to_group($user, $groupid) {
584 require_capability('moodle/course:managegroups', $this->context);
585 $group = $this->get_group($groupid);
586 if (!$group) {
587 return false;
589 return groups_add_member($group->id, $user->id);
593 * Removes a user from a group
595 * @global moodle_database $DB
596 * @param StdClass $user
597 * @param int $groupid
598 * @return bool
600 public function remove_user_from_group($user, $groupid) {
601 global $DB;
602 require_capability('moodle/course:managegroups', $this->context);
603 $group = $this->get_group($groupid);
604 if (!$group) {
605 return false;
607 return groups_remove_member($group, $user);
611 * Gets the requested group
613 * @param int $groupid
614 * @return stdClass|int
616 public function get_group($groupid) {
617 $groups = $this->get_all_groups();
618 if (!array_key_exists($groupid, $groups)) {
619 return false;
621 return $groups[$groupid];
625 * Edits an enrolment
627 * @param stdClass $userenrolment
628 * @param stdClass $data
629 * @return bool
631 public function edit_enrolment($userenrolment, $data) {
632 //Only allow editing if the user has the appropriate capability
633 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
634 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
635 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
636 if (!isset($data->status)) {
637 $data->status = $userenrolment->status;
639 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
640 return true;
642 return false;
646 * Returns the current enrolment filter that is being applied by this class
647 * @return string
649 public function get_enrolment_filter() {
650 return $this->instancefilter;
654 * Gets the roles assigned to this user that are applicable for this course.
656 * @param int $userid
657 * @return array
659 public function get_user_roles($userid) {
660 $roles = array();
661 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
662 foreach ($ras as $ra) {
663 if ($ra->contextid != $this->context->id) {
664 if (!array_key_exists($ra->roleid, $roles)) {
665 $roles[$ra->roleid] = null;
667 // higher ras, course always takes precedence
668 continue;
670 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
671 continue;
673 $roles[$ra->roleid] = ($ra->itemid == 0 and $ra->component === '');
675 return $roles;
679 * Gets the enrolments this user has in the course
681 * @global moodle_database $DB
682 * @param int $userid
683 * @return array
685 public function get_user_enrolments($userid) {
686 global $DB;
687 list($instancessql, $params, $filter) = $this->get_instance_sql();
688 $params['userid'] = $userid;
689 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
690 $instances = $this->get_enrolment_instances();
691 $plugins = $this->get_enrolment_plugins();
692 $inames = $this->get_enrolment_instance_names();
693 foreach ($userenrolments as &$ue) {
694 $ue->enrolmentinstance = $instances[$ue->enrolid];
695 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
696 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
698 return $userenrolments;
702 * Gets the groups this user belongs to
704 * @param int $userid
705 * @return array
707 public function get_user_groups($userid) {
708 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
712 * Retursn an array of params that would go into the URL to return to this
713 * exact page.
715 * @return array
717 public function get_url_params() {
718 $args = array(
719 'id' => $this->course->id
721 if (!empty($this->instancefilter)) {
722 $args['ifilter'] = $this->instancefilter;
724 return $args;
728 * Returns the course this object is managing enrolments for
730 * @return stdClass
732 public function get_course() {
733 return $this->course;
737 * Returns the course context
739 * @return stdClass
741 public function get_context() {
742 return $this->context;
746 * Gets an array of other users in this course ready for display.
748 * Other users are users who have been assigned or inherited roles within this
749 * course but have not been enrolled.
751 * @param core_enrol_renderer $renderer
752 * @param moodle_url $pageurl
753 * @param string $sort
754 * @param string $direction ASC | DESC
755 * @param int $page Starting from 0
756 * @param int $perpage
757 * @return array
759 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
761 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
762 $roles = $this->get_all_roles();
764 $context = $this->get_context();
765 $now = time();
766 $extrafields = get_extra_user_fields($context);
768 $users = array();
769 foreach ($userroles as $userrole) {
770 $contextid = $userrole->contextid;
771 unset($userrole->contextid); // This would collide with user avatar.
772 if (!array_key_exists($userrole->id, $users)) {
773 $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
775 $a = new stdClass;
776 $a->role = $roles[$userrole->roleid]->localname;
777 $changeable = ($userrole->component == '');
778 if ($contextid == $this->context->id) {
779 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
780 } else {
781 $changeable = false;
782 switch ($userrole->contextlevel) {
783 case CONTEXT_COURSE :
784 // Meta course
785 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
786 break;
787 case CONTEXT_COURSECAT :
788 $roletext = get_string('rolefromcategory', 'enrol', $a);
789 break;
790 case CONTEXT_SYSTEM:
791 default:
792 $roletext = get_string('rolefromsystem', 'enrol', $a);
793 break;
796 if (!isset($users[$userrole->id]['roles'])) {
797 $users[$userrole->id]['roles'] = array();
799 $users[$userrole->id]['roles'][$userrole->roleid] = array(
800 'text' => $roletext,
801 'unchangeable' => !$changeable
804 return $users;
808 * Gets an array of users for display, this includes minimal user information
809 * as well as minimal information on the users roles, groups, and enrolments.
811 * @param core_enrol_renderer $renderer
812 * @param moodle_url $pageurl
813 * @param int $sort
814 * @param string $direction ASC or DESC
815 * @param int $page
816 * @param int $perpage
817 * @return array
819 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
820 $pageurl = $manager->get_moodlepage()->url;
821 $users = $this->get_users($sort, $direction, $page, $perpage);
823 $now = time();
824 $straddgroup = get_string('addgroup', 'group');
825 $strunenrol = get_string('unenrol', 'enrol');
826 $stredit = get_string('edit');
828 $allroles = $this->get_all_roles();
829 $assignable = $this->get_assignable_roles();
830 $allgroups = $this->get_all_groups();
831 $context = $this->get_context();
832 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
834 $url = new moodle_url($pageurl, $this->get_url_params());
835 $extrafields = get_extra_user_fields($context);
837 $userdetails = array();
838 foreach ($users as $user) {
839 $details = $this->prepare_user_for_display($user, $extrafields, $now);
841 // Roles
842 $details['roles'] = array();
843 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
844 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>(!$rassignable || !isset($assignable[$rid])));
847 // Users
848 $usergroups = $this->get_user_groups($user->id);
849 $details['groups'] = array();
850 foreach($usergroups as $gid=>$unused) {
851 $details['groups'][$gid] = $allgroups[$gid]->name;
854 // Enrolments
855 $details['enrolments'] = array();
856 foreach ($this->get_user_enrolments($user->id) as $ue) {
857 if ($ue->timestart and $ue->timeend) {
858 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
859 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
860 } else if ($ue->timestart) {
861 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
862 $periodoutside = ($ue->timestart && $now < $ue->timestart);
863 } else if ($ue->timeend) {
864 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
865 $periodoutside = ($ue->timeend && $now > $ue->timeend);
866 } else {
867 $period = '';
868 $periodoutside = false;
870 $details['enrolments'][$ue->id] = array(
871 'text' => $ue->enrolmentinstancename,
872 'period' => $period,
873 'dimmed' => ($periodoutside || $ue->status != ENROL_USER_ACTIVE),
874 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
877 $userdetails[$user->id] = $details;
879 return $userdetails;
883 * Prepare a user record for display
885 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
886 * prepare user fields for display
888 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
890 * @param object $user The user record
891 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
892 * additional fields may be displayed
893 * @param int $now The time used for lastaccess calculation
894 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
895 * additional fields from $extrafields
897 private function prepare_user_for_display($user, $extrafields, $now) {
898 $details = array(
899 'userid' => $user->id,
900 'courseid' => $this->get_course()->id,
901 'picture' => new user_picture($user),
902 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
903 'lastseen' => get_string('never'),
905 foreach ($extrafields as $field) {
906 $details[$field] = $user->{$field};
909 if ($user->lastaccess) {
910 $details['lastseen'] = format_time($now - $user->lastaccess);
912 return $details;
915 public function get_manual_enrol_buttons() {
916 $plugins = $this->get_enrolment_plugins();
917 $buttons = array();
918 foreach ($plugins as $plugin) {
919 $newbutton = $plugin->get_manual_enrol_button($this);
920 if (is_array($newbutton)) {
921 $buttons += $newbutton;
922 } else if ($newbutton instanceof enrol_user_button) {
923 $buttons[] = $newbutton;
926 return $buttons;
929 public function has_instance($enrolpluginname) {
930 // Make sure manual enrolments instance exists
931 foreach ($this->get_enrolment_instances() as $instance) {
932 if ($instance->enrol == $enrolpluginname) {
933 return true;
936 return false;
940 * Returns the enrolment plugin that the course manager was being filtered to.
942 * If no filter was being applied then this function returns false.
944 * @return enrol_plugin
946 public function get_filtered_enrolment_plugin() {
947 $instances = $this->get_enrolment_instances();
948 $plugins = $this->get_enrolment_plugins();
950 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
951 return false;
954 $instance = $instances[$this->instancefilter];
955 return $plugins[$instance->enrol];
959 * Returns and array of users + enrolment details.
961 * Given an array of user id's this function returns and array of user enrolments for those users
962 * as well as enough user information to display the users name and picture for each enrolment.
964 * @global moodle_database $DB
965 * @param array $userids
966 * @return array
968 public function get_users_enrolments(array $userids) {
969 global $DB;
971 $instances = $this->get_enrolment_instances();
972 $plugins = $this->get_enrolment_plugins();
974 if (!empty($this->instancefilter)) {
975 $instancesql = ' = :instanceid';
976 $instanceparams = array('instanceid' => $this->instancefilter);
977 } else {
978 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
981 $userfields = user_picture::fields('u');
982 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
984 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
985 FROM {user_enrolments} ue
986 LEFT JOIN {user} u ON u.id = ue.userid
987 WHERE ue.enrolid $instancesql AND
988 u.id $idsql
989 ORDER BY u.firstname ASC, u.lastname ASC";
991 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams);
992 $users = array();
993 foreach ($rs as $ue) {
994 $user = user_picture::unalias($ue);
995 $ue->id = $ue->ueid;
996 unset($ue->ueid);
997 if (!array_key_exists($user->id, $users)) {
998 $user->enrolments = array();
999 $users[$user->id] = $user;
1001 $ue->enrolmentinstance = $instances[$ue->enrolid];
1002 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1003 $users[$user->id]->enrolments[$ue->id] = $ue;
1005 $rs->close();
1006 return $users;
1011 * A button that is used to enrol users in a course
1013 * @copyright 2010 Sam Hemelryk
1014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1016 class enrol_user_button extends single_button {
1019 * An array containing JS YUI modules required by this button
1020 * @var array
1022 protected $jsyuimodules = array();
1025 * An array containing JS initialisation calls required by this button
1026 * @var array
1028 protected $jsinitcalls = array();
1031 * An array strings required by JS for this button
1032 * @var array
1034 protected $jsstrings = array();
1037 * Initialises the new enrol_user_button
1039 * @staticvar int $count The number of enrol user buttons already created
1040 * @param moodle_url $url
1041 * @param string $label The text to display in the button
1042 * @param string $method Either post or get
1044 public function __construct(moodle_url $url, $label, $method = 'post') {
1045 static $count = 0;
1046 $count ++;
1047 parent::__construct($url, $label, $method);
1048 $this->class = 'singlebutton enrolusersbutton';
1049 $this->formid = 'enrolusersbutton-'.$count;
1053 * Adds a YUI module call that will be added to the page when the button is used.
1055 * @param string|array $modules One or more modules to require
1056 * @param string $function The JS function to call
1057 * @param array $arguments An array of arguments to pass to the function
1058 * @param string $galleryversion The YUI gallery version of any modules required
1059 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1061 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1062 $js = new stdClass;
1063 $js->modules = (array)$modules;
1064 $js->function = $function;
1065 $js->arguments = $arguments;
1066 $js->galleryversion = $galleryversion;
1067 $js->ondomready = $ondomready;
1068 $this->jsyuimodules[] = $js;
1072 * Adds a JS initialisation call to the page when the button is used.
1074 * @param string $function The function to call
1075 * @param array $extraarguments An array of arguments to pass to the function
1076 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1077 * @param array $module A module definition
1079 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1080 $js = new stdClass;
1081 $js->function = $function;
1082 $js->extraarguments = $extraarguments;
1083 $js->ondomready = $ondomready;
1084 $js->module = $module;
1085 $this->jsinitcalls[] = $js;
1089 * Requires strings for JS that will be loaded when the button is used.
1091 * @param type $identifiers
1092 * @param string $component
1093 * @param mixed $a
1095 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1096 $string = new stdClass;
1097 $string->identifiers = (array)$identifiers;
1098 $string->component = $component;
1099 $string->a = $a;
1100 $this->jsstrings[] = $string;
1104 * Initialises the JS that is required by this button
1106 * @param moodle_page $page
1108 public function initialise_js(moodle_page $page) {
1109 foreach ($this->jsyuimodules as $js) {
1110 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1112 foreach ($this->jsinitcalls as $js) {
1113 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1115 foreach ($this->jsstrings as $string) {
1116 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1122 * User enrolment action
1124 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1125 * a user enrolment.
1127 * @copyright 2011 Sam Hemelryk
1128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1130 class user_enrolment_action implements renderable {
1133 * The icon to display for the action
1134 * @var pix_icon
1136 protected $icon;
1139 * The title for the action
1140 * @var string
1142 protected $title;
1145 * The URL to the action
1146 * @var moodle_url
1148 protected $url;
1151 * An array of HTML attributes
1152 * @var array
1154 protected $attributes = array();
1157 * Constructor
1158 * @param pix_icon $icon
1159 * @param string $title
1160 * @param moodle_url $url
1161 * @param array $attributes
1163 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1164 $this->icon = $icon;
1165 $this->title = $title;
1166 $this->url = new moodle_url($url);
1167 if (!empty($attributes)) {
1168 $this->attributes = $attributes;
1170 $this->attributes['title'] = $title;
1174 * Returns the icon for this action
1175 * @return pix_icon
1177 public function get_icon() {
1178 return $this->icon;
1182 * Returns the title for this action
1183 * @return string
1185 public function get_title() {
1186 return $this->title;
1190 * Returns the URL for this action
1191 * @return moodle_url
1193 public function get_url() {
1194 return $this->url;
1198 * Returns the attributes to use for this action
1199 * @return array
1201 public function get_attributes() {
1202 return $this->attributes;
1206 class enrol_ajax_exception extends moodle_exception {
1208 * Constructor
1209 * @param string $errorcode The name of the string from error.php to print
1210 * @param string $module name of module
1211 * @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.
1212 * @param object $a Extra words and phrases that might be required in the error string
1213 * @param string $debuginfo optional debugging information
1215 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1216 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1221 * This class is used to manage a bulk operations for enrolment plugins.
1223 * @copyright 2011 Sam Hemelryk
1224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1226 abstract class enrol_bulk_enrolment_operation {
1229 * The course enrolment manager
1230 * @var course_enrolment_manager
1232 protected $manager;
1235 * The enrolment plugin to which this operation belongs
1236 * @var enrol_plugin
1238 protected $plugin;
1241 * Contructor
1242 * @param course_enrolment_manager $manager
1243 * @param stdClass $plugin
1245 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1246 $this->manager = $manager;
1247 $this->plugin = $plugin;
1251 * Returns a moodleform used for this operation, or false if no form is required and the action
1252 * should be immediatly processed.
1254 * @param moodle_url|string $defaultaction
1255 * @param mixed $defaultcustomdata
1256 * @return enrol_bulk_enrolment_change_form|moodleform|false
1258 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1259 return false;
1263 * Returns the title to use for this bulk operation
1265 * @return string
1267 abstract public function get_title();
1270 * Returns the identifier for this bulk operation.
1271 * This should be the same identifier used by the plugins function when returning
1272 * all of its bulk operations.
1274 * @return string
1276 abstract public function get_identifier();
1279 * Processes the bulk operation on the given users
1281 * @param course_enrolment_manager $manager
1282 * @param array $users
1283 * @param stdClass $properties
1285 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);