3 // Lists all the users within a given course
5 require_once('../config.php');
6 require_once($CFG->libdir
.'/tablelib.php');
8 define('USER_SMALL_CLASS', 20); // Below this is considered small
9 define('USER_LARGE_CLASS', 200); // Above this is considered large
10 define('DEFAULT_PAGE_SIZE', 20);
11 define('SHOW_ALL_PAGE_SIZE', 5000);
13 $group = optional_param('group', -1, PARAM_INT
); // Group to show
14 $page = optional_param('page', 0, PARAM_INT
); // which page to show
15 $perpage = optional_param('perpage', DEFAULT_PAGE_SIZE
, PARAM_INT
); // how many per page
16 $mode = optional_param('mode', NULL); // '0' for less details, '1' for more
17 $accesssince = optional_param('accesssince',0,PARAM_INT
); // filter by last access. -1 = never
18 $search = optional_param('search','',PARAM_CLEAN
);
19 $roleid = optional_param('roleid', 0, PARAM_INT
); // optional roleid
21 $contextid = optional_param('contextid', 0, PARAM_INT
); // one of this or
22 $courseid = optional_param('id', 0, PARAM_INT
); // this are required
25 if (! $context = get_context_instance_by_id($contextid)) {
26 error("Context ID is incorrect");
28 if (! $course = get_record('course', 'id', $context->instanceid
)) {
29 error("Course ID is incorrect");
32 if (! $course = get_record('course', 'id', $courseid)) {
33 error("Course ID is incorrect");
35 if (! $context = get_context_instance(CONTEXT_COURSE
, $course->id
)) {
36 error("Context ID is incorrect");
43 require_login($course);
45 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
47 if (!has_capability('moodle/course:viewparticipants', $context)) {
48 print_error('nopermissions');
52 $avoidroles = array();
54 if ($roles = get_roles_used_in_context($context, true)) {
55 // We should ONLY allow roles with moodle/course:view because otherwise we get little niggly issues
57 // We should further exclude "admin" users (those with "doanything" at site level) because
58 // Otherwise they appear in every participant list
60 $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW
, $context);
61 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
63 foreach ($roles as $role) {
64 if (!isset($canviewroles[$role->id
])) { // Avoid this role (eg course creator)
65 $avoidroles[] = $role->id
;
66 unset($roles[$role->id
]);
69 if (isset($doanythingroles[$role->id
])) { // Avoid this role (ie admin)
70 $avoidroles[] = $role->id
;
71 unset($roles[$role->id
]);
74 $rolenames[$role->id
] = strip_tags(role_get_name($role, $context)); // Used in menus etc later on
78 // no roles to display yet?
79 if (empty($rolenames)) {
80 if (has_capability('moodle/role:assign', $context)) {
81 redirect($CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?contextid='.$context->id
);
83 error ('No participants found for this course');
87 add_to_log($course->id
, 'user', 'view all', 'index.php?id='.$course->id
, '');
89 $bulkoperations = has_capability('moodle/course:bulkmessaging', $context);
91 $countries = get_list_of_countries();
93 $strnever = get_string('never');
95 $datestring->year
= get_string('year');
96 $datestring->years
= get_string('years');
97 $datestring->day
= get_string('day');
98 $datestring->days
= get_string('days');
99 $datestring->hour
= get_string('hour');
100 $datestring->hours
= get_string('hours');
101 $datestring->min
= get_string('min');
102 $datestring->mins
= get_string('mins');
103 $datestring->sec
= get_string('sec');
104 $datestring->secs
= get_string('secs');
106 if ($mode !== NULL) {
107 $SESSION->userindexmode
= $fullmode = ($mode == 1);
108 } else if (isset($SESSION->userindexmode
)) {
109 $fullmode = $SESSION->userindexmode
;
114 /// Check to see if groups are being used in this forum
115 /// and if so, set $currentgroup to reflect the current group
117 $groupmode = groupmode($course); // Groups are being used
118 $currentgroup = get_and_set_current_group($course, $groupmode, $group);
120 if (!$currentgroup) { // To make some other functions work better later
121 $currentgroup = NULL;
124 $isseparategroups = ($course->groupmode
== SEPARATEGROUPS
and $course->groupmodeforce
and
125 !has_capability('moodle/site:accessallgroups', $context));
127 if ($isseparategroups and (!$currentgroup) ) {
129 $navlinks[] = array('name' => get_string('participants'), 'link' => null, 'type' => 'misc');
130 $navigation = build_navigation($navlinks);
132 print_header("$course->shortname: ".get_string('participants'), $course->fullname
, $navigation, "", "", true, " ", navmenu($course));
133 print_heading(get_string("notingroup", "forum"));
134 print_footer($course);
138 // Should use this variable so that we don't break stuff every time a variable is added or changed.
139 $baseurl = $CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'&id='.$course->id
.'&group='.$currentgroup.'&perpage='.$perpage.'&accesssince='.$accesssince.'&search='.s($search);
144 $navlinks[] = array('name' => get_string('participants'), 'link' => null, 'type' => 'misc');
145 $navigation = build_navigation($navlinks);
147 print_header("$course->shortname: ".get_string('participants'), $course->fullname
, $navigation, "", "", true, " ", navmenu($course));
150 if ($course->id
== SITEID
) {
151 $filtertype = 'site';
152 } else if ($course->id
&& !$currentgroup) {
153 $filtertype = 'course';
154 $filterselect = $course->id
;
156 $filtertype = 'group';
157 $filterselect = $currentgroup;
159 $currenttab = 'participants';
162 require_once($CFG->dirroot
.'/user/tabs.php');
165 /// Get the hidden field list
166 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
167 $hiddenfields = array(); // teachers and admins are allowed to see everything
169 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
173 /// Print settings and things in a table across the top
175 echo '<table class="controls" cellspacing="0"><tr>';
177 /// Print my course menus
178 if ($mycourses = get_my_courses($USER->id
)) {
179 echo '<td class="left">';
180 $courselist = array();
181 foreach ($mycourses as $mycourse) {
182 $courselist[$mycourse->id
] = format_string($mycourse->shortname
);
184 popup_form($CFG->wwwroot
.'/user/index.php?roleid='.$roleid.'&sifirst=&silast=&id=',
185 $courselist, 'courseform', $course->id
, '', '', '', false, 'self', get_string('mycourses'));
189 echo '<td class="left">';
190 setup_and_print_groups($course, $groupmode, $baseurl);
193 // get minimum lastaccess for this course and display a dropbox to filter by lastaccess going back this far.
194 // this might not work anymore because you always going to get yourself as the most recent entry? added $USER!=$user ch
195 $minlastaccess = get_field_sql('SELECT min(timeaccess) FROM '.$CFG->prefix
.'user_lastaccess WHERE courseid = '.$course->id
.' AND timeaccess != 0 AND userid!='.$USER->id
);
196 $lastaccess0exists = record_exists('user_lastaccess','courseid',$course->id
,'timeaccess',0);
197 $now = usergetmidnight(time());
198 $timeaccess = array();
200 // makes sense for this to go first.
201 $timeoptions[0] = get_string('selectperiod');
204 for ($i = 1; $i < 7; $i++
) {
205 if (strtotime('-'.$i.' days',$now) >= $minlastaccess) {
206 $timeoptions[strtotime('-'.$i.' days',$now)] = get_string('numdays','moodle',$i);
210 for ($i = 1; $i < 10; $i++
) {
211 if (strtotime('-'.$i.' weeks',$now) >= $minlastaccess) {
212 $timeoptions[strtotime('-'.$i.' weeks',$now)] = get_string('numweeks','moodle',$i);
216 for ($i = 2; $i < 12; $i++
) {
217 if (strtotime('-'.$i.' months',$now) >= $minlastaccess) {
218 $timeoptions[strtotime('-'.$i.' months',$now)] = get_string('nummonths','moodle',$i);
222 if (strtotime('-1 year',$now) >= $minlastaccess) {
223 $timeoptions[strtotime('-1 year',$now)] = get_string('lastyear');
226 if (!empty($lastaccess0exists)) {
227 $timeoptions[-1] = get_string('never');
230 if (count($timeoptions) > 1) {
231 echo '<td class="left">';
232 $baseurl = preg_replace('/&accesssince='.$accesssince.'/','',$baseurl);
233 popup_form($baseurl.'&accesssince=',$timeoptions,'timeoptions',$accesssince, '', '', '', false, 'self', get_string('usersnoaccesssince'));
238 echo '<td class="right">';
239 $formatmenu = array( '0' => get_string('detailedless'),
240 '1' => get_string('detailedmore'));
241 popup_form($baseurl.'&mode=', $formatmenu, 'formatmenu', $fullmode, '', '', '', false, 'self', get_string('userlist'));
242 echo '</td></tr></table>';
244 if ($currentgroup and (!$isseparategroups or has_capability('moodle/site:accessallgroups', $context))) { /// Display info about the group
245 if ($group = groups_get_group($currentgroup)) { //TODO:
246 if (!empty($group->description
) or (!empty($group->picture
) and empty($group->hidepicture
))) {
247 echo '<table class="groupinfobox"><tr><td class="left side picture">';
248 print_group_picture($group, $course->id
, true, false, false);
249 echo '</td><td class="content">';
250 echo '<h3>'.$group->name
;
251 if (has_capability('moodle/course:managegroups', $context)) {
252 echo ' <a title="'.get_string('editgroupprofile').'" href="'.$CFG->wwwroot
.'/group/group.php?id='.$group->id
.'&courseid='.$group->courseid
.'">';
253 echo '<img src="'.$CFG->pixpath
.'/t/edit.gif" alt="'.get_string('editgroupprofile').'" />';
257 echo format_text($group->description
);
258 echo '</td></tr></table>';
264 /// Define a table showing a list of users in the current role selection
266 $tablecolumns = array('userpic', 'fullname');
267 $tableheaders = array(get_string('userpic'), get_string('fullname'));
268 if (!isset($hiddenfields['city'])) {
269 $tablecolumns[] = 'city';
270 $tableheaders[] = get_string('city');
272 if (!isset($hiddenfields['country'])) {
273 $tablecolumns[] = 'country';
274 $tableheaders[] = get_string('country');
276 if (!isset($hiddenfields['lastaccess'])) {
277 $tablecolumns[] = 'lastaccess';
278 $tableheaders[] = get_string('lastaccess');
281 if ($course->enrolperiod
) {
282 $tablecolumns[] = 'timeend';
283 $tableheaders[] = get_string('enrolmentend');
286 if ($bulkoperations) {
287 $tablecolumns[] = '';
288 $tableheaders[] = get_string('select');
291 $table = new flexible_table('user-index-participants-'.$course->id
);
293 $table->define_columns($tablecolumns);
294 $table->define_headers($tableheaders);
295 $table->define_baseurl($baseurl);
297 $table->sortable(true, 'lastaccess', SORT_DESC
);
299 $table->set_attribute('cellspacing', '0');
300 $table->set_attribute('id', 'participants');
301 $table->set_attribute('class', 'generaltable generalbox');
303 $table->set_control_variables(array(
304 TABLE_VAR_SORT
=> 'ssort',
305 TABLE_VAR_HIDE
=> 'shide',
306 TABLE_VAR_SHOW
=> 'sshow',
307 TABLE_VAR_IFIRST
=> 'sifirst',
308 TABLE_VAR_ILAST
=> 'silast',
309 TABLE_VAR_PAGE
=> 'spage'
314 // we are looking for all users with this role assigned in this context or higher
315 if ($usercontexts = get_parent_contexts($context)) {
316 $listofcontexts = '('.implode(',', $usercontexts).')';
318 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
321 $selectrole = " AND r.roleid = $roleid ";
325 $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.email, u.city, u.country, u.picture, u.lang, u.timezone, u.emailstop, u.maildisplay, ul.timeaccess AS lastaccess, r.hidden '; // s.lastaccess
326 $select .= $course->enrolperiod?
', r.timeend ':'';
328 $from = "FROM {$CFG->prefix}user u INNER JOIN
329 {$CFG->prefix}role_assignments r on u.id=r.userid LEFT OUTER JOIN
330 {$CFG->prefix}user_lastaccess ul on (r.userid=ul.userid and ul.courseid = $course->id)";
332 $hiddensql = has_capability('moodle/role:viewhiddenassigns', $context)?
'':' AND r.hidden = 0 ';
334 // exclude users with roles we are avoiding
336 $adminroles = 'AND r.roleid NOT IN (';
337 $adminroles .= implode(',', $avoidroles);
343 // join on 2 conditions
344 // otherwise we run into the problem of having records in ul table, but not relevant course
345 // and user record is not pulled out
346 $where = "WHERE (r.contextid = $context->id OR r.contextid in $listofcontexts)
347 AND u.deleted = 0 $selectrole
348 AND (ul.courseid = $course->id OR ul.courseid IS NULL)
349 AND u.username != 'guest'
352 $where .= get_lastaccess_sql($accesssince);
356 if (!empty($search)) {
358 $fullname = sql_fullname('u.firstname','u.lastname');
359 $wheresearch .= ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\' OR idnumber '.$LIKE.' \'%'.$search.'%\') ';
363 if ($currentgroup) { // Displaying a group by choice
364 // FIX: TODO: This will not work if $currentgroup == 0, i.e. "those not in a group"
365 $from .= 'LEFT JOIN '.$CFG->prefix
.'groups_members gm ON u.id = gm.userid ';
366 $where .= ' AND gm.groupid = '.$currentgroup;
369 $totalcount = count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where); // Each user could have > 1 role
371 if ($table->get_sql_where()) {
372 $where .= ' AND '.$table->get_sql_where();
375 if ($table->get_sql_sort()) {
376 $sort = ' ORDER BY '.$table->get_sql_sort();
381 $matchcount = count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where.$wheresearch);
383 $table->initialbars($totalcount > $perpage);
384 $table->pagesize($perpage, $matchcount);
386 $userlist = get_records_sql($select.$from.$where.$wheresearch.$sort,
387 $table->get_page_start(), $table->get_page_size());
389 /// If there are multiple Roles in the course, then show a drop down menu for switching
391 if (count($rolenames) > 1) {
392 echo '<div class="rolesform">';
393 echo get_string('currentrole', 'role').': ';
394 $rolenames = array(0 => get_string('all')) +
$rolenames;
395 popup_form("$CFG->wwwroot/user/index.php?contextid=$context->id&sifirst=&silast=&roleid=", $rolenames,
396 'rolesform', $roleid, '');
401 if (!$currentrole = get_record('role','id',$roleid)) {
402 error('That role does not exist');
404 $a->number
= $totalcount;
405 $a->role
= $currentrole->name
;
406 $heading = format_string(get_string('xuserswiththerole', 'role', $a));
407 if (user_can_assign($context, $roleid)) {
408 $heading .= ' <a href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?roleid='.$roleid.'&contextid='.$context->id
.'">';
409 $heading .= '<img src="'.$CFG->pixpath
.'/i/edit.gif" class="icon" alt="" /></a>';
411 print_heading($heading, 'center', 3);
413 if ($matchcount < $totalcount) {
414 print_heading(get_string('allparticipants').': '.$matchcount.'/'.$totalcount, '', 3);
416 print_heading(get_string('allparticipants').': '.$matchcount, '', 3);
421 if ($bulkoperations) {
423 <script type="text/javascript">
425 function checksubmit(form) {
426 var destination = form.formaction.options[form.formaction.selectedIndex].value;
427 if (destination == "" || !checkchecked(form)) {
428 form.formaction.selectedIndex = 0;
435 function checkchecked(form) {
436 var inputs = document.getElementsByTagName(\'INPUT\');
438 inputs = filterByParent(inputs, function() {return form;});
439 for(var i = 0; i < inputs.length; ++i) {
440 if (inputs[i].type == \'checkbox\' && inputs[i].checked) {
449 echo '<form action="action_redir.php" method="post" id="participantsform" onsubmit="return checksubmit(this);">';
451 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey
.'" />';
452 echo '<input type="hidden" name="returnto" value="'.s($_SERVER['REQUEST_URI']).'" />';
455 if ($CFG->longtimenosee
> 0 && $CFG->longtimenosee
< 1000 && $totalcount > 0) {
456 echo '<p id="longtimenosee">('.get_string('unusedaccounts', '', $CFG->longtimenosee
).')</p>';
459 if ($fullmode) { // Print simple listing
460 if ($totalcount < 1) {
461 print_heading(get_string('nothingtodisplay'));
463 if ($totalcount > $perpage) {
465 $firstinitial = $table->get_initial_first();
466 $lastinitial = $table->get_initial_last();
467 $strall = get_string('all');
468 $alpha = explode(',', get_string('alphabet'));
470 // Bar of first initials
472 echo '<div class="initialbar firstinitial">'.get_string('firstname').' : ';
473 if(!empty($firstinitial)) {
474 echo '<a href="'.$baseurl.'&sifirst=">'.$strall.'</a>';
476 echo '<strong>'.$strall.'</strong>';
478 foreach ($alpha as $letter) {
479 if ($letter == $firstinitial) {
480 echo ' <strong>'.$letter.'</strong>';
482 echo ' <a href="'.$baseurl.'&sifirst='.$letter.'">'.$letter.'</a>';
487 // Bar of last initials
489 echo '<div class="initialbar lastinitial">'.get_string('lastname').' : ';
490 if(!empty($lastinitial)) {
491 echo '<a href="'.$baseurl.'&silast=">'.$strall.'</a>';
493 echo '<strong>'.$strall.'</strong>';
495 foreach ($alpha as $letter) {
496 if ($letter == $lastinitial) {
497 echo ' <strong>'.$letter.'</strong>';
499 echo ' <a href="'.$baseurl.'&silast='.$letter.'">'.$letter.'</a>';
504 print_paging_bar($matchcount, intval($table->get_page_start() / $perpage), $perpage, $baseurl.'&', 'spage');
507 if ($matchcount > 0) {
508 foreach ($userlist as $user) {
509 print_user($user, $course, $bulkoperations);
513 print_heading(get_string('nothingtodisplay'));
518 $countrysort = (strpos($sort, 'country') !== false);
519 $timeformat = get_string('strftimedate');
522 if (!empty($userlist)) {
523 foreach ($userlist as $user) {
525 // if the assignment is hidden, display icon
526 $hidden = "<img src=\"{$CFG->pixpath}/t/hide.gif\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
531 if ($user->lastaccess
) {
532 $lastaccess = format_time(time() - $user->lastaccess
, $datestring);
534 $lastaccess = $strnever;
537 if (empty($user->country
)) {
542 $country = '('.$user->country
.') '.$countries[$user->country
];
545 $country = $countries[$user->country
];
549 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
551 if ($piclink = ($USER->id
== $user->id ||
has_capability('moodle/user:viewdetails', $context) ||
has_capability('moodle/user:viewdetails', $context))) {
552 $profilelink = '<strong><a href="'.$CFG->wwwroot
.'/user/view.php?id='.$user->id
.'&course='.$course->id
.'">'.fullname($user).'</a></strong>';
554 $profilelink = '<strong>'.fullname($user).'</strong>';
558 print_user_picture($user->id
, $course->id
, $user->picture
, false, true, $piclink),
561 if (!isset($hiddenfields['city'])) {
562 $data[] = $user->city
;
564 if (!isset($hiddenfields['country'])) {
567 if (!isset($hiddenfields['lastaccess'])) {
568 $data[] = $lastaccess;
570 if ($course->enrolperiod
) {
571 if ($user->timeend
) {
572 $data[] = userdate($user->timeend
, $timeformat);
574 $data[] = get_string('unlimited');
577 if ($bulkoperations) {
578 $data[] = '<input type="checkbox" name="user'.$user->id
.'" />';
580 $table->add_data($data);
585 $table->print_html();
589 if ($bulkoperations) {
590 echo '<br /><div class="buttons">';
591 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
592 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
593 $displaylist = array();
594 // fix for MDL-8885, only show this if user has capability
595 if (has_capability('moodle/site:readallmessages', $context) && !empty($CFG->messaging
)) {
596 $displaylist['messageselect.php'] = get_string('messageselectadd');
598 if (has_capability('moodle/notes:manage', $context)) {
599 $displaylist['addnote.php'] = get_string('addnewnote', 'notes');
600 $displaylist['groupaddnote.php'] = get_string('groupaddnewnote', 'notes');
602 $displaylist['extendenrol.php'] = get_string('extendenrol');
603 $displaylist['groupextendenrol.php'] = get_string('groupextendenrol');
605 helpbutton("participantswithselectedusers", get_string("withselectedusers"));
606 choose_from_menu ($displaylist, "formaction", "", get_string("withselectedusers"), "if(checksubmit(this.form))this.form.submit();", "");
607 echo '<input type="hidden" name="id" value="'.$course->id
.'" />';
608 echo '<input type="submit" value="' . get_string('ok') . '" />';
615 if ($bulkoperations && $totalcount > ($perpage*3)) {
616 echo '<form action="index.php"><div><input type="hidden" name="id" value="'.$course->id
.'" />'.get_string('search').': '."\n";
617 echo '<input type="text" name="search" value="'.s($search).'" /> <input type="submit" value="'.get_string('search').'" /></div></form>'."\n";
620 $perpageurl = preg_replace('/&perpage=\d*/','', $baseurl);
621 if ($perpage == SHOW_ALL_PAGE_SIZE
) {
622 echo '<div id="showall"><a href="'.$perpageurl.'&perpage='.DEFAULT_PAGE_SIZE
.'">'.get_string('showperpage', '', DEFAULT_PAGE_SIZE
).'</a></div>';
624 } else if ($matchcount > 0 && $perpage < $matchcount) {
625 echo '<div id="showall"><a href="'.$perpageurl.'&perpage='.SHOW_ALL_PAGE_SIZE
.'">'.get_string('showall', '', $matchcount).'</a></div>';
628 print_footer($course);
633 function get_lastaccess_sql($accesssince='') {
634 if (empty($accesssince)) {
637 if ($accesssince == -1) { // never
638 return ' AND ul.timeaccess = 0';
640 return ' AND ul.timeaccess != 0 AND timeaccess < '.$accesssince;