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