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->id
);
47 if ($roles = get_roles_used_in_context($context)) {
48 foreach ($roles as $role) {
49 $options[$role->id
] = $role->name
;
51 } else { // no roles yet
52 if (has_capability('moodle/user:assign', $context)) {
53 redirect($CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?contextid='.$context->id
);
55 error ('no participants found for this course');
59 if (!has_capability('moodle/course:viewparticipants', $context)
60 && !has_capability('moodle/site:viewparticipants', $context)) {
61 print_error('nopermissions');
64 if (!$course->category
) {
65 if (!has_capability('moodle/course:viewparticipants', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
66 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
67 get_string('participants'), "", "", true, " ", navmenu($course));
68 notice(get_string('sitepartlist'));
72 add_to_log($course->id
, 'user', 'view all', 'index.php?id='.$course->id
, '');
74 $bulkoperations = has_capability('moodle/course:bulkmessaging', $context);
76 $countries = get_list_of_countries();
78 $strnever = get_string('never');
80 $datestring->day
= get_string('day');
81 $datestring->days
= get_string('days');
82 $datestring->hour
= get_string('hour');
83 $datestring->hours
= get_string('hours');
84 $datestring->min
= get_string('min');
85 $datestring->mins
= get_string('mins');
86 $datestring->sec
= get_string('sec');
87 $datestring->secs
= get_string('secs');
90 $SESSION->userindexmode
= $fullmode = ($mode == 1);
91 } else if (isset($SESSION->userindexmode
)) {
92 $fullmode = $SESSION->userindexmode
;
97 /// Check to see if groups are being used in this course
98 /// and if so, set $currentgroup to reflect the current group
100 $groupmode = groupmode($course); // Groups are being used
101 $currentgroup = get_and_set_current_group($course, $groupmode, $group);
103 if (!$currentgroup) { // To make some other functions work better later
104 $currentgroup = NULL;
107 $isseparategroups = ($course->groupmode
== SEPARATEGROUPS
and $course->groupmodeforce
and
108 !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_COURSE
, $course->id
)));
110 if ($isseparategroups and (!$currentgroup) ) {
111 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
112 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> -> ".
113 get_string('participants'), "", "", true, " ", navmenu($course));
114 print_heading(get_string("notingroup"));
115 print_footer($course);
119 // Should use this variable so that we don't break stuff every time a variable is added or changed.
120 $baseurl = $CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'&id='.$course->id
.'&group='.$currentgroup.'&perpage='.$perpage.'&accesssince='.$accesssince.'&search='.s($search);
124 if ($course->category
) {
125 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
126 "<a href=\"../course/view.php?id=$course->id\">$course->shortname</a> -> ".
127 get_string('participants'), "", "", true, " ", navmenu($course));
129 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
130 get_string('participants'), "", "", true, " ", navmenu($course));
135 if ($course->id
== SITEID
) {
136 $filtertype = 'site';
137 } else if ($course->id
&& !$currentgroup) {
138 $filtertype = 'course';
139 $filterselect = $course->id
;
141 $filtertype = 'group';
142 $filterselect = $currentgroup;
144 $currenttab = 'participants';
147 require_once($CFG->dirroot
.'/user/tabs.php');
150 /// Get the hidden field list
151 if (has_capability('moodle/course:viewhiddenuserfields', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
152 $hiddenfields = array(); // teachers and admins are allowed to see everything
154 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
158 /// Print settings and things in a table across the top
160 echo '<table class="controls" cellspacing="0"><tr>';
162 /// Print my course menus
163 if ($mycourses = get_my_courses($USER->id
)) {
164 echo '<td class="left">';
165 print_string('mycourses');
168 $courselist = array();
169 foreach ($mycourses as $mycourse) {
170 $courselist[$mycourse->id
] = $mycourse->shortname
;
172 popup_form($CFG->wwwroot
.'/user/index.php?roleid='.$roleid.'&sifirst=&silast=&id=',
173 $courselist, 'courseform',$course->id
);
177 if ($groupmode == VISIBLEGROUPS
or ($groupmode and has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_COURSE
, $course->id
)))) {
178 if ($groups = get_records_menu("groups", "courseid", $course->id
, "name ASC", "id,name")) {
179 echo '<td class="left">';
180 print_group_menu($groups, $groupmode, $currentgroup, $baseurl);
185 // get minimum lastaccess for this course and display a dropbox to filter by lastaccess going back this far.
186 // this might not work anymore because you always going to get yourself as the most recent entry? added $USER!=$user ch
187 $minlastaccess = get_field_sql('SELECT min(timeaccess) FROM '.$CFG->prefix
.'user_lastaccess WHERE courseid = '.$course->id
.' AND timeaccess != 0 AND userid!='.$USER->id
);
188 $lastaccess0exists = record_exists('user_lastaccess','courseid',$course->id
,'timeaccess',0);
189 $now = usergetmidnight(time());
190 $timeaccess = array();
192 // makes sense for this to go first.
193 $timeoptions[0] = get_string('selectperiod');
196 for ($i = 1; $i < 7; $i++
) {
197 if (strtotime('-'.$i.' days',$now) >= $minlastaccess) {
198 $timeoptions[strtotime('-'.$i.' days',$now)] = get_string('numdays','moodle',$i);
202 for ($i = 1; $i < 10; $i++
) {
203 if (strtotime('-'.$i.' weeks',$now) >= $minlastaccess) {
204 $timeoptions[strtotime('-'.$i.' weeks',$now)] = get_string('numweeks','moodle',$i);
208 for ($i = 2; $i < 12; $i++
) {
209 if (strtotime('-'.$i.' months',$now) >= $minlastaccess) {
210 $timeoptions[strtotime('-'.$i.' months',$now)] = get_string('nummonths','moodle',$i);
214 if (strtotime('-1 year',$now) >= $minlastaccess) {
215 $timeoptions[strtotime('-1 year',$now)] = get_string('lastyear');
218 if (!empty($lastaccess0exists)) {
219 $timeoptions[-1] = get_string('never');
222 if (count($timeoptions) > 1) {
223 echo '<td class="left">';
224 echo get_string('usersnoaccesssince').': ';
225 $baseurl = preg_replace('/&accesssince='.$accesssince.'/','',$baseurl);
226 echo popup_form($baseurl.'&accesssince=',$timeoptions,'timeoptions',$accesssince,'','','',true);
231 echo '<td class="right">';
232 echo get_string('userlist').': ';
233 $formatmenu = array( '0' => get_string('detailedless'),
234 '1' => get_string('detailedmore'));
235 echo popup_form($baseurl.'&mode=', $formatmenu, 'formatmenu', $fullmode, '', '', '', true);
236 echo '</td></tr></table>';
238 if ($currentgroup and (!$isseparategroups or has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_COURSE
, $course->id
)))) { /// Display info about the group
239 if ($group = get_record('groups', 'id', $currentgroup)) {
240 if (!empty($group->description
) or (!empty($group->picture
) and empty($group->hidepicture
))) {
241 echo '<table class="groupinfobox"><tr><td class="left side picture">';
242 print_group_picture($group, $course->id
, true, false, false);
243 echo '</td><td class="content">';
244 echo '<h3>'.$group->name
;
245 if (has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
246 echo ' <a title="'.get_string('editgroupprofile').'" href="../course/groups.php?id='.$course->id
.'&group='.$group->id
.'">';
247 echo '<img src="'.$CFG->pixpath
.'/t/edit.gif" alt="" border="0">';
251 echo format_text($group->description
);
252 echo '</td></tr></table>';
257 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
259 $rolenames = array();
260 $avoidroles = array();
263 if ($roles = get_roles_used_in_context($context)) {
265 // We should ONLY allow roles with moodle/course:view because otherwise we get little niggly issues
267 // We should further exclude "admin" users (those with "doanything" at site level) because
268 // Otherwise they appear in every participant list
270 $canviewroles = get_roles_with_capability('moodle/course:view', CAP_ALLOW
, $context);
271 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $sitecontext);
273 foreach ($roles as $role) {
274 if (!isset($canviewroles[$role->id
])) { // Avoid this role (eg course creator)
275 $avoidroles[] = $role->id
;
276 unset($roles[$role->id
]);
279 if (isset($doanythingroles[$role->id
])) { // Avoid this role (ie admin)
280 $avoidroles[] = $role->id
;
281 unset($roles[$role->id
]);
286 foreach ($roles as $role) {
287 $rolenames[$role->id
] = strip_tags(format_string($role->name
)); // Used in menus etc later on
292 /// Define a table showing a list of users in the current role selection
294 $tablecolumns = array('picture', 'fullname');
295 $tableheaders = array('', get_string('fullname'));
296 if (!isset($hiddenfields['city'])) {
297 $tablecolumns[] = 'city';
298 $tableheaders[] = get_string('city');
300 if (!isset($hiddenfields['country'])) {
301 $tablecolumns[] = 'country';
302 $tableheaders[] = get_string('country');
304 if (!isset($hiddenfields['lastaccess'])) {
305 $tablecolumns[] = 'lastaccess';
306 $tableheaders[] = get_string('lastaccess');
309 if ($course->enrolperiod
) {
310 $tablecolumns[] = 'timeend';
311 $tableheaders[] = get_string('enrolmentend');
314 if ($bulkoperations) {
315 $tablecolumns[] = '';
316 $tableheaders[] = get_string('select');
319 $table = new flexible_table('user-index-participants-'.$course->id
);
321 $table->define_columns($tablecolumns);
322 $table->define_headers($tableheaders);
323 $table->define_baseurl($baseurl);
325 $table->sortable(true, 'lastaccess', SORT_DESC
);
327 $table->set_attribute('cellspacing', '0');
328 $table->set_attribute('id', 'participants');
329 $table->set_attribute('class', 'generaltable generalbox');
331 $table->set_control_variables(array(
332 TABLE_VAR_SORT
=> 'ssort',
333 TABLE_VAR_HIDE
=> 'shide',
334 TABLE_VAR_SHOW
=> 'sshow',
335 TABLE_VAR_IFIRST
=> 'sifirst',
336 TABLE_VAR_ILAST
=> 'silast',
337 TABLE_VAR_PAGE
=> 'spage'
342 // we are looking for all users with this role assigned in this context or higher
343 if ($usercontexts = get_parent_contexts($context)) {
344 $listofcontexts = '('.implode(',', $usercontexts).')';
346 $sitecontext = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
347 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
350 $selectrole = " AND r.roleid = $roleid ";
354 $select = 'SELECT u.id, u.username, u.firstname, u.lastname, u.email, u.city, u.country,
355 u.picture, u.lang, u.timezone, u.emailstop, u.maildisplay, ul.timeaccess AS lastaccess '; // s.lastaccess
356 $select .= $course->enrolperiod?
', r.timeend ':'';
357 $from = "FROM {$CFG->prefix}user u INNER JOIN
358 {$CFG->prefix}role_assignments r on u.id=r.userid LEFT OUTER JOIN
359 {$CFG->prefix}user_lastaccess ul on (r.userid=ul.userid and ul.courseid = $course->id)";
361 $hiddensql = has_capability('moodle/role:viewhiddenassigns', $context)?
'':' AND r.hidden = 0 ';
363 // exclude users with roles we are avoiding
365 $adminroles = 'AND r.roleid NOT IN (';
366 $adminroles .= implode(',', $avoidroles);
372 // join on 2 conditions
373 // otherwise we run into the problem of having records in ul table, but not relevant course
374 // and user record is not pulled out
375 $where = "WHERE (r.contextid = $context->id OR r.contextid in $listofcontexts)
376 AND u.deleted = 0 $selectrole
377 AND (ul.courseid = $course->id OR ul.courseid IS NULL)
378 AND u.username <> 'guest'
381 $where .= get_lastaccess_sql($accesssince);
385 if (!empty($search)) {
387 $fullname = sql_fullname('u.firstname','u.lastname');
388 $wheresearch .= ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\' OR idnumber '.$LIKE.' \'%'.$search.'%\') ';
392 if ($currentgroup) { // Displaying a group by choice
393 // FIX: TODO: This will not work if $currentgroup == 0, i.e. "those not in a group"
394 $from .= 'LEFT JOIN '.$CFG->prefix
.'groups_members gm ON u.id = gm.userid ';
395 $where .= ' AND gm.groupid = '.$currentgroup;
398 $totalcount = count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where); // Each user could have > 1 role
400 if ($table->get_sql_where()) {
401 $where .= ' AND '.$table->get_sql_where();
404 if ($table->get_sql_sort()) {
405 $sort = ' ORDER BY '.$table->get_sql_sort();
410 $matchcount = count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where.$wheresearch);
412 $table->initialbars($totalcount > $perpage);
413 $table->pagesize($perpage, $matchcount);
415 $userlist = get_records_sql($select.$from.$where.$wheresearch.$sort,
416 $table->get_page_start(), $table->get_page_size());
418 /// If there are multiple Roles in the course, then show a drop down menu for switching
420 if (!empty($rolenames)) {
421 echo '<div class="rolesform">';
422 echo get_string('currentrole', 'role').': ';
423 $rolenames = array(0 => get_string('all')) +
$rolenames;
424 popup_form('index.php?contextid='.$context->id
.'&sifirst=&silast=&roleid=', $rolenames,
425 'rolesform', $roleid, '');
430 if (!$currentrole = get_record('role','id',$roleid)) {
431 error('That role does not exist');
433 $a->number
= $totalcount;
434 $a->role
= $currentrole->name
;
435 $heading = get_string('xuserswiththerole', 'role', $a);
436 if (user_can_assign($context, $roleid)) {
437 $heading .= ' <a href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?roleid='.$roleid.'&contextid='.$context->id
.'">';
438 $heading .= '<img src="'.$CFG->pixpath
.'/i/edit.gif" height="16" width="16" alt="" /></a>';
440 print_heading($heading, 'center', 3);
442 if ($matchcount < $totalcount) {
443 print_heading(get_string('allparticipants').': '.$matchcount.'/'.$totalcount, 'center', 3);
445 print_heading(get_string('allparticipants').': '.$matchcount, 'center', 3);
450 if ($bulkoperations) {
452 <script Language="JavaScript">
454 function checksubmit(form) {
455 var destination = form.formaction.options[form.formaction.selectedIndex].value;
456 if (destination == "" || !checkchecked(form)) {
457 form.formaction.selectedIndex = 0;
464 function checkchecked(form) {
465 var inputs = document.getElementsByTagName(\'INPUT\');
467 inputs = filterByParent(inputs, function() {return form;});
468 for(var i = 0; i < inputs.length; ++i) {
469 if (inputs[i].type == \'checkbox\' && inputs[i].checked) {
478 echo '<form action="action_redir.php" method="post" name="participantsform" onSubmit="return checksubmit(this);">';
479 echo '<input type="hidden" name="returnto" value="'.$_SERVER['REQUEST_URI'].'" />';
480 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey
.'" />';
483 if ($CFG->longtimenosee
> 0 && $CFG->longtimenosee
< 1000 && $totalcount > 0) {
484 echo '<p id="longtimenosee">('.get_string('unusedaccounts', '', $CFG->longtimenosee
).')</p>';
487 if ($fullmode) { // Print simple listing
488 if ($totalcount < 1) {
489 print_heading(get_string('nothingtodisplay'));
491 if ($totalcount > $perpage) {
493 $firstinitial = $table->get_initial_first();
494 $lastinitial = $table->get_initial_last();
495 $strall = get_string('all');
496 $alpha = explode(',', get_string('alphabet'));
498 // Bar of first initials
500 echo '<div class="initialbar firstinitial">'.get_string('firstname').' : ';
501 if(!empty($firstinitial)) {
502 echo '<a href="'.$baseurl.'&sifirst=">'.$strall.'</a>';
504 echo '<strong>'.$strall.'</strong>';
506 foreach ($alpha as $letter) {
507 if ($letter == $firstinitial) {
508 echo ' <strong>'.$letter.'</strong>';
510 echo ' <a href="'.$baseurl.'&sifirst='.$letter.'">'.$letter.'</a>';
515 // Bar of last initials
517 echo '<div class="initialbar lastinitial">'.get_string('lastname').' : ';
518 if(!empty($lastinitial)) {
519 echo '<a href="'.$baseurl.'&silast=">'.$strall.'</a>';
521 echo '<strong>'.$strall.'</strong>';
523 foreach ($alpha as $letter) {
524 if ($letter == $lastinitial) {
525 echo ' <strong>'.$letter.'</strong>';
527 echo ' <a href="'.$baseurl.'&silast='.$letter.'">'.$letter.'</a>';
532 print_paging_bar($matchcount, intval($table->get_page_start() / $perpage), $perpage, $baseurl.'&', 'spage');
535 if ($matchcount > 0) {
536 foreach ($userlist as $user) {
537 print_user($user, $course, $bulkoperations);
541 print_heading(get_string('nothingtodisplay'));
546 $countrysort = (strpos($sort, 'country') !== false);
547 $timeformat = get_string('strftimedate');
548 if (!empty($userlist)) {
549 foreach ($userlist as $user) {
550 if ($user->lastaccess
) {
551 $lastaccess = format_time(time() - $user->lastaccess
, $datestring);
553 $lastaccess = $strnever;
556 if (empty($user->country
)) {
561 $country = '('.$user->country
.') '.$countries[$user->country
];
564 $country = $countries[$user->country
];
568 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
570 if ($piclink = ($USER->id
== $user->id ||
has_capability('moodle/user:viewdetails', $context) ||
has_capability('moodle/user:viewdetails', $context))) {
571 $profilelink = '<strong><a href="'.$CFG->wwwroot
.'/user/view.php?id='.$user->id
.'&course='.$course->id
.'">'.fullname($user).'</a></strong>';
573 $profilelink = '<strong>'.fullname($user).'</strong>';
577 print_user_picture($user->id
, $course->id
, $user->picture
, false, true, $piclink),
579 if (!isset($hiddenfields['city'])) {
580 $data[] = $user->city
;
582 if (!isset($hiddenfields['country'])) {
585 if (!isset($hiddenfields['lastaccess'])) {
586 $data[] = $lastaccess;
588 if ($course->enrolperiod
) {
589 if ($user->timeend
) {
590 $data[] = userdate($user->timeend
, $timeformat);
592 $data[] = get_string('unlimited');
595 if ($bulkoperations) {
596 $data[] = '<input type="checkbox" name="user'.$user->id
.'" />';
598 $table->add_data($data);
603 $table->print_html();
607 if ($bulkoperations) {
608 echo '<br /><div class="form-buttons" align="center">';
609 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
610 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
611 $displaylist = array();
612 // fix for MDL-8885, only show this if user has capability
613 if (has_capability('moodle/site:readallmessages', $context)) {
614 $displaylist['messageselect.php'] = get_string('messageselectadd');
616 if ($course->enrolperiod
) {
617 $displaylist['extendenrol.php'] = get_string('extendenrol');
619 choose_from_menu ($displaylist, "formaction", "", get_string("withselectedusers"), "if(checksubmit(this.form))this.form.submit();", "");
620 helpbutton("participantswithselectedusers", get_string("withselectedusers"));
621 echo '<input type="hidden" name="id" value="'.$course->id
.'" />';
622 echo '<input type="submit" value="' . get_string('ok') . '" />';
623 echo '</div></form>';
626 if ($bulkoperations && $totalcount > ($perpage*3)) {
627 echo '<form action="index.php"><p align="center"><input type="hidden" name="id" value="'.$course->id
.'" />'.get_string('search').': '."\n";
628 echo '<input type="text" name="search" value="'.s($search).'" /> <input type="submit" value="'.get_string('search').'" /></p></form>'."\n";
631 if ($perpage == SHOW_ALL_PAGE_SIZE
) {
632 echo '<div id="showall"><a href="'.$baseurl.'&perpage='.DEFAULT_PAGE_SIZE
.'">'.get_string('showperpage', '', DEFAULT_PAGE_SIZE
).'</a></div>';
634 } else if ($matchcount > 0 && $perpage < $matchcount) {
635 echo '<div id="showall"><a href="'.$baseurl.'&perpage='.SHOW_ALL_PAGE_SIZE
.'">'.get_string('showall', '', $matchcount).'</a></div>';
638 print_footer($course);
643 function get_lastaccess_sql($accesssince='') {
644 if (empty($accesssince)) {
647 if ($accesssince == -1) { // never
648 return ' AND ul.timeaccess = 0';
650 return ' AND ul.timeaccess != 0 AND timeaccess < '.$accesssince;