weekly release 2.3dev
[moodle.git] / enrol / locallib.php
CommitLineData
a70eb30f
SH
1<?php
2
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.
14//
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/>.
17
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.
21 *
5379726a
PS
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
a70eb30f
SH
26 */
27
75ee207b
SH
28defined('MOODLE_INTERNAL') || die();
29
a70eb30f
SH
30/**
31 * This class provides a targeted tied together means of interfacing the enrolment
32 * tasks together with a course.
33 *
34 * It is provided as a convenience more than anything else.
35 *
36 * @copyright 2010 Sam Hemelryk
37 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 */
39class course_enrolment_manager {
40
41 /**
42 * The course context
43 * @var stdClass
44 */
45 protected $context;
46 /**
47 * The course we are managing enrolments for
48 * @var stdClass
49 */
50 protected $course = null;
51 /**
52 * Limits the focus of the manager to one enrolment plugin instance
53 * @var string
54 */
55 protected $instancefilter = null;
56
57 /**
58 * The total number of users enrolled in the course
59 * Populated by course_enrolment_manager::get_total_users
60 * @var int
61 */
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
67 */
68 protected $users = array();
69
6db3eee0
SH
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
74 */
75 protected $otherusers = array();
76
77 /**
78 * The total number of users who hold a role within the course but who
79 * arn't enrolled.
80 * @var int
81 */
82 protected $totalotherusers = null;
83
076995bf
SH
84 /**
85 * The current moodle_page object
86 * @var moodle_page
87 */
88 protected $moodlepage = null;
89
a70eb30f
SH
90 /**#@+
91 * These variables are used to cache the information this class uses
df4a889e 92 * please never use these directly instead use their get_ counterparts.
a70eb30f
SH
93 * @access private
94 * @var array
95 */
96 private $_instancessql = null;
97 private $_instances = null;
98 private $_inames = null;
99 private $_plugins = null;
100 private $_roles = null;
101 private $_assignableroles = null;
9f15347e 102 private $_assignablerolesothers = null;
a70eb30f
SH
103 private $_groups = null;
104 /**#@-*/
105
106 /**
107 * Constructs the course enrolment manager
108 *
076995bf 109 * @param moodle_page $moodlepage
a70eb30f
SH
110 * @param stdClass $course
111 * @param string $instancefilter
112 */
076995bf
SH
113 public function __construct(moodle_page $moodlepage, $course, $instancefilter = null) {
114 $this->moodlepage = $moodlepage;
a70eb30f
SH
115 $this->context = get_context_instance(CONTEXT_COURSE, $course->id);
116 $this->course = $course;
117 $this->instancefilter = $instancefilter;
118 }
119
076995bf
SH
120 /**
121 * Returns the current moodle page
5dbfbacc 122 * @return moodle_page
076995bf
SH
123 */
124 public function get_moodlepage() {
125 return $this->moodlepage;
126 }
127
a70eb30f
SH
128 /**
129 * Returns the total number of enrolled users in the course.
130 *
131 * If a filter was specificed this will be the total number of users enrolled
132 * in this course by means of that instance.
133 *
134 * @global moodle_database $DB
135 * @return int
136 */
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);
146 }
147 return $this->totalusers;
148 }
149
6db3eee0
SH
150 /**
151 * Returns the total number of enrolled users in the course.
152 *
153 * If a filter was specificed this will be the total number of users enrolled
154 * in this course by means of that instance.
155 *
156 * @global moodle_database $DB
157 * @return int
158 */
159 public function get_total_other_users() {
160 global $DB;
161 if ($this->totalotherusers === null) {
cf717dc2 162 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
6db3eee0
SH
163 $params['courseid'] = $this->course->id;
164 $sql = "SELECT COUNT(DISTINCT u.id)
884faffd
SH
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
6db3eee0 171 LEFT JOIN {enrol} e ON e.id=ue.enrolid
884faffd
SH
172 WHERE e.courseid = :courseid
173 ) ue ON ue.userid=u.id
174 WHERE ctx.id $ctxcondition AND
175 ue.id IS NULL";
6db3eee0
SH
176 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
177 }
178 return $this->totalotherusers;
179 }
180
a70eb30f
SH
181 /**
182 * Gets all of the users enrolled in this course.
183 *
df4a889e 184 * If a filter was specified this will be the users who were enrolled
a70eb30f
SH
185 * in this course by means of that instance.
186 *
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
193 */
194 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
195 global $DB;
196 if ($direction !== 'ASC') {
197 $direction = 'DESC';
198 }
199 $key = md5("$sort-$direction-$page-$perpage");
200 if (!array_key_exists($key, $this->users)) {
201 list($instancessql, $params, $filter) = $this->get_instance_sql();
b849c212 202 $extrafields = get_extra_user_fields($this->get_context());
203 $extrafields[] = 'lastaccess';
204 $ufields = user_picture::fields('u', $extrafields);
df4a889e 205 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
a70eb30f
SH
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";
218 }
219 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
220 }
221 return $this->users[$key];
222 }
223
6db3eee0
SH
224 /**
225 * Gets and array of other users.
226 *
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
229 *
230 * @global moodle_database $DB
231 * @param string $sort
232 * @param string $direction
233 * @param int $page
234 * @param int $perpage
235 * @return array
236 */
237 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
238 global $DB;
239 if ($direction !== 'ASC') {
240 $direction = 'DESC';
241 }
242 $key = md5("$sort-$direction-$page-$perpage");
243 if (!array_key_exists($key, $this->otherusers)) {
cf717dc2 244 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
6db3eee0
SH
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
884faffd
SH
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)
6db3eee0 256 WHERE e.courseid = :courseid
884faffd
SH
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";
6db3eee0
SH
261 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
262 }
263 return $this->otherusers[$key];
264 }
265
a70eb30f
SH
266 /**
267 * Gets an array of the users that can be enrolled in this course.
268 *
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 * @return array Array(totalusers => int, users => array)
276 */
277 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25) {
b3df1764 278 global $DB, $CFG;
a70eb30f
SH
279
280 // Add some additional sensible conditions
b3df1764
PS
281 $tests = array("id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
282 $params = array('guestid' => $CFG->siteguest);
a70eb30f 283 if (!empty($search)) {
b849c212 284 $conditions = get_extra_user_fields($this->get_context());
285 $conditions[] = $DB->sql_concat('u.firstname', "' '", 'u.lastname');
a70eb30f
SH
286 if ($searchanywhere) {
287 $searchparam = '%' . $search . '%';
288 } else {
289 $searchparam = $search . '%';
290 }
291 $i = 0;
f7614bb0
PS
292 foreach ($conditions as $key=>$condition) {
293 $conditions[$key] = $DB->sql_like($condition,":con{$i}00", false);
a70eb30f
SH
294 $params["con{$i}00"] = $searchparam;
295 $i++;
296 }
297 $tests[] = '(' . implode(' OR ', $conditions) . ')';
298 }
299 $wherecondition = implode(' AND ', $tests);
300
b849c212 301 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
302 $extrafields[] = 'username';
303 $extrafields[] = 'lastaccess';
304 $ufields = user_picture::fields('u', $extrafields);
a70eb30f 305
93b4ecb2 306 $fields = 'SELECT '.$ufields;
a70eb30f
SH
307 $countfields = 'SELECT COUNT(1)';
308 $sql = " FROM {user} u
309 WHERE $wherecondition
310 AND u.id NOT IN (SELECT ue.userid
311 FROM {user_enrolments} ue
312 JOIN {enrol} e ON (e.id = ue.enrolid AND e.id = :enrolid))";
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, $perpage);
317 return array('totalusers'=>$totalusers, 'users'=>$availableusers);
318 }
319
6db3eee0
SH
320 /**
321 * Searches other users and returns paginated results
322 *
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
329 */
330 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
b3df1764 331 global $DB, $CFG;
6db3eee0
SH
332
333 // Add some additional sensible conditions
b3df1764
PS
334 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
335 $params = array('guestid'=>$CFG->siteguest);
6db3eee0
SH
336 if (!empty($search)) {
337 $conditions = array('u.firstname','u.lastname');
6db3eee0
SH
338 if ($searchanywhere) {
339 $searchparam = '%' . $search . '%';
340 } else {
341 $searchparam = $search . '%';
342 }
343 $i = 0;
f7614bb0
PS
344 foreach ($conditions as $key=>$condition) {
345 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
6db3eee0
SH
346 $params["con{$i}00"] = $searchparam;
347 $i++;
348 }
349 $tests[] = '(' . implode(' OR ', $conditions) . ')';
350 }
351 $wherecondition = implode(' AND ', $tests);
5379726a 352
603087b8 353 $fields = 'SELECT '.user_picture::fields('u', array('username','lastaccess'));
6db3eee0
SH
354 $countfields = 'SELECT COUNT(u.id)';
355 $sql = " FROM {user} u
356 WHERE $wherecondition
884faffd 357 AND u.id NOT IN (
6db3eee0
SH
358 SELECT u.id
359 FROM {role_assignments} r, {user} u
884faffd
SH
360 WHERE r.contextid = :contextid AND
361 u.id = r.userid)";
6db3eee0
SH
362 $order = ' ORDER BY lastname ASC, firstname ASC';
363
364 $params['contextid'] = $this->context->id;
365 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
366 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
367 return array('totalusers'=>$totalusers, 'users'=>$availableusers);
368 }
369
a70eb30f
SH
370 /**
371 * Gets an array containing some SQL to user for when selecting, params for
372 * that SQL, and the filter that was used in constructing the sql.
373 *
374 * @global moodle_database $DB
375 * @return string
376 */
377 protected function get_instance_sql() {
378 global $DB;
379 if ($this->_instancessql === null) {
380 $instances = $this->get_enrolment_instances();
381 $filter = $this->get_enrolment_filter();
382 if ($filter && array_key_exists($filter, $instances)) {
383 $sql = " = :ifilter";
384 $params = array('ifilter'=>$filter);
385 } else {
386 $filter = 0;
387 if ($instances) {
388 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
389 } else {
390 // no enabled instances, oops, we should probably say something
391 $sql = "= :never";
392 $params = array('never'=>-1);
393 }
394 }
395 $this->instancefilter = $filter;
396 $this->_instancessql = array($sql, $params, $filter);
397 }
398 return $this->_instancessql;
399 }
400
401 /**
402 * Returns all of the enrolment instances for this course.
403 *
404 * @return array
405 */
406 public function get_enrolment_instances() {
407 if ($this->_instances === null) {
408 $this->_instances = enrol_get_instances($this->course->id, true);
409 }
410 return $this->_instances;
411 }
412
413 /**
414 * Returns the names for all of the enrolment instances for this course.
415 *
416 * @return array
417 */
418 public function get_enrolment_instance_names() {
419 if ($this->_inames === null) {
420 $instances = $this->get_enrolment_instances();
421 $plugins = $this->get_enrolment_plugins();
422 foreach ($instances as $key=>$instance) {
423 if (!isset($plugins[$instance->enrol])) {
424 // weird, some broken stuff in plugin
425 unset($instances[$key]);
426 continue;
427 }
428 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
429 }
430 }
431 return $this->_inames;
432 }
433
434 /**
435 * Gets all of the enrolment plugins that are active for this course.
436 *
437 * @return array
438 */
439 public function get_enrolment_plugins() {
440 if ($this->_plugins === null) {
441 $this->_plugins = enrol_get_plugins(true);
442 }
443 return $this->_plugins;
444 }
445
446 /**
447 * Gets all of the roles this course can contain.
448 *
449 * @return array
450 */
451 public function get_all_roles() {
452 if ($this->_roles === null) {
453 $this->_roles = role_fix_names(get_all_roles(), $this->context);
454 }
455 return $this->_roles;
456 }
457
458 /**
459 * Gets all of the assignable roles for this course.
460 *
461 * @return array
462 */
9f15347e 463 public function get_assignable_roles($otherusers = false) {
a70eb30f
SH
464 if ($this->_assignableroles === null) {
465 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
466 }
9f15347e
SH
467
468 if ($otherusers) {
469 if (!is_array($this->_assignablerolesothers)) {
470 $this->_assignablerolesothers = array();
471 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
472 foreach ($this->_assignableroles as $roleid=>$role) {
473 if (isset($courseviewroles[$roleid])) {
474 $this->_assignablerolesothers[$roleid] = $role;
475 }
476 }
477 }
478 return $this->_assignablerolesothers;
479 } else {
480 return $this->_assignableroles;
481 }
a70eb30f
SH
482 }
483
484 /**
485 * Gets all of the groups for this course.
486 *
487 * @return array
488 */
489 public function get_all_groups() {
490 if ($this->_groups === null) {
491 $this->_groups = groups_get_all_groups($this->course->id);
492 foreach ($this->_groups as $gid=>$group) {
493 $this->_groups[$gid]->name = format_string($group->name);
494 }
495 }
496 return $this->_groups;
497 }
498
499 /**
df4a889e 500 * Unenrols a user from the course given the users ue entry
a70eb30f
SH
501 *
502 * @global moodle_database $DB
503 * @param stdClass $ue
504 * @return bool
505 */
506 public function unenrol_user($ue) {
a942f757 507 global $DB;
a3c71984 508 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
282b5cc7 509 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
a3c71984
SH
510 $plugin->unenrol_user($instance, $ue->userid);
511 return true;
512 }
513 return false;
514 }
a70eb30f 515
a3c71984
SH
516 /**
517 * Given a user enrolment record this method returns the plugin and enrolment
518 * instance that relate to it.
519 *
520 * @param stdClass|int $userenrolment
521 * @return array array($instance, $plugin)
522 */
523 public function get_user_enrolment_components($userenrolment) {
524 global $DB;
a942f757 525 if (is_numeric($userenrolment)) {
a3c71984
SH
526 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
527 }
a70eb30f
SH
528 $instances = $this->get_enrolment_instances();
529 $plugins = $this->get_enrolment_plugins();
a3c71984
SH
530 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
531 return array(false, false);
a70eb30f 532 }
a3c71984 533 $instance = $instances[$userenrolment->enrolid];
a70eb30f 534 $plugin = $plugins[$instance->enrol];
a3c71984 535 return array($instance, $plugin);
a70eb30f
SH
536 }
537
538 /**
539 * Removes an assigned role from a user.
540 *
541 * @global moodle_database $DB
542 * @param int $userid
543 * @param int $roleid
544 * @return bool
545 */
546 public function unassign_role_from_user($userid, $roleid) {
547 global $DB;
a3c71984 548 require_capability('moodle/role:assign', $this->context);
a70eb30f
SH
549 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
550 try {
551 role_unassign($roleid, $user->id, $this->context->id, '', NULL);
552 } catch (Exception $e) {
894843b4 553 if (defined('AJAX_SCRIPT')) {
6db3eee0
SH
554 throw $e;
555 }
a70eb30f
SH
556 return false;
557 }
558 return true;
559 }
560
561 /**
562 * Assigns a role to a user.
563 *
564 * @param int $roleid
565 * @param int $userid
566 * @return int|false
567 */
568 public function assign_role_to_user($roleid, $userid) {
569 require_capability('moodle/role:assign', $this->context);
823a807e 570 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
894843b4 571 if (defined('AJAX_SCRIPT')) {
c05260de 572 throw new moodle_exception('invalidrole');
6db3eee0 573 }
823a807e
SH
574 return false;
575 }
a70eb30f
SH
576 return role_assign($roleid, $userid, $this->context->id, '', NULL);
577 }
578
579 /**
580 * Adds a user to a group
581 *
582 * @param stdClass $user
583 * @param int $groupid
584 * @return bool
585 */
586 public function add_user_to_group($user, $groupid) {
587 require_capability('moodle/course:managegroups', $this->context);
588 $group = $this->get_group($groupid);
589 if (!$group) {
590 return false;
591 }
592 return groups_add_member($group->id, $user->id);
593 }
594
595 /**
596 * Removes a user from a group
597 *
598 * @global moodle_database $DB
599 * @param StdClass $user
600 * @param int $groupid
601 * @return bool
602 */
603 public function remove_user_from_group($user, $groupid) {
604 global $DB;
605 require_capability('moodle/course:managegroups', $this->context);
606 $group = $this->get_group($groupid);
607 if (!$group) {
608 return false;
609 }
610 return groups_remove_member($group, $user);
611 }
612
613 /**
614 * Gets the requested group
615 *
616 * @param int $groupid
617 * @return stdClass|int
618 */
619 public function get_group($groupid) {
620 $groups = $this->get_all_groups();
621 if (!array_key_exists($groupid, $groups)) {
622 return false;
623 }
624 return $groups[$groupid];
625 }
626
627 /**
628 * Edits an enrolment
629 *
630 * @param stdClass $userenrolment
631 * @param stdClass $data
632 * @return bool
633 */
634 public function edit_enrolment($userenrolment, $data) {
13ba9036
AD
635 //Only allow editing if the user has the appropriate capability
636 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
621ee955 637 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
a3c71984
SH
638 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
639 if (!isset($data->status)) {
640 $data->status = $userenrolment->status;
641 }
642 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
643 return true;
a70eb30f 644 }
a3c71984 645 return false;
a70eb30f
SH
646 }
647
648 /**
649 * Returns the current enrolment filter that is being applied by this class
650 * @return string
651 */
652 public function get_enrolment_filter() {
653 return $this->instancefilter;
654 }
655
656 /**
657 * Gets the roles assigned to this user that are applicable for this course.
658 *
659 * @param int $userid
660 * @return array
661 */
662 public function get_user_roles($userid) {
663 $roles = array();
664 $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
665 foreach ($ras as $ra) {
666 if ($ra->contextid != $this->context->id) {
667 if (!array_key_exists($ra->roleid, $roles)) {
668 $roles[$ra->roleid] = null;
669 }
670 // higher ras, course always takes precedence
671 continue;
672 }
673 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
674 continue;
675 }
676 $roles[$ra->roleid] = ($ra->itemid == 0 and $ra->component === '');
677 }
678 return $roles;
679 }
680
681 /**
682 * Gets the enrolments this user has in the course
683 *
684 * @global moodle_database $DB
685 * @param int $userid
686 * @return array
687 */
688 public function get_user_enrolments($userid) {
689 global $DB;
690 list($instancessql, $params, $filter) = $this->get_instance_sql();
691 $params['userid'] = $userid;
692 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
693 $instances = $this->get_enrolment_instances();
694 $plugins = $this->get_enrolment_plugins();
695 $inames = $this->get_enrolment_instance_names();
696 foreach ($userenrolments as &$ue) {
697 $ue->enrolmentinstance = $instances[$ue->enrolid];
698 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
699 $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
700 }
701 return $userenrolments;
702 }
703
704 /**
705 * Gets the groups this user belongs to
706 *
707 * @param int $userid
708 * @return array
709 */
710 public function get_user_groups($userid) {
711 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
712 }
713
714 /**
715 * Retursn an array of params that would go into the URL to return to this
716 * exact page.
717 *
718 * @return array
719 */
720 public function get_url_params() {
721 $args = array(
722 'id' => $this->course->id
723 );
724 if (!empty($this->instancefilter)) {
725 $args['ifilter'] = $this->instancefilter;
726 }
727 return $args;
728 }
729
730 /**
731 * Returns the course this object is managing enrolments for
732 *
733 * @return stdClass
734 */
735 public function get_course() {
736 return $this->course;
737 }
738
739 /**
740 * Returns the course context
741 *
742 * @return stdClass
743 */
744 public function get_context() {
745 return $this->context;
746 }
747
6db3eee0
SH
748 /**
749 * Gets an array of other users in this course ready for display.
750 *
751 * Other users are users who have been assigned or inherited roles within this
752 * course but have not been enrolled.
753 *
754 * @param core_enrol_renderer $renderer
755 * @param moodle_url $pageurl
756 * @param string $sort
757 * @param string $direction ASC | DESC
758 * @param int $page Starting from 0
759 * @param int $perpage
760 * @return array
761 */
762 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
5379726a 763
6db3eee0
SH
764 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
765 $roles = $this->get_all_roles();
766
767 $courseid = $this->get_course()->id;
768 $context = $this->get_context();
769
770 $users = array();
771 foreach ($userroles as $userrole) {
772 if (!array_key_exists($userrole->id, $users)) {
773 $users[$userrole->id] = array(
774 'userid' => $userrole->id,
775 'courseid' => $courseid,
776 'picture' => new user_picture($userrole),
777 'firstname' => fullname($userrole, true),
778 'email' => $userrole->email,
779 'roles' => array()
780 );
781 }
782 $a = new stdClass;
783 $a->role = $roles[$userrole->roleid]->localname;
784 $changeable = ($userrole->component == '');
785 if ($userrole->contextid == $this->context->id) {
786 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
787 } else {
788 $changeable = false;
789 switch ($userrole->contextlevel) {
790 case CONTEXT_COURSE :
791 // Meta course
792 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
793 break;
794 case CONTEXT_COURSECAT :
795 $roletext = get_string('rolefromcategory', 'enrol', $a);
796 break;
797 case CONTEXT_SYSTEM:
798 default:
799 $roletext = get_string('rolefromsystem', 'enrol', $a);
800 break;
801 }
802 }
803 $users[$userrole->id]['roles'][$userrole->roleid] = array(
804 'text' => $roletext,
805 'unchangeable' => !$changeable
806 );
807 }
808 return $users;
809 }
810
a70eb30f
SH
811 /**
812 * Gets an array of users for display, this includes minimal user information
813 * as well as minimal information on the users roles, groups, and enrolments.
814 *
815 * @param core_enrol_renderer $renderer
816 * @param moodle_url $pageurl
817 * @param int $sort
818 * @param string $direction ASC or DESC
819 * @param int $page
820 * @param int $perpage
821 * @return array
822 */
291215f4
SH
823 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
824 $pageurl = $manager->get_moodlepage()->url;
a70eb30f
SH
825 $users = $this->get_users($sort, $direction, $page, $perpage);
826
827 $now = time();
828 $strnever = get_string('never');
829 $straddgroup = get_string('addgroup', 'group');
830 $strunenrol = get_string('unenrol', 'enrol');
831 $stredit = get_string('edit');
832
a70eb30f
SH
833 $allroles = $this->get_all_roles();
834 $assignable = $this->get_assignable_roles();
835 $allgroups = $this->get_all_groups();
836 $courseid = $this->get_course()->id;
837 $context = $this->get_context();
838 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
839
840 $url = new moodle_url($pageurl, $this->get_url_params());
b849c212 841 $extrafields = get_extra_user_fields($context);
a70eb30f
SH
842
843 $userdetails = array();
844 foreach ($users as $user) {
845 $details = array(
846 'userid' => $user->id,
847 'courseid' => $courseid,
848 'picture' => new user_picture($user),
849 'firstname' => fullname($user, true),
a70eb30f
SH
850 'lastseen' => $strnever,
851 'roles' => array(),
852 'groups' => array(),
853 'enrolments' => array()
854 );
b849c212 855 foreach ($extrafields as $field) {
856 $details[$field] = $user->{$field};
857 }
a70eb30f 858
6db3eee0
SH
859 if ($user->lastaccess) {
860 $details['lastseen'] = format_time($now - $user->lastaccess);
a70eb30f
SH
861 }
862
863 // Roles
864 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
865 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>(!$rassignable || !isset($assignable[$rid])));
866 }
867
868 // Users
869 $usergroups = $this->get_user_groups($user->id);
870 foreach($usergroups as $gid=>$unused) {
871 $details['groups'][$gid] = $allgroups[$gid]->name;
872 }
873
874 // Enrolments
875 foreach ($this->get_user_enrolments($user->id) as $ue) {
876 if ($ue->timestart and $ue->timeend) {
877 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
878 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
879 } else if ($ue->timestart) {
880 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
881 $periodoutside = ($ue->timestart && $now < $ue->timestart);
882 } else if ($ue->timeend) {
883 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
884 $periodoutside = ($ue->timeend && $now > $ue->timeend);
885 } else {
886 $period = '';
887 $periodoutside = false;
888 }
889 $details['enrolments'][$ue->id] = array(
890 'text' => $ue->enrolmentinstancename,
891 'period' => $period,
892 'dimmed' => ($periodoutside || $ue->status != ENROL_USER_ACTIVE),
291215f4 893 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
a70eb30f
SH
894 );
895 }
896 $userdetails[$user->id] = $details;
897 }
898 return $userdetails;
a70eb30f 899 }
b69ca6be
SH
900
901 public function get_manual_enrol_buttons() {
902 $plugins = $this->get_enrolment_plugins();
903 $buttons = array();
904 foreach ($plugins as $plugin) {
905 $newbutton = $plugin->get_manual_enrol_button($this);
906 if (is_array($newbutton)) {
907 $buttons += $newbutton;
908 } else if ($newbutton instanceof enrol_user_button) {
909 $buttons[] = $newbutton;
910 }
911 }
912 return $buttons;
913 }
914
915 public function has_instance($enrolpluginname) {
916 // Make sure manual enrolments instance exists
917 foreach ($this->get_enrolment_instances() as $instance) {
918 if ($instance->enrol == $enrolpluginname) {
919 return true;
920 }
921 }
922 return false;
923 }
75ee207b
SH
924
925 /**
926 * Returns the enrolment plugin that the course manager was being filtered to.
927 *
928 * If no filter was being applied then this function returns false.
929 *
930 * @return enrol_plugin
931 */
932 public function get_filtered_enrolment_plugin() {
933 $instances = $this->get_enrolment_instances();
934 $plugins = $this->get_enrolment_plugins();
935
936 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
937 return false;
938 }
939
940 $instance = $instances[$this->instancefilter];
941 return $plugins[$instance->enrol];
942 }
943
944 /**
945 * Returns and array of users + enrolment details.
946 *
947 * Given an array of user id's this function returns and array of user enrolments for those users
948 * as well as enough user information to display the users name and picture for each enrolment.
949 *
950 * @global moodle_database $DB
951 * @param array $userids
952 * @return array
953 */
954 public function get_users_enrolments(array $userids) {
955 global $DB;
956
957 $instances = $this->get_enrolment_instances();
958 $plugins = $this->get_enrolment_plugins();
959
960 if (!empty($this->instancefilter)) {
961 $instancesql = ' = :instanceid';
962 $instanceparams = array('instanceid' => $this->instancefilter);
963 } else {
964 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
965 }
966
967 $userfields = user_picture::fields('u');
968 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
969
970 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
971 FROM {user_enrolments} ue
972 LEFT JOIN {user} u ON u.id = ue.userid
973 WHERE ue.enrolid $instancesql AND
974 u.id $idsql
975 ORDER BY u.firstname ASC, u.lastname ASC";
976
977 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams);
978 $users = array();
979 foreach ($rs as $ue) {
980 $user = user_picture::unalias($ue);
981 $ue->id = $ue->ueid;
982 unset($ue->ueid);
983 if (!array_key_exists($user->id, $users)) {
984 $user->enrolments = array();
985 $users[$user->id] = $user;
986 }
987 $ue->enrolmentinstance = $instances[$ue->enrolid];
988 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
989 $users[$user->id]->enrolments[$ue->id] = $ue;
990 }
991 $rs->close();
992 return $users;
993 }
b69ca6be
SH
994}
995
996/**
997 * A button that is used to enrol users in a course
998 *
999 * @copyright 2010 Sam Hemelryk
1000 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1001 */
1002class enrol_user_button extends single_button {
1003
1004 /**
1005 * An array containing JS YUI modules required by this button
1006 * @var array
1007 */
1008 protected $jsyuimodules = array();
1009
1010 /**
1011 * An array containing JS initialisation calls required by this button
1012 * @var array
1013 */
1014 protected $jsinitcalls = array();
1015
1016 /**
1017 * An array strings required by JS for this button
1018 * @var array
1019 */
1020 protected $jsstrings = array();
1021
1022 /**
1023 * Initialises the new enrol_user_button
1024 *
1025 * @staticvar int $count The number of enrol user buttons already created
1026 * @param moodle_url $url
1027 * @param string $label The text to display in the button
1028 * @param string $method Either post or get
1029 */
1030 public function __construct(moodle_url $url, $label, $method = 'post') {
1031 static $count = 0;
1032 $count ++;
1033 parent::__construct($url, $label, $method);
1034 $this->class = 'singlebutton enrolusersbutton';
1035 $this->formid = 'enrolusersbutton-'.$count;
1036 }
1037
1038 /**
1039 * Adds a YUI module call that will be added to the page when the button is used.
1040 *
1041 * @param string|array $modules One or more modules to require
1042 * @param string $function The JS function to call
1043 * @param array $arguments An array of arguments to pass to the function
1044 * @param string $galleryversion The YUI gallery version of any modules required
1045 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1046 */
1047 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1048 $js = new stdClass;
1049 $js->modules = (array)$modules;
1050 $js->function = $function;
1051 $js->arguments = $arguments;
1052 $js->galleryversion = $galleryversion;
1053 $js->ondomready = $ondomready;
1054 $this->jsyuimodules[] = $js;
1055 }
1056
1057 /**
1058 * Adds a JS initialisation call to the page when the button is used.
1059 *
1060 * @param string $function The function to call
1061 * @param array $extraarguments An array of arguments to pass to the function
1062 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1063 * @param array $module A module definition
1064 */
1065 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1066 $js = new stdClass;
1067 $js->function = $function;
1068 $js->extraarguments = $extraarguments;
1069 $js->ondomready = $ondomready;
1070 $js->module = $module;
1071 $this->jsinitcalls[] = $js;
1072 }
1073
1074 /**
1075 * Requires strings for JS that will be loaded when the button is used.
1076 *
1077 * @param type $identifiers
1078 * @param string $component
1079 * @param mixed $a
1080 */
1081 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1082 $string = new stdClass;
1083 $string->identifiers = (array)$identifiers;
1084 $string->component = $component;
1085 $string->a = $a;
1086 $this->jsstrings[] = $string;
1087 }
1088
1089 /**
1090 * Initialises the JS that is required by this button
1091 *
1092 * @param moodle_page $page
1093 */
1094 public function initialise_js(moodle_page $page) {
1095 foreach ($this->jsyuimodules as $js) {
1096 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1097 }
1098 foreach ($this->jsinitcalls as $js) {
1099 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1100 }
1101 foreach ($this->jsstrings as $string) {
1102 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1103 }
1104 }
6db3eee0
SH
1105}
1106
291215f4
SH
1107/**
1108 * User enrolment action
1109 *
1110 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1111 * a user enrolment.
1112 *
1113 * @copyright 2011 Sam Hemelryk
1114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1115 */
1116class user_enrolment_action implements renderable {
1117
1118 /**
1119 * The icon to display for the action
1120 * @var pix_icon
1121 */
1122 protected $icon;
1123
1124 /**
1125 * The title for the action
1126 * @var string
1127 */
1128 protected $title;
1129
1130 /**
1131 * The URL to the action
1132 * @var moodle_url
1133 */
1134 protected $url;
1135
1136 /**
1137 * An array of HTML attributes
1138 * @var array
1139 */
1140 protected $attributes = array();
1141
1142 /**
1143 * Constructor
1144 * @param pix_icon $icon
1145 * @param string $title
1146 * @param moodle_url $url
1147 * @param array $attributes
1148 */
1149 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1150 $this->icon = $icon;
1151 $this->title = $title;
1152 $this->url = new moodle_url($url);
1153 if (!empty($attributes)) {
1154 $this->attributes = $attributes;
1155 }
1156 $this->attributes['title'] = $title;
1157 }
1158
1159 /**
1160 * Returns the icon for this action
1161 * @return pix_icon
1162 */
1163 public function get_icon() {
1164 return $this->icon;
1165 }
1166
1167 /**
1168 * Returns the title for this action
1169 * @return string
1170 */
1171 public function get_title() {
1172 return $this->title;
1173 }
1174
1175 /**
1176 * Returns the URL for this action
1177 * @return moodle_url
1178 */
1179 public function get_url() {
1180 return $this->url;
1181 }
1182
1183 /**
1184 * Returns the attributes to use for this action
1185 * @return array
1186 */
1187 public function get_attributes() {
1188 return $this->attributes;
1189 }
1190}
1191
6db3eee0
SH
1192class enrol_ajax_exception extends moodle_exception {
1193 /**
1194 * Constructor
1195 * @param string $errorcode The name of the string from error.php to print
1196 * @param string $module name of module
1197 * @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.
1198 * @param object $a Extra words and phrases that might be required in the error string
1199 * @param string $debuginfo optional debugging information
1200 */
1201 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1202 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1203 }
75ee207b
SH
1204}
1205
1206/**
1207 * This class is used to manage a bulk operations for enrolment plugins.
1208 *
1209 * @copyright 2011 Sam Hemelryk
1210 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1211 */
1212abstract class enrol_bulk_enrolment_operation {
1213
1214 /**
1215 * The course enrolment manager
1216 * @var course_enrolment_manager
1217 */
1218 protected $manager;
1219
1220 /**
1221 * The enrolment plugin to which this operation belongs
1222 * @var enrol_plugin
1223 */
1224 protected $plugin;
1225
1226 /**
1227 * Contructor
1228 * @param course_enrolment_manager $manager
1229 * @param stdClass $plugin
1230 */
1231 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1232 $this->manager = $manager;
1233 $this->plugin = $plugin;
1234 }
1235
1236 /**
1237 * Returns a moodleform used for this operation, or false if no form is required and the action
1238 * should be immediatly processed.
1239 *
1240 * @param moodle_url|string $defaultaction
1241 * @param mixed $defaultcustomdata
1242 * @return enrol_bulk_enrolment_change_form|moodleform|false
1243 */
1244 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1245 return false;
1246 }
1247
1248 /**
1249 * Returns the title to use for this bulk operation
1250 *
1251 * @return string
1252 */
1253 abstract public function get_title();
1254
1255 /**
1256 * Returns the identifier for this bulk operation.
1257 * This should be the same identifier used by the plugins function when returning
1258 * all of its bulk operations.
1259 *
1260 * @return string
1261 */
1262 abstract public function get_identifier();
1263
1264 /**
1265 * Processes the bulk operation on the given users
1266 *
1267 * @param course_enrolment_manager $manager
1268 * @param array $users
1269 * @param stdClass $properties
1270 */
1271 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);
5dbfbacc 1272}