MDL-23532 theme-base - added base styles for the changes to tne enrolment UI
[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)
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
169 LEFT JOIN {enrol} e ON e.id=ue.enrolid
170 WHERE e.courseid = :courseid
171 ) ue ON ue.userid=u.id
172 WHERE
173 ctx.id $ctxcondition AND
174 ue.id IS NULL";
175 $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
176 }
177 return $this->totalotherusers;
178 }
179
a70eb30f
SH
180 /**
181 * Gets all of the users enrolled in this course.
182 *
df4a889e 183 * If a filter was specified this will be the users who were enrolled
a70eb30f
SH
184 * in this course by means of that instance.
185 *
186 * @global moodle_database $DB
187 * @param string $sort
188 * @param string $direction ASC or DESC
189 * @param int $page First page should be 0
190 * @param int $perpage Defaults to 25
191 * @return array
192 */
193 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
194 global $DB;
195 if ($direction !== 'ASC') {
196 $direction = 'DESC';
197 }
198 $key = md5("$sort-$direction-$page-$perpage");
199 if (!array_key_exists($key, $this->users)) {
200 list($instancessql, $params, $filter) = $this->get_instance_sql();
df4a889e
PS
201 $ufields = user_picture::fields('u', array('lastaccess', 'email'));
202 $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
a70eb30f
SH
203 FROM {user} u
204 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
205 JOIN {enrol} e ON (e.id = ue.enrolid)
206 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
207 if ($sort === 'firstname') {
208 $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
209 } else if ($sort === 'lastname') {
210 $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
211 } else if ($sort === 'email') {
212 $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
213 } else if ($sort === 'lastseen') {
214 $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
215 }
216 $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
217 }
218 return $this->users[$key];
219 }
220
6db3eee0
SH
221 /**
222 * Gets and array of other users.
223 *
224 * Other users are users who have been assigned roles or inherited roles
225 * within this course but who have not been enrolled in the course
226 *
227 * @global moodle_database $DB
228 * @param string $sort
229 * @param string $direction
230 * @param int $page
231 * @param int $perpage
232 * @return array
233 */
234 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
235 global $DB;
236 if ($direction !== 'ASC') {
237 $direction = 'DESC';
238 }
239 $key = md5("$sort-$direction-$page-$perpage");
240 if (!array_key_exists($key, $this->otherusers)) {
cf717dc2 241 list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx');
6db3eee0
SH
242 $params['courseid'] = $this->course->id;
243 $params['cid'] = $this->course->id;
244 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
245 FROM {role_assignments} ra
246 JOIN {user} u ON u.id = ra.userid
247 JOIN {context} ctx ON ra.contextid = ctx.id
248 LEFT JOIN (
249 SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
250 FROM {user_enrolments} ue
251 LEFT JOIN {enrol} e ON e.id=ue.enrolid
252 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
253 WHERE e.courseid = :courseid
254 ) ue ON ue.userid=u.id
255 WHERE
256 ctx.id $ctxcondition AND
257 ue.id IS NULL
258 ORDER BY u.$sort $direction, ctx.depth DESC";
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
354 AND u.id NOT IN (
355 SELECT u.id
356 FROM {role_assignments} r, {user} u
357 WHERE r.contextid = :contextid
358 AND u.id = r.userid)";
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 */
820 public function get_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
821 $users = $this->get_users($sort, $direction, $page, $perpage);
822
823 $now = time();
824 $strnever = get_string('never');
825 $straddgroup = get_string('addgroup', 'group');
826 $strunenrol = get_string('unenrol', 'enrol');
827 $stredit = get_string('edit');
828
829 $iconedit = $renderer->pix_url('t/edit');
830 $iconenroladd = $renderer->pix_url('t/enroladd');
831 $iconenrolremove = $renderer->pix_url('t/delete');
832
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());
841
842 $userdetails = array();
843 foreach ($users as $user) {
844 $details = array(
845 'userid' => $user->id,
846 'courseid' => $courseid,
847 'picture' => new user_picture($user),
848 'firstname' => fullname($user, true),
849 'email' => $user->email,
850 'lastseen' => $strnever,
851 'roles' => array(),
852 'groups' => array(),
853 'enrolments' => array()
854 );
855
6db3eee0
SH
856 if ($user->lastaccess) {
857 $details['lastseen'] = format_time($now - $user->lastaccess);
a70eb30f
SH
858 }
859
860 // Roles
861 foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
862 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>(!$rassignable || !isset($assignable[$rid])));
863 }
864
865 // Users
866 $usergroups = $this->get_user_groups($user->id);
867 foreach($usergroups as $gid=>$unused) {
868 $details['groups'][$gid] = $allgroups[$gid]->name;
869 }
870
871 // Enrolments
872 foreach ($this->get_user_enrolments($user->id) as $ue) {
873 if ($ue->timestart and $ue->timeend) {
874 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
875 $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend);
876 } else if ($ue->timestart) {
877 $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
878 $periodoutside = ($ue->timestart && $now < $ue->timestart);
879 } else if ($ue->timeend) {
880 $period = get_string('periodend', 'enrol', userdate($ue->timeend));
881 $periodoutside = ($ue->timeend && $now > $ue->timeend);
882 } else {
883 $period = '';
884 $periodoutside = false;
885 }
886 $details['enrolments'][$ue->id] = array(
887 'text' => $ue->enrolmentinstancename,
888 'period' => $period,
889 'dimmed' => ($periodoutside || $ue->status != ENROL_USER_ACTIVE),
890 'canunenrol' => ($ue->enrolmentplugin->allow_unenrol($ue->enrolmentinstance) && has_capability("enrol/".$ue->enrolmentinstance->enrol.":unenrol", $context)),
891 'canmanage' => ($ue->enrolmentplugin->allow_manage($ue->enrolmentinstance) && has_capability("enrol/".$ue->enrolmentinstance->enrol.":manage", $context))
892 );
893 }
894 $userdetails[$user->id] = $details;
895 }
896 return $userdetails;
a70eb30f 897 }
b69ca6be
SH
898
899 public function get_manual_enrol_buttons() {
900 $plugins = $this->get_enrolment_plugins();
901 $buttons = array();
902 foreach ($plugins as $plugin) {
903 $newbutton = $plugin->get_manual_enrol_button($this);
904 if (is_array($newbutton)) {
905 $buttons += $newbutton;
906 } else if ($newbutton instanceof enrol_user_button) {
907 $buttons[] = $newbutton;
908 }
909 }
910 return $buttons;
911 }
912
913 public function has_instance($enrolpluginname) {
914 // Make sure manual enrolments instance exists
915 foreach ($this->get_enrolment_instances() as $instance) {
916 if ($instance->enrol == $enrolpluginname) {
917 return true;
918 }
919 }
920 return false;
921 }
922}
923
924/**
925 * A button that is used to enrol users in a course
926 *
927 * @copyright 2010 Sam Hemelryk
928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
929 */
930class enrol_user_button extends single_button {
931
932 /**
933 * An array containing JS YUI modules required by this button
934 * @var array
935 */
936 protected $jsyuimodules = array();
937
938 /**
939 * An array containing JS initialisation calls required by this button
940 * @var array
941 */
942 protected $jsinitcalls = array();
943
944 /**
945 * An array strings required by JS for this button
946 * @var array
947 */
948 protected $jsstrings = array();
949
950 /**
951 * Initialises the new enrol_user_button
952 *
953 * @staticvar int $count The number of enrol user buttons already created
954 * @param moodle_url $url
955 * @param string $label The text to display in the button
956 * @param string $method Either post or get
957 */
958 public function __construct(moodle_url $url, $label, $method = 'post') {
959 static $count = 0;
960 $count ++;
961 parent::__construct($url, $label, $method);
962 $this->class = 'singlebutton enrolusersbutton';
963 $this->formid = 'enrolusersbutton-'.$count;
964 }
965
966 /**
967 * Adds a YUI module call that will be added to the page when the button is used.
968 *
969 * @param string|array $modules One or more modules to require
970 * @param string $function The JS function to call
971 * @param array $arguments An array of arguments to pass to the function
972 * @param string $galleryversion The YUI gallery version of any modules required
973 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
974 */
975 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) {
976 $js = new stdClass;
977 $js->modules = (array)$modules;
978 $js->function = $function;
979 $js->arguments = $arguments;
980 $js->galleryversion = $galleryversion;
981 $js->ondomready = $ondomready;
982 $this->jsyuimodules[] = $js;
983 }
984
985 /**
986 * Adds a JS initialisation call to the page when the button is used.
987 *
988 * @param string $function The function to call
989 * @param array $extraarguments An array of arguments to pass to the function
990 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
991 * @param array $module A module definition
992 */
993 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
994 $js = new stdClass;
995 $js->function = $function;
996 $js->extraarguments = $extraarguments;
997 $js->ondomready = $ondomready;
998 $js->module = $module;
999 $this->jsinitcalls[] = $js;
1000 }
1001
1002 /**
1003 * Requires strings for JS that will be loaded when the button is used.
1004 *
1005 * @param type $identifiers
1006 * @param string $component
1007 * @param mixed $a
1008 */
1009 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1010 $string = new stdClass;
1011 $string->identifiers = (array)$identifiers;
1012 $string->component = $component;
1013 $string->a = $a;
1014 $this->jsstrings[] = $string;
1015 }
1016
1017 /**
1018 * Initialises the JS that is required by this button
1019 *
1020 * @param moodle_page $page
1021 */
1022 public function initialise_js(moodle_page $page) {
1023 foreach ($this->jsyuimodules as $js) {
1024 $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready);
1025 }
1026 foreach ($this->jsinitcalls as $js) {
1027 $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1028 }
1029 foreach ($this->jsstrings as $string) {
1030 $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1031 }
1032 }
6db3eee0
SH
1033}
1034
1035class enrol_ajax_exception extends moodle_exception {
1036 /**
1037 * Constructor
1038 * @param string $errorcode The name of the string from error.php to print
1039 * @param string $module name of module
1040 * @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.
1041 * @param object $a Extra words and phrases that might be required in the error string
1042 * @param string $debuginfo optional debugging information
1043 */
1044 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1045 parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1046 }
a70eb30f 1047}