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/user: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) ) {
128 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
129 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> -> ".
130 get_string('participants'), "", "", true, " ", navmenu($course));
131 print_heading(get_string("notingroup", "forum"));
132 print_footer($course);
136 // Should use this variable so that we don't break stuff every time a variable is added or changed.
137 $baseurl = $CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'&id='.$course->id
.'&group='.$currentgroup.'&perpage='.$perpage.'&accesssince='.$accesssince.'&search='.s($search);
141 if ($course->id
!= SITEID
) {
142 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
143 "<a href=\"../course/view.php?id=$course->id\">$course->shortname</a> -> ".
144 get_string('participants'), "", "", true, " ", navmenu($course));
146 print_header("$course->shortname: ".get_string('participants'), $course->fullname
,
147 get_string('participants'), "", "", true, " ", navmenu($course));
153 if ($course->id
== SITEID
) {
154 $filtertype = 'site';
155 } else if ($course->id
&& !$currentgroup) {
156 $filtertype = 'course';
157 $filterselect = $course->id
;
159 $filtertype = 'group';
160 $filterselect = $currentgroup;
162 $currenttab = 'participants';
165 require_once($CFG->dirroot
.'/user/tabs.php');
168 /// Get the hidden field list
169 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
170 $hiddenfields = array(); // teachers and admins are allowed to see everything
172 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields
));
176 /// Print settings and things in a table across the top
178 echo '<table class="controls" cellspacing="0"><tr>';
180 /// Print my course menus
181 if ($mycourses = get_my_courses($USER->id
)) {
182 echo '<td class="left">';
183 $courselist = array();
184 foreach ($mycourses as $mycourse) {
185 $courselist[$mycourse->id
] = format_string($mycourse->shortname
);
187 popup_form($CFG->wwwroot
.'/user/index.php?roleid='.$roleid.'&sifirst=&silast=&id=',
188 $courselist, 'courseform', $course->id
, '', '', '', false, 'self', get_string('mycourses'));
192 echo '<td class="left">';
193 setup_and_print_groups($course, $groupmode, $baseurl);
196 // get minimum lastaccess for this course and display a dropbox to filter by lastaccess going back this far.
197 // this might not work anymore because you always going to get yourself as the most recent entry? added $USER!=$user ch
198 $minlastaccess = get_field_sql('SELECT min(timeaccess) FROM '.$CFG->prefix
.'user_lastaccess WHERE courseid = '.$course->id
.' AND timeaccess != 0 AND userid!='.$USER->id
);
199 $lastaccess0exists = record_exists('user_lastaccess','courseid',$course->id
,'timeaccess',0);
200 $now = usergetmidnight(time());
201 $timeaccess = array();
203 // makes sense for this to go first.
204 $timeoptions[0] = get_string('selectperiod');
207 for ($i = 1; $i < 7; $i++
) {
208 if (strtotime('-'.$i.' days',$now) >= $minlastaccess) {
209 $timeoptions[strtotime('-'.$i.' days',$now)] = get_string('numdays','moodle',$i);
213 for ($i = 1; $i < 10; $i++
) {
214 if (strtotime('-'.$i.' weeks',$now) >= $minlastaccess) {
215 $timeoptions[strtotime('-'.$i.' weeks',$now)] = get_string('numweeks','moodle',$i);
219 for ($i = 2; $i < 12; $i++
) {
220 if (strtotime('-'.$i.' months',$now) >= $minlastaccess) {
221 $timeoptions[strtotime('-'.$i.' months',$now)] = get_string('nummonths','moodle',$i);
225 if (strtotime('-1 year',$now) >= $minlastaccess) {
226 $timeoptions[strtotime('-1 year',$now)] = get_string('lastyear');
229 if (!empty($lastaccess0exists)) {
230 $timeoptions[-1] = get_string('never');
233 if (count($timeoptions) > 1) {
234 echo '<td class="left">';
235 $baseurl = preg_replace('/&accesssince='.$accesssince.'/','',$baseurl);
236 popup_form($baseurl.'&accesssince=',$timeoptions,'timeoptions',$accesssince, '', '', '', false, 'self', get_string('usersnoaccesssince'));
241 echo '<td class="right">';
242 $formatmenu = array( '0' => get_string('detailedless'),
243 '1' => get_string('detailedmore'));
244 popup_form($baseurl.'&mode=', $formatmenu, 'formatmenu', $fullmode, '', '', '', false, 'self', get_string('userlist'));
245 echo '</td></tr></table>';
247 if ($currentgroup and (!$isseparategroups or has_capability('moodle/site:accessallgroups', $context))) { /// Display info about the group
248 if ($group = groups_get_group($currentgroup)) { //TODO:
249 if (!empty($group->description
) or (!empty($group->picture
) and empty($group->hidepicture
))) {
250 echo '<table class="groupinfobox"><tr><td class="left side picture">';
251 print_group_picture($group, $course->id
, true, false, false);
252 echo '</td><td class="content">';
253 echo '<h3>'.$group->name
;
254 if (has_capability('moodle/course:managegroups', $context)) {
255 echo ' <a title="'.get_string('editgroupprofile').'" href="'.groups_group_edit_url($course->id
, $group->id
).'">';
256 echo '<img src="'.$CFG->pixpath
.'/t/edit.gif" alt="'.get_string('editgroupprofile').'" />';
260 echo format_text($group->description
);
261 echo '</td></tr></table>';
267 /// Define a table showing a list of users in the current role selection
269 $tablecolumns = array('userpic', 'fullname');
270 $tableheaders = array(get_string('userpic'), get_string('fullname'));
271 if (!isset($hiddenfields['city'])) {
272 $tablecolumns[] = 'city';
273 $tableheaders[] = get_string('city');
275 if (!isset($hiddenfields['country'])) {
276 $tablecolumns[] = 'country';
277 $tableheaders[] = get_string('country');
279 if (!isset($hiddenfields['lastaccess'])) {
280 $tablecolumns[] = 'lastaccess';
281 $tableheaders[] = get_string('lastaccess');
284 if ($course->enrolperiod
) {
285 $tablecolumns[] = 'timeend';
286 $tableheaders[] = get_string('enrolmentend');
289 if ($bulkoperations) {
290 $tablecolumns[] = '';
291 $tableheaders[] = get_string('select');
294 $table = new flexible_table('user-index-participants-'.$course->id
);
296 $table->define_columns($tablecolumns);
297 $table->define_headers($tableheaders);
298 $table->define_baseurl($baseurl);
300 $table->sortable(true, 'lastaccess', SORT_DESC
);
302 $table->set_attribute('cellspacing', '0');
303 $table->set_attribute('id', 'participants');
304 $table->set_attribute('class', 'generaltable generalbox');
306 $table->set_control_variables(array(
307 TABLE_VAR_SORT
=> 'ssort',
308 TABLE_VAR_HIDE
=> 'shide',
309 TABLE_VAR_SHOW
=> 'sshow',
310 TABLE_VAR_IFIRST
=> 'sifirst',
311 TABLE_VAR_ILAST
=> 'silast',
312 TABLE_VAR_PAGE
=> 'spage'
317 // we are looking for all users with this role assigned in this context or higher
318 if ($usercontexts = get_parent_contexts($context)) {
319 $listofcontexts = '('.implode(',', $usercontexts).')';
321 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
324 $selectrole = " AND r.roleid = $roleid ";
328 $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
329 $select .= $course->enrolperiod?
', r.timeend ':'';
331 $from = "FROM {$CFG->prefix}user u INNER JOIN
332 {$CFG->prefix}role_assignments r on u.id=r.userid LEFT OUTER JOIN
333 {$CFG->prefix}user_lastaccess ul on (r.userid=ul.userid and ul.courseid = $course->id)";
335 $hiddensql = has_capability('moodle/role:viewhiddenassigns', $context)?
'':' AND r.hidden = 0 ';
337 // exclude users with roles we are avoiding
339 $adminroles = 'AND r.roleid NOT IN (';
340 $adminroles .= implode(',', $avoidroles);
346 // join on 2 conditions
347 // otherwise we run into the problem of having records in ul table, but not relevant course
348 // and user record is not pulled out
349 $where = "WHERE (r.contextid = $context->id OR r.contextid in $listofcontexts)
350 AND u.deleted = 0 $selectrole
351 AND (ul.courseid = $course->id OR ul.courseid IS NULL)
352 AND u.username != 'guest'
355 $where .= get_lastaccess_sql($accesssince);
359 if (!empty($search)) {
361 $fullname = sql_fullname('u.firstname','u.lastname');
362 $wheresearch .= ' AND ('. $fullname .' '. $LIKE .'\'%'. $search .'%\' OR email '. $LIKE .'\'%'. $search .'%\' OR idnumber '.$LIKE.' \'%'.$search.'%\') ';
366 if ($currentgroup) { // Displaying a group by choice
367 // FIX: TODO: This will not work if $currentgroup == 0, i.e. "those not in a group"
368 $from .= 'LEFT JOIN '.$CFG->prefix
.'groups_members gm ON u.id = gm.userid ';
369 $where .= ' AND gm.groupid = '.$currentgroup;
372 $totalcount = count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where); // Each user could have > 1 role
374 if ($table->get_sql_where()) {
375 $where .= ' AND '.$table->get_sql_where();
378 if ($table->get_sql_sort()) {
379 $sort = ' ORDER BY '.$table->get_sql_sort();
384 $matchcount = count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where.$wheresearch);
386 $table->initialbars($totalcount > $perpage);
387 $table->pagesize($perpage, $matchcount);
389 $userlist = get_records_sql($select.$from.$where.$wheresearch.$sort,
390 $table->get_page_start(), $table->get_page_size());
392 /// If there are multiple Roles in the course, then show a drop down menu for switching
394 if (count($rolenames) > 1) {
395 echo '<div class="rolesform">';
396 echo get_string('currentrole', 'role').': ';
397 $rolenames = array(0 => get_string('all')) +
$rolenames;
398 popup_form("$CFG->wwwroot/user/index.php?contextid=$context->id&sifirst=&silast=&roleid=", $rolenames,
399 'rolesform', $roleid, '');
403 if (!$currentrole = get_record('role','id',$roleid)) {
404 error('That role does not exist');
406 $a->number
= $totalcount;
407 $a->role
= $currentrole->name
;
408 $heading = format_string(get_string('xuserswiththerole', 'role', $a));
409 if (user_can_assign($context, $roleid)) {
410 $heading .= ' <a href="'.$CFG->wwwroot
.'/'.$CFG->admin
.'/roles/assign.php?roleid='.$roleid.'&contextid='.$context->id
.'">';
411 $heading .= '<img src="'.$CFG->pixpath
.'/i/edit.gif" class="icon" alt="" /></a>';
413 print_heading($heading, 'center', 3);
415 if ($matchcount < $totalcount) {
416 print_heading(get_string('allparticipants').': '.$matchcount.'/'.$totalcount, '', 3);
418 print_heading(get_string('allparticipants').': '.$matchcount, '', 3);
423 if ($bulkoperations) {
425 <script type="text/javascript">
427 function checksubmit(form) {
428 var destination = form.formaction.options[form.formaction.selectedIndex].value;
429 if (destination == "" || !checkchecked(form)) {
430 form.formaction.selectedIndex = 0;
437 function checkchecked(form) {
438 var inputs = document.getElementsByTagName(\'INPUT\');
440 inputs = filterByParent(inputs, function() {return form;});
441 for(var i = 0; i < inputs.length; ++i) {
442 if (inputs[i].type == \'checkbox\' && inputs[i].checked) {
451 echo '<form action="action_redir.php" method="post" id="participantsform" onsubmit="return checksubmit(this);">';
453 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey
.'" />';
454 echo '<input type="hidden" name="returnto" value="'.s($_SERVER['REQUEST_URI']).'" />';
457 if ($CFG->longtimenosee
> 0 && $CFG->longtimenosee
< 1000 && $totalcount > 0) {
458 echo '<p id="longtimenosee">('.get_string('unusedaccounts', '', $CFG->longtimenosee
).')</p>';
461 if ($fullmode) { // Print simple listing
462 if ($totalcount < 1) {
463 print_heading(get_string('nothingtodisplay'));
465 if ($totalcount > $perpage) {
467 $firstinitial = $table->get_initial_first();
468 $lastinitial = $table->get_initial_last();
469 $strall = get_string('all');
470 $alpha = explode(',', get_string('alphabet'));
472 // Bar of first initials
474 echo '<div class="initialbar firstinitial">'.get_string('firstname').' : ';
475 if(!empty($firstinitial)) {
476 echo '<a href="'.$baseurl.'&sifirst=">'.$strall.'</a>';
478 echo '<strong>'.$strall.'</strong>';
480 foreach ($alpha as $letter) {
481 if ($letter == $firstinitial) {
482 echo ' <strong>'.$letter.'</strong>';
484 echo ' <a href="'.$baseurl.'&sifirst='.$letter.'">'.$letter.'</a>';
489 // Bar of last initials
491 echo '<div class="initialbar lastinitial">'.get_string('lastname').' : ';
492 if(!empty($lastinitial)) {
493 echo '<a href="'.$baseurl.'&silast=">'.$strall.'</a>';
495 echo '<strong>'.$strall.'</strong>';
497 foreach ($alpha as $letter) {
498 if ($letter == $lastinitial) {
499 echo ' <strong>'.$letter.'</strong>';
501 echo ' <a href="'.$baseurl.'&silast='.$letter.'">'.$letter.'</a>';
506 print_paging_bar($matchcount, intval($table->get_page_start() / $perpage), $perpage, $baseurl.'&', 'spage');
509 if ($matchcount > 0) {
510 foreach ($userlist as $user) {
511 print_user($user, $course, $bulkoperations);
515 print_heading(get_string('nothingtodisplay'));
520 $countrysort = (strpos($sort, 'country') !== false);
521 $timeformat = get_string('strftimedate');
524 if (!empty($userlist)) {
525 foreach ($userlist as $user) {
527 // if the assignment is hidden, display icon
528 $hidden = "<img src=\"{$CFG->pixpath}/t/hide.gif\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
533 if ($user->lastaccess
) {
534 $lastaccess = format_time(time() - $user->lastaccess
, $datestring);
536 $lastaccess = $strnever;
539 if (empty($user->country
)) {
544 $country = '('.$user->country
.') '.$countries[$user->country
];
547 $country = $countries[$user->country
];
551 $usercontext = get_context_instance(CONTEXT_USER
, $user->id
);
553 if ($piclink = ($USER->id
== $user->id ||
has_capability('moodle/user:viewdetails', $context) ||
has_capability('moodle/user:viewdetails', $context))) {
554 $profilelink = '<strong><a href="'.$CFG->wwwroot
.'/user/view.php?id='.$user->id
.'&course='.$course->id
.'">'.fullname($user).'</a></strong>';
556 $profilelink = '<strong>'.fullname($user).'</strong>';
560 print_user_picture($user->id
, $course->id
, $user->picture
, false, true, $piclink),
563 if (!isset($hiddenfields['city'])) {
564 $data[] = $user->city
;
566 if (!isset($hiddenfields['country'])) {
569 if (!isset($hiddenfields['lastaccess'])) {
570 $data[] = $lastaccess;
572 if ($course->enrolperiod
) {
573 if ($user->timeend
) {
574 $data[] = userdate($user->timeend
, $timeformat);
576 $data[] = get_string('unlimited');
579 if ($bulkoperations) {
580 $data[] = '<input type="checkbox" name="user'.$user->id
.'" />';
582 $table->add_data($data);
587 $table->print_html();
591 if ($bulkoperations) {
592 echo '<br /><div class="buttons">';
593 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
594 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
595 $displaylist = array();
596 // fix for MDL-8885, only show this if user has capability
597 if (has_capability('moodle/site:readallmessages', $context) && !empty($CFG->messaging
)) {
598 $displaylist['messageselect.php'] = get_string('messageselectadd');
601 $displaylist['extendenrol.php'] = get_string('extendenrol');
602 $displaylist['groupextendenrol.php'] = get_string('groupextendenrol');
604 helpbutton("participantswithselectedusers", get_string("withselectedusers"));
605 choose_from_menu ($displaylist, "formaction", "", get_string("withselectedusers"), "if(checksubmit(this.form))this.form.submit();", "");
606 echo '<input type="hidden" name="id" value="'.$course->id
.'" />';
607 echo '<input type="submit" value="' . get_string('ok') . '" />';
614 if ($bulkoperations && $totalcount > ($perpage*3)) {
615 echo '<form action="index.php"><div><input type="hidden" name="id" value="'.$course->id
.'" />'.get_string('search').': '."\n";
616 echo '<input type="text" name="search" value="'.s($search).'" /> <input type="submit" value="'.get_string('search').'" /></div></form>'."\n";
619 $perpageurl = preg_replace('/&perpage=\d*/','', $baseurl);
620 if ($perpage == SHOW_ALL_PAGE_SIZE
) {
621 echo '<div id="showall"><a href="'.$perpageurl.'&perpage='.DEFAULT_PAGE_SIZE
.'">'.get_string('showperpage', '', DEFAULT_PAGE_SIZE
).'</a></div>';
623 } else if ($matchcount > 0 && $perpage < $matchcount) {
624 echo '<div id="showall"><a href="'.$perpageurl.'&perpage='.SHOW_ALL_PAGE_SIZE
.'">'.get_string('showall', '', $matchcount).'</a></div>';
627 print_footer($course);
632 function get_lastaccess_sql($accesssince='') {
633 if (empty($accesssince)) {
636 if ($accesssince == -1) { // never
637 return ' AND ul.timeaccess = 0';
639 return ' AND ul.timeaccess != 0 AND timeaccess < '.$accesssince;