minor fix for count of users
[moodle-pu.git] / admin / roles / assign.php
blob417d878b99f965c02e7ce3df7310d1317e138d1e
1 <?php // $Id$
2 // Script to assign users to contexts
4 require_once('../../config.php');
5 require_once($CFG->dirroot.'/mod/forum/lib.php');
6 require_once($CFG->libdir.'/adminlib.php');
8 define("MAX_USERS_PER_PAGE", 5000);
10 $contextid = required_param('contextid',PARAM_INT); // context id
11 $roleid = optional_param('roleid', 0, PARAM_INT); // required role id
12 $add = optional_param('add', 0, PARAM_BOOL);
13 $remove = optional_param('remove', 0, PARAM_BOOL);
14 $showall = optional_param('showall', 0, PARAM_BOOL);
15 $searchtext = optional_param('searchtext', '', PARAM_RAW); // search string
16 $previoussearch = optional_param('previoussearch', 0, PARAM_BOOL);
17 $hidden = optional_param('hidden', 0, PARAM_BOOL); // whether this assignment is hidden
18 $extendperiod = optional_param('extendperiod', 0, PARAM_INT);
19 $extendbase = optional_param('extendbase', 0, PARAM_INT);
20 $userid = optional_param('userid', 0, PARAM_INT); // needed for user tabs
21 $courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs
23 $errors = array();
25 $previoussearch = ($searchtext != '') or ($previoussearch) ? 1:0;
27 $baseurl = 'assign.php?contextid='.$contextid;
28 if (!empty($userid)) {
29 $baseurl .= '&amp;userid='.$userid;
31 if (!empty($courseid)) {
32 $baseurl .= '&amp;courseid='.$courseid;
35 if (! $context = get_context_instance_by_id($contextid)) {
36 error("Context ID was incorrect (can't find it)");
39 $inmeta = 0;
40 if ($context->contextlevel == CONTEXT_COURSE) {
41 $courseid = $context->instanceid;
42 if ($course = get_record('course', 'id', $courseid)) {
43 $inmeta = $course->metacourse;
44 } else {
45 error('Invalid course id');
47 $coursecontext = $context;
49 } else if (!empty($courseid)){ // we need this for user tabs in user context
50 if (!$course = get_record('course', 'id', $courseid)) {
51 error('Invalid course id');
53 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
55 } else {
56 $courseid = SITEID;
57 $course = clone($SITE);
60 require_login($course);
62 if ($context->contextlevel == CONTEXT_COURSE) {
63 require_login($context->instanceid);
64 } else {
65 require_login();
68 require_capability('moodle/role:assign', $context);
70 /// needed for tabs.php
71 $overridableroles = get_overridable_roles($context);
72 $assignableroles = get_assignable_roles($context); // Plain role names, may be altered later
75 /// Get some language strings
77 $strassignusers = get_string('assignusers', 'role');
78 $strpotentialusers = get_string('potentialusers', 'role');
79 $strexistingusers = get_string('existingusers', 'role');
80 $straction = get_string('assignroles', 'role');
81 $strroletoassign = get_string('roletoassign', 'role');
82 $strcurrentcontext = get_string('currentcontext', 'role');
83 $strsearch = get_string('search');
84 $strshowall = get_string('showall');
85 $strparticipants = get_string('participants');
86 $strsearchresults = get_string('searchresults');
88 $unlimitedperiod = get_string('unlimited');
89 $defaultperiod = $course->enrolperiod;
90 for ($i=1; $i<=365; $i++) {
91 $seconds = $i * 86400;
92 $periodmenu[$seconds] = get_string('numdays', '', $i);
95 $timeformat = get_string('strftimedate');
96 $today = time();
97 $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
99 $basemenu[0] = get_string('startdate') . ' (' . userdate($course->startdate, $timeformat) . ')';
100 if ($course->enrollable != 2 || ($course->enrolstartdate == 0 || $course->enrolstartdate <= $today) && ($course->enrolenddate == 0 || $course->enrolenddate > $today)) {
101 $basemenu[3] = get_string('today') . ' (' . userdate($today, $timeformat) . ')' ;
103 if($course->enrollable == 2) {
104 if($course->enrolstartdate > 0) {
105 $basemenu[4] = get_string('courseenrolstartdate') . ' (' . userdate($course->enrolstartdate, $timeformat) . ')';
107 if($course->enrolenddate > 0) {
108 $basemenu[5] = get_string('courseenrolenddate') . ' (' . userdate($course->enrolenddate, $timeformat) . ')';
112 /// Make sure this user can assign that role
114 if ($roleid) {
115 if (!user_can_assign($context, $roleid)) {
116 error ('you can not override this role in this context');
120 if ($userid) {
121 $user = get_record('user', 'id', $userid);
122 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
126 /// Print the header and tabs
128 if ($context->contextlevel == CONTEXT_USER) {
129 /// course header
130 $navlinks = array();
131 if ($courseid != SITEID) {
132 $navlinks[] = array('name' => $course->shortname, 'link' => "$CFG->wwwroot/course/view.php?id=$course->id", 'type' => 'course');
133 $navlinks[] = array('name' => $strparticipants, 'link' => "$CFG->wwwroot/user/index.php?id=$course->id", 'type' => 'misc');
134 $navlinks[] = array('name' => $fullname, 'link' => "$CFG->wwwroot/user/view.php?id=$userid&amp;course=$courseid", 'type' => 'misc');
135 $navlinks[] = array('name' => $straction, 'link' => null, 'type' => 'misc');
136 $navigation = build_navigation($navlinks);
138 print_header("$fullname", "$fullname", $navigation, "", "", true, "&nbsp;", navmenu($course));
140 /// site header
141 } else {
142 $navlinks[] = array('name' => $fullname, 'link' => "$CFG->wwwroot/user/view.php?id=$userid&amp;course=$courseid", 'type' => 'misc');
143 $navlinks[] = array('name' => $straction, 'link' => null, 'type' => 'misc');
144 $navigation = build_navigation($navlinks);
145 print_header("$course->fullname: $fullname", $course->fullname, $navigation, "", "", true, "&nbsp;", navmenu($course));
148 $showroles = 1;
149 $currenttab = 'assign';
150 include_once($CFG->dirroot.'/user/tabs.php');
151 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
152 admin_externalpage_setup('assignroles');
153 admin_externalpage_print_header();
154 } else if ($context->contextlevel==CONTEXT_COURSE and $context->instanceid == SITEID) {
155 admin_externalpage_setup('frontpageroles');
156 admin_externalpage_print_header();
157 $currenttab = '';
158 $tabsmode = 'assign';
159 include_once('tabs.php');
160 } else {
161 $currenttab = '';
162 $tabsmode = 'assign';
163 include_once('tabs.php');
167 /// Rename some of the role names if needed
168 if (isset($coursecontext)) {
169 if ($aliasnames = get_records('role_names', 'contextid', $coursecontext->id)) {
170 foreach ($aliasnames as $alias) {
171 if (isset($assignableroles[$alias->roleid])) {
172 $assignableroles[$alias->roleid] = $alias->text.' ('.$assignableroles[$alias->roleid].')';
179 /// Process incoming role assignment
181 if ($frm = data_submitted()) {
183 if ($add and !empty($frm->addselect) and confirm_sesskey()) {
185 foreach ($frm->addselect as $adduser) {
186 if (!$adduser = clean_param($adduser, PARAM_INT)) {
187 continue;
189 $allow = true;
190 if ($inmeta) {
191 if (has_capability('moodle/course:managemetacourse', $context, $adduser)) {
192 //ok
193 } else {
194 $managerroles = get_roles_with_capability('moodle/course:managemetacourse', CAP_ALLOW, $context);
195 if (!empty($managerroles) and !array_key_exists($roleid, $managerroles)) {
196 $erruser = get_record('user', 'id', $adduser, '','','','', 'id, firstname, lastname');
197 $errors[] = get_string('metaassignerror', 'role', fullname($erruser));
198 $allow = false;
202 if ($allow) {
203 switch($extendbase) {
204 case 0:
205 $timestart = $course->startdate;
206 break;
207 case 3:
208 $timestart = $today;
209 break;
210 case 4:
211 $timestart = $course->enrolstartdate;
212 break;
213 case 5:
214 $timestart = $course->enrolenddate;
215 break;
218 if($extendperiod > 0) {
219 $timeend = $timestart + $extendperiod;
220 } else {
221 $timeend = 0;
223 if (! role_assign($roleid, $adduser, 0, $context->id, $timestart, $timeend, $hidden)) {
224 $errors[] = "Could not add user with id $adduser to this role!";
229 } else if ($remove and !empty($frm->removeselect) and confirm_sesskey()) {
231 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
232 $topleveladmin = false;
234 // we only worry about this if the role has doanything capability at site level
235 if ($context->id == $sitecontext->id && $adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext)) {
236 foreach ($adminroles as $adminrole) {
237 if ($adminrole->id == $roleid) {
238 $topleveladmin = true;
243 foreach ($frm->removeselect as $removeuser) {
244 $removeuser = clean_param($removeuser, PARAM_INT);
246 if ($topleveladmin && ($removeuser == $USER->id)) { // Prevent unassigning oneself from being admin
247 continue;
250 if (! role_unassign($roleid, $removeuser, 0, $context->id)) {
251 $errors[] = "Could not remove user with id $removeuser from this role!";
252 } else if ($inmeta) {
253 sync_metacourse($courseid);
254 $newroles = get_user_roles($context, $removeuser, false);
255 if (!empty($newroles) and !array_key_exists($roleid, $newroles)) {
256 $erruser = get_record('user', 'id', $removeuser, '','','','', 'id, firstname, lastname');
257 $errors[] = get_string('metaunassignerror', 'role', fullname($erruser));
258 $allow = false;
263 } else if ($showall) {
264 $searchtext = '';
265 $previoussearch = 0;
269 if ($context->contextlevel==CONTEXT_COURSE and $context->instanceid == SITEID) {
270 print_heading_with_help(get_string('frontpageroles', 'admin'), 'assignroles');
271 } else {
272 print_heading_with_help(get_string('assignroles', 'role'), 'assignroles');
275 if ($context->contextlevel==CONTEXT_SYSTEM) {
276 print_box(get_string('globalroleswarning', 'role'));
279 if ($roleid) { /// prints a form to swap roles
281 /// Get all existing participants in this context.
282 // Why is this not done with get_users???
284 if (!$contextusers = get_role_users($roleid, $context, false, 'u.id, u.firstname, u.lastname, u.email, r.hidden')) {
285 $contextusers = array();
288 $select = "username <> 'guest' AND deleted = 0 AND confirmed = 1";
290 $usercount = count_records_select('user', $select) - count($contextusers);
292 $searchtext = trim($searchtext);
294 if ($searchtext !== '') { // Search for a subset of remaining users
295 $LIKE = sql_ilike();
296 $FULLNAME = sql_fullname();
298 $selectsql = " AND ($FULLNAME $LIKE '%$searchtext%' OR email $LIKE '%$searchtext%') ";
299 $select .= $selectsql;
300 } else {
301 $selectsql = "";
304 if ($context->contextlevel > CONTEXT_COURSE) { // mod or block (or group?)
306 /************************************************************************
308 * context level is above or equal course context level *
309 * in this case we pull out all users matching search criteria (if any) *
311 * MDL-11324 *
312 * a mini get_users_by_capability() call here, this is done instead of *
313 * get_users_by_capability() because *
314 * 1) get_users_by_capability() does not deal with searching by name *
315 * 2) exceptions array can be potentially large for large courses *
316 * 3) get_recordset_sql() is more efficient *
318 ************************************************************************/
320 if ($possibleroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW, $context)) {
322 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM));
324 $validroleids = array();
325 foreach ($possibleroles as $possiblerole) {
326 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
327 continue;
329 if ($caps = role_context_capabilities($possiblerole->id, $context, 'moodle/course:view')) { // resolved list
330 if (isset($caps['moodle/course:view']) && $caps['moodle/course:view'] > 0) { // resolved capability > 0
331 $validroleids[] = $possiblerole->id;
336 if ($validroleids) {
337 $roleids = '('.implode(',', $validroleids).')';
339 $select = " SELECT u.id, u.firstname, u.lastname, u.email";
340 $countselect = "SELECT COUNT(u.id)";
341 $from = " FROM {$CFG->prefix}user u
342 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
343 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid";
344 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
345 AND u.deleted = 0
346 AND ra.roleid in $roleids";
347 $excsql = " AND u.id NOT IN (
348 SELECT u.id
349 FROM {$CFG->prefix}role_assignments r,
350 {$CFG->prefix}user u
351 WHERE r.contextid = $contextid
352 AND u.id = r.userid
353 AND r.roleid = $roleid
354 $selectsql)";
356 $availableusers = get_recordset_sql($select . $from . $where . $selectsql . $excsql);
359 $usercount = count_records_sql($countselect . $from . $where) - count($contextusers);
362 } else {
364 /************************************************************************
366 * context level is above or equal course context level *
367 * in this case we pull out all users matching search criteria (if any) *
369 ************************************************************************/
371 /// MDL-11111 do not include user already assigned this role in this context as available users
372 /// so that the number of available users is right and we save time looping later
373 $availableusers = get_recordset_sql('SELECT id, firstname, lastname, email
374 FROM '.$CFG->prefix.'user
375 WHERE '.$select.'
376 AND id NOT IN (
377 SELECT u.id
378 FROM '.$CFG->prefix.'role_assignments r,
379 '.$CFG->prefix.'user u
380 WHERE r.contextid = '.$contextid.'
381 AND u.id = r.userid
382 AND r.roleid = '.$roleid.'
383 '.$selectsql.')
384 ORDER BY lastname ASC, firstname ASC');
385 $usercount = count_records_select('user', $select) - count($contextusers);
389 echo '<div style="text-align:center">'.$strcurrentcontext.': '.print_context_name($context).'<br/>';
390 $assignableroles = array('0'=>get_string('listallroles', 'role').'...') + $assignableroles;
391 popup_form("$CFG->wwwroot/$CFG->admin/roles/assign.php?userid=$userid&amp;courseid=$courseid&amp;contextid=$contextid&amp;roleid=",
392 $assignableroles, 'switchrole', $roleid, '', '', '', false, 'self', $strroletoassign);
393 echo '</div>';
395 print_simple_box_start('center');
396 include('assign.html');
397 print_simple_box_end();
399 if (!empty($errors)) {
400 $msg = '<p>';
401 foreach ($errors as $e) {
402 $msg .= $e.'<br />';
404 $msg .= '</p>';
405 print_simple_box_start('center');
406 notify($msg);
407 print_simple_box_end();
410 } else { // Print overview table
412 // sync metacourse enrolments if needed
413 if ($inmeta) {
414 sync_metacourse($course);
417 $table->tablealign = 'center';
418 $table->cellpadding = 5;
419 $table->cellspacing = 0;
420 $table->width = '60%';
421 $table->head = array(get_string('roles', 'role'), get_string('description'), get_string('users'));
422 $table->wrap = array('nowrap', '', 'nowrap');
423 $table->align = array('right', 'left', 'center');
425 foreach ($assignableroles as $roleid => $rolename) {
426 $countusers = count_role_users($roleid, $context);
427 $description = format_string(get_field('role', 'description', 'id', $roleid));
428 $table->data[] = array('<a href="'.$baseurl.'&amp;roleid='.$roleid.'">'.$rolename.'</a>',$description, $countusers);
431 print_table($table);
434 print_footer($course);