MDL-26647 (7) Support showuseridentity on assignment report
[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
122 * @return moodle_page
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();
df4a889e
PS
202 $ufields = user_picture::fields('u', array('lastaccess', 'email'));
203 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
a70eb30f
SH
204 FROM {user} u
205 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
206 JOIN {enrol} e ON (e.id = ue.enrolid)
207 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
208 if ($sort === 'firstname') {
209 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
210 } else if ($sort === 'lastname') {
211 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
212 } else if ($sort === 'email') {
213 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
214 } else if ($sort === 'lastseen') {
215 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
216 }
217 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
218 }
219 return $this->users[$key];
220 }
221
6db3eee0
SH
222 /**
223 * Gets and array of other users.
224 *
225 * Other users are users who have been assigned roles or inherited roles
226 * within this course but who have not been enrolled in the course
227 *
228 * @global moodle_database $DB
229 * @param string $sort
230 * @param string $direction
231 * @param int $page
232 * @param int $perpage
233 * @return array
234 */
235 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
236 global $DB;
237 if ($direction !== 'ASC') {
238 $direction = 'DESC';
239 }
240 $key = md5("$sort-$direction-$page-$perpage");
241 if (!array_key_exists($key, $this->otherusers)) {
cf717dc2 242 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
6db3eee0
SH
243 $params['courseid'] = $this->course->id;
244 $params['cid'] = $this->course->id;
245 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
246 FROM {role_assignments} ra
247 JOIN {user} u ON u.id = ra.userid
248 JOIN {context} ctx ON ra.contextid = ctx.id
884faffd
SH
249 LEFT JOIN (
250 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
251 FROM {user_enrolments} ue
252 LEFT JOIN {enrol} e ON e.id=ue.enrolid
253 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
6db3eee0 254 WHERE e.courseid = :courseid
884faffd
SH
255 ) ue ON ue.userid=u.id
256 WHERE ctx.id $ctxcondition AND
257 ue.id IS NULL
258 ORDER BY u.$sort $direction, ctx.depth DESC";
6db3eee0
SH
259 $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
260 }
261 return $this->otherusers[$key];
262 }
263
a70eb30f
SH
264 /**
265 * Gets an array of the users that can be enrolled in this course.
266 *
267 * @global moodle_database $DB
268 * @param int $enrolid
269 * @param string $search
270 * @param bool $searchanywhere
271 * @param int $page Defaults to 0
272 * @param int $perpage Defaults to 25
273 * @return array Array(totalusers => int, users => array)
274 */
275 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25) {
b3df1764 276 global $DB, $CFG;
a70eb30f
SH
277
278 // Add some additional sensible conditions
b3df1764
PS
279 $tests = array("id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
280 $params = array('guestid' => $CFG->siteguest);
a70eb30f 281 if (!empty($search)) {
9fc9de91
SH
282 $conditions = array(
283 $DB->sql_concat('u.firstname', "' '", 'u.lastname'),
284 'u.email'
285 );
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
93b4ecb2 301 $ufields = user_picture::fields('u', array('username', 'lastaccess'));
a70eb30f 302
93b4ecb2 303 $fields = 'SELECT '.$ufields;
a70eb30f
SH
304 $countfields = 'SELECT COUNT(1)';
305 $sql = " FROM {user} u
306 WHERE $wherecondition
307 AND u.id NOT IN (SELECT ue.userid
308 FROM {user_enrolments} ue
309 JOIN {enrol} e ON (e.id = ue.enrolid AND e.id = :enrolid))";
310 $order = ' ORDER BY u.lastname ASC, u.firstname ASC';
311 $params['enrolid'] = $enrolid;
312 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
313 $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
314 return array('totalusers'=>$totalusers, 'users'=>$availableusers);
315 }
316
6db3eee0
SH
317 /**
318 * Searches other users and returns paginated results
319 *
320 * @global moodle_database $DB
321 * @param string $search
322 * @param bool $searchanywhere
323 * @param int $page Starting at 0
324 * @param int $perpage
325 * @return array
326 */
327 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
b3df1764 328 global $DB, $CFG;
6db3eee0
SH
329
330 // Add some additional sensible conditions
b3df1764
PS
331 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
332 $params = array('guestid'=>$CFG->siteguest);
6db3eee0
SH
333 if (!empty($search)) {
334 $conditions = array('u.firstname','u.lastname');
6db3eee0
SH
335 if ($searchanywhere) {
336 $searchparam = '%' . $search . '%';
337 } else {
338 $searchparam = $search . '%';
339 }
340 $i = 0;
f7614bb0
PS
341 foreach ($conditions as $key=>$condition) {
342 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
6db3eee0
SH
343 $params["con{$i}00"] = $searchparam;
344 $i++;
345 }
346 $tests[] = '(' . implode(' OR ', $conditions) . ')';
347 }
348 $wherecondition = implode(' AND ', $tests);
5379726a 349
603087b8 350 $fields = 'SELECT '.user_picture::fields('u', array('username','lastaccess'));
6db3eee0
SH
351 $countfields = 'SELECT COUNT(u.id)';
352 $sql = " FROM {user} u
353 WHERE $wherecondition
884faffd 354 AND u.id NOT IN (
6db3eee0
SH
355 SELECT u.id
356 FROM {role_assignments} r, {user} u
884faffd
SH
357 WHERE r.contextid = :contextid AND
358 u.id = r.userid)";
6db3eee0
SH
359 $order = ' ORDER BY lastname ASC, firstname ASC';
360
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);
365 }
366
a70eb30f
SH
367 /**
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.
370 *
371 * @global moodle_database $DB
372 * @return string
373 */
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);
390 }
391 }
392 $this->instancefilter = $filter;
393 $this->_instancessql = array($sql, $params, $filter);
394 }
395 return $this->_instancessql;
396 }
397
398 /**
399 * Returns all of the enrolment instances for this course.
400 *
401 * @return array
402 */
403 public function get_enrolment_instances() {
404 if ($this->_instances === null) {
405 $this->_instances = enrol_get_instances($this->course->id, true);
406 }
407 return $this->_instances;
408 }
409
410 /**
411 * Returns the names for all of the enrolment instances for this course.
412 *
413 * @return array
414 */
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;
424 }
425 $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
426 }
427 }
428 return $this->_inames;
429 }
430
431 /**
432 * Gets all of the enrolment plugins that are active for this course.
433 *
434 * @return array
435 */
436 public function get_enrolment_plugins() {
437 if ($this->_plugins === null) {
438 $this->_plugins = enrol_get_plugins(true);
439 }
440 return $this->_plugins;
441 }
442
443 /**
444 * Gets all of the roles this course can contain.
445 *
446 * @return array
447 */
448 public function get_all_roles() {
449 if ($this->_roles === null) {
450 $this->_roles = role_fix_names(get_all_roles(), $this->context);
451 }
452 return $this->_roles;
453 }
454
455 /**
456 * Gets all of the assignable roles for this course.
457 *
458 * @return array
459 */
9f15347e 460 public function get_assignable_roles($otherusers = false) {
a70eb30f
SH
461 if ($this->_assignableroles === null) {
462 $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
463 }
9f15347e
SH
464
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;
472 }
473 }
474 }
475 return $this->_assignablerolesothers;
476 } else {
477 return $this->_assignableroles;
478 }
a70eb30f
SH
479 }
480
481 /**
482 * Gets all of the groups for this course.
483 *
484 * @return array
485 */
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);
491 }
492 }
493 return $this->_groups;
494 }
495
496 /**
df4a889e 497 * Unenrols a user from the course given the users ue entry
a70eb30f
SH
498 *
499 * @global moodle_database $DB
500 * @param stdClass $ue
501 * @return bool
502 */
503 public function unenrol_user($ue) {
a942f757 504 global $DB;
a3c71984
SH
505 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
506 if ($instance && $plugin && $plugin->allow_unenrol($instance) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
507 $plugin->unenrol_user($instance, $ue->userid);
508 return true;
509 }
510 return false;
511 }
a70eb30f 512
a3c71984
SH
513 /**
514 * Given a user enrolment record this method returns the plugin and enrolment
515 * instance that relate to it.
516 *
517 * @param stdClass|int $userenrolment
518 * @return array array($instance, $plugin)
519 */
520 public function get_user_enrolment_components($userenrolment) {
521 global $DB;
a942f757 522 if (is_numeric($userenrolment)) {
a3c71984
SH
523 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
524 }
a70eb30f
SH
525 $instances = $this->get_enrolment_instances();
526 $plugins = $this->get_enrolment_plugins();
a3c71984
SH
527 if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
528 return array(false, false);
a70eb30f 529 }
a3c71984 530 $instance = $instances[$userenrolment->enrolid];
a70eb30f 531 $plugin = $plugins[$instance->enrol];
a3c71984 532 return array($instance, $plugin);
a70eb30f
SH
533 }
534
535 /**
536 * Removes an assigned role from a user.
537 *
538 * @global moodle_database $DB
539 * @param int $userid
540 * @param int $roleid
541 * @return bool
542 */
543 public function unassign_role_from_user($userid, $roleid) {
544 global $DB;
a3c71984 545 require_capability('moodle/role:assign', $this->context);
a70eb30f
SH
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) {
894843b4 550 if (defined('AJAX_SCRIPT')) {
6db3eee0
SH
551 throw $e;
552 }
a70eb30f
SH
553 return false;
554 }
555 return true;
556 }
557
558 /**
559 * Assigns a role to a user.
560 *
561 * @param int $roleid
562 * @param int $userid
563 * @return int|false
564 */
565 public function assign_role_to_user($roleid, $userid) {
566 require_capability('moodle/role:assign', $this->context);
823a807e 567 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
894843b4 568 if (defined('AJAX_SCRIPT')) {
c05260de 569 throw new moodle_exception('invalidrole');
6db3eee0 570 }
823a807e
SH
571 return false;
572 }
a70eb30f
SH
573 return role_assign($roleid, $userid, $this->context->id, '', NULL);
574 }
575
576 /**
577 * Adds a user to a group
578 *
579 * @param stdClass $user
580 * @param int $groupid
581 * @return bool
582 */
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;
588 }
589 return groups_add_member($group->id, $user->id);
590 }
591
592 /**
593 * Removes a user from a group
594 *
595 * @global moodle_database $DB
596 * @param StdClass $user
597 * @param int $groupid
598 * @return bool
599 */
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;
606 }
607 return groups_remove_member($group, $user);
608 }
609
610 /**
611 * Gets the requested group
612 *
613 * @param int $groupid
614 * @return stdClass|int
615 */
616 public function get_group($groupid) {
617 $groups = $this->get_all_groups();
618 if (!array_key_exists($groupid, $groups)) {
619 return false;
620 }
621 return $groups[$groupid];
622 }
623
624 /**
625 * Edits an enrolment
626 *
627 * @param stdClass $userenrolment
628 * @param stdClass $data
629 * @return bool
630 */
631 public function edit_enrolment($userenrolment, $data) {
13ba9036
AD
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
621ee955 634 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
a3c71984
SH
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;
638 }
639 $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
640 return true;
a70eb30f 641 }
a3c71984 642 return false;
a70eb30f
SH
643 }
644
645 /**
646 * Returns the current enrolment filter that is being applied by this class
647 * @return string
648 */
649 public function get_enrolment_filter() {
650 return $this->instancefilter;
651 }
652
653 /**
654 * Gets the roles assigned to this user that are applicable for this course.
655 *
656 * @param int $userid
657 * @return array
658 */
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;
666 }
667 // higher ras, course always takes precedence
668 continue;
669 }
670 if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
671 continue;
672 }
673 $roles[$ra->roleid] = ($ra->itemid == 0 and $ra->component === '');
674 }
675 return $roles;
676 }
677
678 /**
679 * Gets the enrolments this user has in the course
680 *
681 * @global moodle_database $DB
682 * @param int $userid
683 * @return array
684 */
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];
697 }
698 return $userenrolments;
699 }
700
701 /**
702 * Gets the groups this user belongs to
703 *
704 * @param int $userid
705 * @return array
706 */
707 public function get_user_groups($userid) {
708 return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
709 }
710
711 /**
712 * Retursn an array of params that would go into the URL to return to this
713 * exact page.
714 *
715 * @return array
716 */
717 public function get_url_params() {
718 $args = array(
719 'id' => $this->course->id
720 );
721 if (!empty($this->instancefilter)) {
722 $args['ifilter'] = $this->instancefilter;
723 }
724 return $args;
725 }
726
727 /**
728 * Returns the course this object is managing enrolments for
729 *
730 * @return stdClass
731 */
732 public function get_course() {
733 return $this->course;
734 }
735
736 /**
737 * Returns the course context
738 *
739 * @return stdClass
740 */
741 public function get_context() {
742 return $this->context;
743 }
744
6db3eee0
SH
745 /**
746 * Gets an array of other users in this course ready for display.
747 *
748 * Other users are users who have been assigned or inherited roles within this
749 * course but have not been enrolled.
750 *
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
758 */
759 public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
5379726a 760
6db3eee0
SH
761 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
762 $roles = $this->get_all_roles();
763
764 $courseid = $this->get_course()->id;
765 $context = $this->get_context();
766
767 $users = array();
768 foreach ($userroles as $userrole) {
769 if (!array_key_exists($userrole->id, $users)) {
770 $users[$userrole->id] = array(
771 'userid' => $userrole->id,
772 'courseid' => $courseid,
773 'picture' => new user_picture($userrole),
774 'firstname' => fullname($userrole, true),
775 'email' => $userrole->email,
776 'roles' => array()
777 );
778 }
779 $a = new stdClass;
780 $a->role = $roles[$userrole->roleid]->localname;
781 $changeable = ($userrole->component == '');
782 if ($userrole->contextid == $this->context->id) {
783 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
784 } else {
785 $changeable = false;
786 switch ($userrole->contextlevel) {
787 case CONTEXT_COURSE :
788 // Meta course
789 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
790 break;
791 case CONTEXT_COURSECAT :
792 $roletext = get_string('rolefromcategory', 'enrol', $a);
793 break;
794 case CONTEXT_SYSTEM:
795 default:
796 $roletext = get_string('rolefromsystem', 'enrol', $a);
797 break;
798 }
799 }
800 $users[$userrole->id]['roles'][$userrole->roleid] = array(
801 'text' => $roletext,
802 'unchangeable' => !$changeable
803 );
804 }
805 return $users;
806 }
807
a70eb30f
SH
808 /**
809 * Gets an array of users for display, this includes minimal user information
810 * as well as minimal information on the users roles, groups, and enrolments.
811 *
812 * @param core_enrol_renderer $renderer
813 * @param moodle_url $pageurl
814 * @param int $sort
815 * @param string $direction ASC or DESC
816 * @param int $page
817 * @param int $perpage
818 * @return array
819 */
291215f4
SH
820 public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
821 $pageurl = $manager->get_moodlepage()->url;
a70eb30f
SH
822 $users = $this->get_users($sort, $direction, $page, $perpage);
823
824 $now = time();
825 $strnever = get_string('never');
826 $straddgroup = get_string('addgroup', 'group');
827 $strunenrol = get_string('unenrol', 'enrol');
828 $stredit = get_string('edit');
829
a70eb30f
SH
830 $allroles = $this->get_all_roles();
831 $assignable = $this->get_assignable_roles();
832 $allgroups = $this->get_all_groups();
833 $courseid = $this->get_course()->id;
834 $context = $this->get_context();
835 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
836
837 $url = new moodle_url($pageurl, $this->get_url_params());
838
839 $userdetails = array();
840 foreach ($users as $user) {
841 $details = array(
842 'userid' => $user->id,
843 'courseid' => $courseid,
844 'picture' => new user_picture($user),
845 'firstname' => fullname($user, true),
846 'email' => $user->email,
847 'lastseen' => $strnever,
848 'roles' => array(),
849 'groups' => array(),
850 'enrolments' => array()
851 );
852
6db3eee0
SH
853 if ($user->lastaccess) {
854 $details['lastseen'] = format_time($now - $user->lastaccess);
a70eb30f
SH
855 }
856
857 // Roles
858 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
859 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>(!$rassignable || !isset($assignable[$rid])));
860 }
861
862 // Users
863 $usergroups = $this->get_user_groups($user->id);
864 foreach($usergroups as $gid=>$unused) {
865 $details['groups'][$gid] = $allgroups[$gid]->name;
866 }
867
868 // Enrolments
869 foreach ($this->get_user_enrolments($user->id) as $ue) {
870 if ($ue->timestart and $ue->timeend) {
871 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
872 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
873 } else if ($ue->timestart) {
874 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
875 $periodoutside = ($ue->timestart && $now < $ue->timestart);
876 } else if ($ue->timeend) {
877 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
878 $periodoutside = ($ue->timeend && $now > $ue->timeend);
879 } else {
880 $period = '';
881 $periodoutside = false;
882 }
883 $details['enrolments'][$ue->id] = array(
884 'text' => $ue->enrolmentinstancename,
885 'period' => $period,
886 'dimmed' => ($periodoutside || $ue->status != ENROL_USER_ACTIVE),
291215f4 887 'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
a70eb30f
SH
888 );
889 }
890 $userdetails[$user->id] = $details;
891 }
892 return $userdetails;
a70eb30f 893 }
b69ca6be
SH
894
895 public function get_manual_enrol_buttons() {
896 $plugins = $this->get_enrolment_plugins();
897 $buttons = array();
898 foreach ($plugins as $plugin) {
899 $newbutton = $plugin->get_manual_enrol_button($this);
900 if (is_array($newbutton)) {
901 $buttons += $newbutton;
902 } else if ($newbutton instanceof enrol_user_button) {
903 $buttons[] = $newbutton;
904 }
905 }
906 return $buttons;
907 }
908
909 public function has_instance($enrolpluginname) {
910 // Make sure manual enrolments instance exists
911 foreach ($this->get_enrolment_instances() as $instance) {
912 if ($instance->enrol == $enrolpluginname) {
913 return true;
914 }
915 }
916 return false;
917 }
75ee207b
SH
918
919 /**
920 * Returns the enrolment plugin that the course manager was being filtered to.
921 *
922 * If no filter was being applied then this function returns false.
923 *
924 * @return enrol_plugin
925 */
926 public function get_filtered_enrolment_plugin() {
927 $instances = $this->get_enrolment_instances();
928 $plugins = $this->get_enrolment_plugins();
929
930 if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
931 return false;
932 }
933
934 $instance = $instances[$this->instancefilter];
935 return $plugins[$instance->enrol];
936 }
937
938 /**
939 * Returns and array of users + enrolment details.
940 *
941 * Given an array of user id's this function returns and array of user enrolments for those users
942 * as well as enough user information to display the users name and picture for each enrolment.
943 *
944 * @global moodle_database $DB
945 * @param array $userids
946 * @return array
947 */
948 public function get_users_enrolments(array $userids) {
949 global $DB;
950
951 $instances = $this->get_enrolment_instances();
952 $plugins = $this->get_enrolment_plugins();
953
954 if (!empty($this->instancefilter)) {
955 $instancesql = ' = :instanceid';
956 $instanceparams = array('instanceid' => $this->instancefilter);
957 } else {
958 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
959 }
960
961 $userfields = user_picture::fields('u');
962 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
963
964 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
965 FROM {user_enrolments} ue
966 LEFT JOIN {user} u ON u.id = ue.userid
967 WHERE ue.enrolid $instancesql AND
968 u.id $idsql
969 ORDER BY u.firstname ASC, u.lastname ASC";
970
971 $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams);
972 $users = array();
973 foreach ($rs as $ue) {
974 $user = user_picture::unalias($ue);
975 $ue->id = $ue->ueid;
976 unset($ue->ueid);
977 if (!array_key_exists($user->id, $users)) {
978 $user->enrolments = array();
979 $users[$user->id] = $user;
980 }
981 $ue->enrolmentinstance = $instances[$ue->enrolid];
982 $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
983 $users[$user->id]->enrolments[$ue->id] = $ue;
984 }
985 $rs->close();
986 return $users;
987 }
b69ca6be
SH
988}
989
990/**
991 * A button that is used to enrol users in a course
992 *
993 * @copyright 2010 Sam Hemelryk
994 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
995 */
996class enrol_user_button extends single_button {
997
998 /**
999 * An array containing JS YUI modules required by this button
1000 * @var array
1001 */
1002 protected $jsyuimodules = array();
1003
1004 /**
1005 * An array containing JS initialisation calls required by this button
1006 * @var array
1007 */
1008 protected $jsinitcalls = array();
1009
1010 /**
1011 * An array strings required by JS for this button
1012 * @var array
1013 */
1014 protected $jsstrings = array();
1015
1016 /**
1017 * Initialises the new enrol_user_button
1018 *
1019 * @staticvar int $count The number of enrol user buttons already created
1020 * @param moodle_url $url
1021 * @param string $label The text to display in the button
1022 * @param string $method Either post or get
1023 */
1024 public function __construct(moodle_url $url, $label, $method = 'post') {
1025 static $count = 0;
1026 $count ++;
1027 parent::__construct($url, $label, $method);
1028 $this->class = 'singlebutton enrolusersbutton';
1029 $this->formid = 'enrolusersbutton-'.$count;
1030 }
1031
1032 /**
1033 * Adds a YUI module call that will be added to the page when the button is used.
1034 *
1035 * @param string|array $modules One or more modules to require
1036 * @param string $function The JS function to call
1037 * @param array $arguments An array of arguments to pass to the function
1038 * @param string $galleryversion The YUI gallery version of any modules required
1039 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1040 */
1041 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
1042 $js = new stdClass;
1043 $js->modules = (array)$modules;
1044 $js->function = $function;
1045 $js->arguments = $arguments;
1046 $js->galleryversion = $galleryversion;
1047 $js->ondomready = $ondomready;
1048 $this->jsyuimodules[] = $js;
1049 }
1050
1051 /**
1052 * Adds a JS initialisation call to the page when the button is used.
1053 *
1054 * @param string $function The function to call
1055 * @param array $extraarguments An array of arguments to pass to the function
1056 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1057 * @param array $module A module definition
1058 */
1059 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1060 $js = new stdClass;
1061 $js->function = $function;
1062 $js->extraarguments = $extraarguments;
1063 $js->ondomready = $ondomready;
1064 $js->module = $module;
1065 $this->jsinitcalls[] = $js;
1066 }
1067
1068 /**
1069 * Requires strings for JS that will be loaded when the button is used.
1070 *
1071 * @param type $identifiers
1072 * @param string $component
1073 * @param mixed $a
1074 */
1075 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1076 $string = new stdClass;
1077 $string->identifiers = (array)$identifiers;
1078 $string->component = $component;
1079 $string->a = $a;
1080 $this->jsstrings[] = $string;
1081 }
1082
1083 /**
1084 * Initialises the JS that is required by this button
1085 *
1086 * @param moodle_page $page
1087 */
1088 public function initialise_js(moodle_page $page) {
1089 foreach ($this->jsyuimodules as $js) {
1090 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1091 }
1092 foreach ($this->jsinitcalls as $js) {
1093 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1094 }
1095 foreach ($this->jsstrings as $string) {
1096 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1097 }
1098 }
6db3eee0
SH
1099}
1100
291215f4
SH
1101/**
1102 * User enrolment action
1103 *
1104 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1105 * a user enrolment.
1106 *
1107 * @copyright 2011 Sam Hemelryk
1108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1109 */
1110class user_enrolment_action implements renderable {
1111
1112 /**
1113 * The icon to display for the action
1114 * @var pix_icon
1115 */
1116 protected $icon;
1117
1118 /**
1119 * The title for the action
1120 * @var string
1121 */
1122 protected $title;
1123
1124 /**
1125 * The URL to the action
1126 * @var moodle_url
1127 */
1128 protected $url;
1129
1130 /**
1131 * An array of HTML attributes
1132 * @var array
1133 */
1134 protected $attributes = array();
1135
1136 /**
1137 * Constructor
1138 * @param pix_icon $icon
1139 * @param string $title
1140 * @param moodle_url $url
1141 * @param array $attributes
1142 */
1143 public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1144 $this->icon = $icon;
1145 $this->title = $title;
1146 $this->url = new moodle_url($url);
1147 if (!empty($attributes)) {
1148 $this->attributes = $attributes;
1149 }
1150 $this->attributes['title'] = $title;
1151 }
1152
1153 /**
1154 * Returns the icon for this action
1155 * @return pix_icon
1156 */
1157 public function get_icon() {
1158 return $this->icon;
1159 }
1160
1161 /**
1162 * Returns the title for this action
1163 * @return string
1164 */
1165 public function get_title() {
1166 return $this->title;
1167 }
1168
1169 /**
1170 * Returns the URL for this action
1171 * @return moodle_url
1172 */
1173 public function get_url() {
1174 return $this->url;
1175 }
1176
1177 /**
1178 * Returns the attributes to use for this action
1179 * @return array
1180 */
1181 public function get_attributes() {
1182 return $this->attributes;
1183 }
1184}
1185
6db3eee0
SH
1186class enrol_ajax_exception extends moodle_exception {
1187 /**
1188 * Constructor
1189 * @param string $errorcode The name of the string from error.php to print
1190 * @param string $module name of module
1191 * @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.
1192 * @param object $a Extra words and phrases that might be required in the error string
1193 * @param string $debuginfo optional debugging information
1194 */
1195 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1196 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1197 }
75ee207b
SH
1198}
1199
1200/**
1201 * This class is used to manage a bulk operations for enrolment plugins.
1202 *
1203 * @copyright 2011 Sam Hemelryk
1204 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1205 */
1206abstract class enrol_bulk_enrolment_operation {
1207
1208 /**
1209 * The course enrolment manager
1210 * @var course_enrolment_manager
1211 */
1212 protected $manager;
1213
1214 /**
1215 * The enrolment plugin to which this operation belongs
1216 * @var enrol_plugin
1217 */
1218 protected $plugin;
1219
1220 /**
1221 * Contructor
1222 * @param course_enrolment_manager $manager
1223 * @param stdClass $plugin
1224 */
1225 public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1226 $this->manager = $manager;
1227 $this->plugin = $plugin;
1228 }
1229
1230 /**
1231 * Returns a moodleform used for this operation, or false if no form is required and the action
1232 * should be immediatly processed.
1233 *
1234 * @param moodle_url|string $defaultaction
1235 * @param mixed $defaultcustomdata
1236 * @return enrol_bulk_enrolment_change_form|moodleform|false
1237 */
1238 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1239 return false;
1240 }
1241
1242 /**
1243 * Returns the title to use for this bulk operation
1244 *
1245 * @return string
1246 */
1247 abstract public function get_title();
1248
1249 /**
1250 * Returns the identifier for this bulk operation.
1251 * This should be the same identifier used by the plugins function when returning
1252 * all of its bulk operations.
1253 *
1254 * @return string
1255 */
1256 abstract public function get_identifier();
1257
1258 /**
1259 * Processes the bulk operation on the given users
1260 *
1261 * @param course_enrolment_manager $manager
1262 * @param array $users
1263 * @param stdClass $properties
1264 */
1265 abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);
a70eb30f 1266}