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
25 $previoussearch = ($searchtext != '') or ($previoussearch) ?
1:0;
27 $baseurl = 'assign.php?contextid='.$contextid;
28 if (!empty($userid)) {
29 $baseurl .= '&userid='.$userid;
31 if (!empty($courseid)) {
32 $baseurl .= '&courseid='.$courseid;
35 if (! $context = get_context_instance_by_id($contextid)) {
36 error("Context ID was incorrect (can't find it)");
40 if ($context->contextlevel
== CONTEXT_COURSE
) {
41 $courseid = $context->instanceid
;
42 if ($course = get_record('course', 'id', $courseid)) {
43 $inmeta = $course->metacourse
;
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
);
57 $course = clone($SITE);
60 require_login($course);
62 if ($context->contextlevel
== CONTEXT_COURSE
) {
63 require_login($context->instanceid
);
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');
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
115 if (!user_can_assign($context, $roleid)) {
116 error ('you can not override this role in this context');
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
) {
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&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, " ", navmenu($course));
142 $navlinks[] = array('name' => $fullname, 'link' => "$CFG->wwwroot/user/view.php?id=$userid&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, " ", navmenu($course));
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();
158 $tabsmode = 'assign';
159 include_once('tabs.php');
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
)) {
191 if (has_capability('moodle/course:managemetacourse', $context, $adduser)) {
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));
203 switch($extendbase) {
205 $timestart = $course->startdate
;
211 $timestart = $course->enrolstartdate
;
214 $timestart = $course->enrolenddate
;
218 if($extendperiod > 0) {
219 $timeend = $timestart +
$extendperiod;
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
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));
263 } else if ($showall) {
269 if ($context->contextlevel
==CONTEXT_COURSE
and $context->instanceid
== SITEID
) {
270 print_heading_with_help(get_string('frontpageroles', 'admin'), 'assignroles');
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
296 $FULLNAME = sql_fullname();
298 $selectsql = " AND ($FULLNAME $LIKE '%$searchtext%' OR email $LIKE '%$searchtext%') ";
299 $select .= $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) *
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
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
;
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)."
346 AND ra.roleid in $roleids";
347 $excsql = " AND u.id NOT IN (
349 FROM {$CFG->prefix}role_assignments r,
351 WHERE r.contextid = $contextid
353 AND r.roleid = $roleid
356 $availableusers = get_recordset_sql($select . $from . $where . $selectsql . $excsql);
359 $usercount = count_records_sql($countselect . $from . $where) - count($contextusers);
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
378 FROM '.$CFG->prefix
.'role_assignments r,
379 '.$CFG->prefix
.'user u
380 WHERE r.contextid = '.$contextid.'
382 AND r.roleid = '.$roleid.'
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&courseid=$courseid&contextid=$contextid&roleid=",
392 $assignableroles, 'switchrole', $roleid, '', '', '', false, 'self', $strroletoassign);
395 print_simple_box_start('center');
396 include('assign.html');
397 print_simple_box_end();
399 if (!empty($errors)) {
401 foreach ($errors as $e) {
405 print_simple_box_start('center');
407 print_simple_box_end();
410 } else { // Print overview table
412 // sync metacourse enrolments if needed
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.'&roleid='.$roleid.'">'.$rolename.'</a>',$description, $countusers);
434 print_footer($course);