MDL-8857
[moodle-linuxchix.git] / user / index.php
blob1b107b8f0ac77e03fca045e7543e0a80341fbf03
1 <?PHP // $Id$
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
24 if ($contextid) {
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");
31 } else {
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");
39 // not needed anymore
40 unset($contextid);
41 unset($courseid);
43 require_login($course);
45 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
47 if (!has_capability('moodle/course:viewparticipants', $context)) {
48 print_error('nopermissions');
51 $rolenames = array();
53 if ($roles = get_roles_used_in_context($context, true)) {
54 // We should exclude "admin" users (those with "doanything" at site level) because
55 // Otherwise they appear in every participant list
57 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
59 foreach ($roles as $role) {
60 if (isset($doanythingroles[$role->id])) { // Avoid this role (ie admin)
61 unset($roles[$role->id]);
62 continue;
64 $rolenames[$role->id] = strip_tags(format_string($role->name)); // Used in menus etc later on
68 // no roles to display yet?
69 if (empty($rolenames)) {
70 if (has_capability('moodle/user:assign', $context)) {
71 redirect($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id);
72 } else {
73 error ('No participants found for this course');
77 add_to_log($course->id, 'user', 'view all', 'index.php?id='.$course->id, '');
79 $bulkoperations = has_capability('moodle/course:bulkmessaging', $context);
81 $countries = get_list_of_countries();
83 $strnever = get_string('never');
85 $datestring->year = get_string('year');
86 $datestring->years = get_string('years');
87 $datestring->day = get_string('day');
88 $datestring->days = get_string('days');
89 $datestring->hour = get_string('hour');
90 $datestring->hours = get_string('hours');
91 $datestring->min = get_string('min');
92 $datestring->mins = get_string('mins');
93 $datestring->sec = get_string('sec');
94 $datestring->secs = get_string('secs');
96 if ($mode !== NULL) {
97 $SESSION->userindexmode = $fullmode = ($mode == 1);
98 } else if (isset($SESSION->userindexmode)) {
99 $fullmode = $SESSION->userindexmode;
100 } else {
101 $fullmode = false;
104 /// Check to see if groups are being used in this forum
105 /// and if so, set $currentgroup to reflect the current group
107 $groupmode = groupmode($course); // Groups are being used
108 $currentgroup = get_and_set_current_group($course, $groupmode, $group);
110 if (!$currentgroup) { // To make some other functions work better later
111 $currentgroup = NULL;
114 $isseparategroups = ($course->groupmode == SEPARATEGROUPS and $course->groupmodeforce and
115 !has_capability('moodle/site:accessallgroups', $context));
117 if ($isseparategroups and (!$currentgroup) ) {
118 print_header("$course->shortname: ".get_string('participants'), $course->fullname,
119 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> -> ".
120 get_string('participants'), "", "", true, "&nbsp;", navmenu($course));
121 print_heading(get_string("notingroup", "forum"));
122 print_footer($course);
123 exit;
126 // Should use this variable so that we don't break stuff every time a variable is added or changed.
127 $baseurl = $CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'&amp;id='.$course->id.'&amp;group='.$currentgroup.'&amp;perpage='.$perpage.'&amp;accesssince='.$accesssince.'&amp;search='.$search;
129 /// Print headers
131 if ($course->id != SITEID) {
132 print_header("$course->shortname: ".get_string('participants'), $course->fullname,
133 "<a href=\"../course/view.php?id=$course->id\">$course->shortname</a> -> ".
134 get_string('participants'), "", "", true, "&nbsp;", navmenu($course));
135 } else {
136 print_header("$course->shortname: ".get_string('participants'), $course->fullname,
137 get_string('participants'), "", "", true, "&nbsp;", navmenu($course));
141 /// setting up tags
142 if ($course->id == SITEID) {
143 $filtertype = 'site';
144 } else if ($course->id && !$currentgroup) {
145 $filtertype = 'course';
146 $filterselect = $course->id;
147 } else {
148 $filtertype = 'group';
149 $filterselect = $currentgroup;
151 $currenttab = 'participants';
152 $user = $USER;
154 require_once($CFG->dirroot .'/user/tabs.php');
157 /// Get the hidden field list
158 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
159 $hiddenfields = array(); // teachers and admins are allowed to see everything
160 } else {
161 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
165 /// Print settings and things in a table across the top
167 echo '<table class="controls" cellspacing="0"><tr>';
169 /// Print my course menus
170 if ($mycourses = get_my_courses($USER->id)) {
171 echo '<td class="left">';
172 $courselist = array();
173 foreach ($mycourses as $mycourse) {
174 $courselist[$mycourse->id] = $mycourse->shortname;
176 popup_form($CFG->wwwroot.'/user/index.php?roleid='.$roleid.'&amp;sifirst=&amp;silast=&amp;id=',
177 $courselist, 'courseform', $course->id, '', '', '', false, 'self', get_string('mycourses'));
178 echo '</td>';
181 if ($groupmode == VISIBLEGROUPS or ($groupmode and has_capability('moodle/site:accessallgroups', $context))) {
182 if ($groups_names = groups_get_groups_names($course->id)) { //TODO:
183 echo '<td class="left">';
184 print_group_menu($groups_names, $groupmode, $currentgroup, $baseurl);
185 echo '</td>';
189 // get minimum lastaccess for this course and display a dropbox to filter by lastaccess going back this far.
190 // this might not work anymore because you always going to get yourself as the most recent entry? added $USER!=$user ch
191 $minlastaccess = get_field_sql('SELECT min(timeaccess) FROM '.$CFG->prefix.'user_lastaccess WHERE courseid = '.$course->id.' AND timeaccess != 0 AND userid!='.$USER->id);
192 $lastaccess0exists = record_exists('user_lastaccess','courseid',$course->id,'timeaccess',0);
193 $now = usergetmidnight(time());
194 $timeaccess = array();
196 // makes sense for this to go first.
197 $timeoptions[0] = get_string('selectperiod');
199 // days
200 for ($i = 1; $i < 7; $i++) {
201 if (strtotime('-'.$i.' days',$now) >= $minlastaccess) {
202 $timeoptions[strtotime('-'.$i.' days',$now)] = get_string('numdays','moodle',$i);
205 // weeks
206 for ($i = 1; $i < 10; $i++) {
207 if (strtotime('-'.$i.' weeks',$now) >= $minlastaccess) {
208 $timeoptions[strtotime('-'.$i.' weeks',$now)] = get_string('numweeks','moodle',$i);
211 // months
212 for ($i = 2; $i < 12; $i++) {
213 if (strtotime('-'.$i.' months',$now) >= $minlastaccess) {
214 $timeoptions[strtotime('-'.$i.' months',$now)] = get_string('nummonths','moodle',$i);
217 // try a year
218 if (strtotime('-1 year',$now) >= $minlastaccess) {
219 $timeoptions[strtotime('-1 year',$now)] = get_string('lastyear');
222 if (!empty($lastaccess0exists)) {
223 $timeoptions[-1] = get_string('never');
226 if (count($timeoptions) > 1) {
227 echo '<td class="left">';
228 $baseurl = preg_replace('/&amp;accesssince='.$accesssince.'/','',$baseurl);
229 popup_form($baseurl.'&amp;accesssince=',$timeoptions,'timeoptions',$accesssince, '', '', '', false, 'self', get_string('usersnoaccesssince'));
230 echo '</td>';
234 echo '<td class="right">';
235 $formatmenu = array( '0' => get_string('detailedless'),
236 '1' => get_string('detailedmore'));
237 popup_form($baseurl.'&amp;mode=', $formatmenu, 'formatmenu', $fullmode, '', '', '', false, 'self', get_string('userlist'));
238 echo '</td></tr></table>';
240 if ($currentgroup and (!$isseparategroups or has_capability('moodle/site:accessallgroups', $context))) { /// Display info about the group
241 if ($group = groups_get_group($currentgroup)) { //TODO:
242 if (!empty($group->description) or (!empty($group->picture) and empty($group->hidepicture))) {
243 echo '<table class="groupinfobox"><tr><td class="left side picture">';
244 print_group_picture($group, $course->id, true, false, false);
245 echo '</td><td class="content">';
246 echo '<h3>'.$group->name;
247 if (has_capability('moodle/course:managegroups', $context)) {
248 echo '&nbsp;<a title="'.get_string('editgroupprofile').'" href="'.groups_group_edit_url($course->id, $group->id).'">';
249 echo '<img src="'.$CFG->pixpath.'/t/edit.gif" alt="'.get_string('editgroupprofile').'" />';
250 echo '</a>';
252 echo '</h3>';
253 echo format_text($group->description);
254 echo '</td></tr></table>';
260 /// Define a table showing a list of users in the current role selection
262 $tablecolumns = array('userpic', 'fullname');
263 $tableheaders = array(get_string('userpic'), get_string('fullname'));
264 if (!isset($hiddenfields['city'])) {
265 $tablecolumns[] = 'city';
266 $tableheaders[] = get_string('city');
268 if (!isset($hiddenfields['country'])) {
269 $tablecolumns[] = 'country';
270 $tableheaders[] = get_string('country');
272 if (!isset($hiddenfields['lastaccess'])) {
273 $tablecolumns[] = 'lastaccess';
274 $tableheaders[] = get_string('lastaccess');
277 if ($course->enrolperiod) {
278 $tablecolumns[] = 'timeend';
279 $tableheaders[] = get_string('enrolmentend');
282 if ($bulkoperations) {
283 $tablecolumns[] = '';
284 $tableheaders[] = get_string('select');
287 $table = new flexible_table('user-index-participants-'.$course->id);
289 $table->define_columns($tablecolumns);
290 $table->define_headers($tableheaders);
291 $table->define_baseurl($baseurl);
293 $table->sortable(true, 'lastaccess', SORT_DESC);
295 $table->set_attribute('cellspacing', '0');
296 $table->set_attribute('id', 'participants');
297 $table->set_attribute('class', 'generaltable generalbox');
299 $table->set_control_variables(array(
300 TABLE_VAR_SORT => 'ssort',
301 TABLE_VAR_HIDE => 'shide',
302 TABLE_VAR_SHOW => 'sshow',
303 TABLE_VAR_IFIRST => 'sifirst',
304 TABLE_VAR_ILAST => 'silast',
305 TABLE_VAR_PAGE => 'spage'
307 $table->setup();
310 // we are looking for all users with this role assigned in this context or higher
311 if ($usercontexts = get_parent_contexts($context)) {
312 $listofcontexts = '('.implode(',', $usercontexts).')';
313 } else {
314 $listofcontexts = '('.$sitecontext->id.')'; // must be site
316 if ($roleid) {
317 $selectrole = " AND r.roleid = $roleid ";
318 } else {
319 $selectrole = " ";
321 $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
322 $select .= $course->enrolperiod?', r.timeend ':'';
324 $from = "FROM {$CFG->prefix}user u INNER JOIN
325 {$CFG->prefix}role_assignments r on u.id=r.userid LEFT OUTER JOIN
326 {$CFG->prefix}user_lastaccess ul on (r.userid=ul.userid and ul.courseid = $course->id)";
328 $hiddensql = has_capability('moodle/role:viewhiddenassigns', $context)? '':' AND r.hidden = 0 ';
330 // excluse users with these admin role assignments
331 if ($doanythingroles) {
332 $adminroles = 'AND r.roleid NOT IN (';
334 foreach ($doanythingroles as $aroleid=>$role) {
335 $adminroles .= "$aroleid,";
337 $adminroles = rtrim($adminroles,",");
338 $adminroles .= ')';
339 } else {
340 $adminroles = '';
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'
350 $adminroles
351 $hiddensql ";
352 $where .= get_lastaccess_sql($accesssince);
354 $wheresearch = '';
356 if (!empty($search)) {
357 $LIKE = sql_ilike();
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();
377 } else {
378 $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&amp;sifirst=&amp;silast=&amp;roleid=", $rolenames,
396 'rolesform', $roleid, '');
397 echo '</div>';
400 if ($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 = 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.'&amp;contextid='.$context->id.'">';
409 $heading .= '<img src="'.$CFG->pixpath.'/i/edit.gif" class="icon" alt="" /></a>';
411 print_heading($heading, 'center', 3);
412 } else {
413 if ($matchcount < $totalcount) {
414 print_heading(get_string('allparticipants').': '.$matchcount.'/'.$totalcount, '', 3);
415 } else {
416 print_heading(get_string('allparticipants').': '.$matchcount, '', 3);
421 if ($bulkoperations) {
422 echo '
423 <script type="text/javascript">
424 //<![CDATA[
425 function checksubmit(form) {
426 var destination = form.formaction.options[form.formaction.selectedIndex].value;
427 if (destination == "" || !checkchecked(form)) {
428 form.formaction.selectedIndex = 0;
429 return false;
430 } else {
431 return true;
435 function checkchecked(form) {
436 var inputs = document.getElementsByTagName(\'INPUT\');
437 var checked = false;
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) {
441 checked = true;
444 return checked;
446 //]]>
447 </script>
449 echo '<form action="action_redir.php" method="post" id="participantsform" onsubmit="return checksubmit(this);">';
450 echo '<div>';
451 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
454 if ($CFG->longtimenosee > 0 && $CFG->longtimenosee < 1000 && $totalcount > 0) {
455 echo '<p id="longtimenosee">('.get_string('unusedaccounts', '', $CFG->longtimenosee).')</p>';
458 if ($fullmode) { // Print simple listing
459 if ($totalcount < 1) {
460 print_heading(get_string('nothingtodisplay'));
461 } else {
462 if ($totalcount > $perpage) {
464 $firstinitial = $table->get_initial_first();
465 $lastinitial = $table->get_initial_last();
466 $strall = get_string('all');
467 $alpha = explode(',', get_string('alphabet'));
469 // Bar of first initials
471 echo '<div class="initialbar firstinitial">'.get_string('firstname').' : ';
472 if(!empty($firstinitial)) {
473 echo '<a href="'.$baseurl.'&amp;sifirst=">'.$strall.'</a>';
474 } else {
475 echo '<strong>'.$strall.'</strong>';
477 foreach ($alpha as $letter) {
478 if ($letter == $firstinitial) {
479 echo ' <strong>'.$letter.'</strong>';
480 } else {
481 echo ' <a href="'.$baseurl.'&amp;sifirst='.$letter.'">'.$letter.'</a>';
484 echo '</div>';
486 // Bar of last initials
488 echo '<div class="initialbar lastinitial">'.get_string('lastname').' : ';
489 if(!empty($lastinitial)) {
490 echo '<a href="'.$baseurl.'&amp;silast=">'.$strall.'</a>';
491 } else {
492 echo '<strong>'.$strall.'</strong>';
494 foreach ($alpha as $letter) {
495 if ($letter == $lastinitial) {
496 echo ' <strong>'.$letter.'</strong>';
497 } else {
498 echo ' <a href="'.$baseurl.'&amp;silast='.$letter.'">'.$letter.'</a>';
501 echo '</div>';
503 print_paging_bar($matchcount, intval($table->get_page_start() / $perpage), $perpage, $baseurl.'&amp;', 'spage');
506 if ($matchcount > 0) {
507 foreach ($userlist as $user) {
508 print_user($user, $course, $bulkoperations);
511 } else {
512 print_heading(get_string('nothingtodisplay'));
516 } else {
517 $countrysort = (strpos($sort, 'country') !== false);
518 $timeformat = get_string('strftimedate');
521 if (!empty($userlist)) {
522 foreach ($userlist as $user) {
523 if ($user->hidden) {
524 // if the assignment is hidden, display icon
525 $hidden = "<img src=\"{$CFG->pixpath}/t/hide.gif\" alt=\"".get_string('hiddenassign')."\" class=\"hide-show-image\"/>";
526 } else {
527 $hidden = '';
530 if ($user->lastaccess) {
531 $lastaccess = format_time(time() - $user->lastaccess, $datestring);
532 } else {
533 $lastaccess = $strnever;
536 if (empty($user->country)) {
537 $country = '';
539 } else {
540 if($countrysort) {
541 $country = '('.$user->country.') '.$countries[$user->country];
543 else {
544 $country = $countries[$user->country];
548 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
550 if ($piclink = ($USER->id == $user->id || has_capability('moodle/user:viewdetails', $context) ||has_capability('moodle/user:viewdetails', $context))) {
551 $profilelink = '<strong><a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.fullname($user).'</a></strong>';
552 } else {
553 $profilelink = '<strong>'.fullname($user).'</strong>';
556 $data = array (
557 print_user_picture($user->id, $course->id, $user->picture, false, true, $piclink),
558 $profilelink);
560 if (!isset($hiddenfields['city'])) {
561 $data[] = $user->city;
563 if (!isset($hiddenfields['country'])) {
564 $data[] = $country;
566 if (!isset($hiddenfields['lastaccess'])) {
567 $data[] = $lastaccess;
569 if ($course->enrolperiod) {
570 if ($user->timeend) {
571 $data[] = userdate($user->timeend, $timeformat);
572 } else {
573 $data[] = get_string('unlimited');
576 if ($bulkoperations) {
577 $data[] = '<input type="checkbox" name="user'.$user->id.'" />';
579 $table->add_data($data);
584 $table->print_html();
588 if ($bulkoperations) {
589 echo '<br /><div class="buttons">';
590 echo '<input type="button" onclick="checkall()" value="'.get_string('selectall').'" /> ';
591 echo '<input type="button" onclick="checknone()" value="'.get_string('deselectall').'" /> ';
592 $displaylist['messageselect.php'] = get_string('messageselectadd');
593 if ($course->enrolperiod) {
594 $displaylist['extendenrol.php'] = get_string('extendenrol');
596 helpbutton("participantswithselectedusers", get_string("withselectedusers"));
597 choose_from_menu ($displaylist, "formaction", "", get_string("withselectedusers"), "if(checksubmit(this.form))this.form.submit();", "");
598 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
599 echo '<input type="submit" value="' . get_string('ok') . '" />';
600 echo '</div>';
601 echo '</div>';
602 echo '</form>';
605 if ($bulkoperations && $totalcount > ($perpage*3)) {
606 echo '<form action="index.php"><div><input type="hidden" name="id" value="'.$course->id.'" />'.get_string('search').':&nbsp;'."\n";
607 echo '<input type="text" name="search" value="'.$search.'" />&nbsp;<input type="submit" value="'.get_string('search').'" /></div></form>'."\n";
610 if ($perpage == SHOW_ALL_PAGE_SIZE) {
611 echo '<div id="showall"><a href="'.$baseurl.'&amp;perpage='.DEFAULT_PAGE_SIZE.'">'.get_string('showperpage', '', DEFAULT_PAGE_SIZE).'</a></div>';
613 } else if ($matchcount > 0 && $perpage < $matchcount) {
614 echo '<div id="showall"><a href="'.$baseurl.'&amp;perpage='.SHOW_ALL_PAGE_SIZE.'">'.get_string('showall', '', $matchcount).'</a></div>';
617 print_footer($course);
622 function get_lastaccess_sql($accesssince='') {
623 if (empty($accesssince)) {
624 return '';
626 if ($accesssince == -1) { // never
627 return ' AND ul.timeaccess = 0';
628 } else {
629 return ' AND ul.timeaccess != 0 AND timeaccess < '.$accesssince;