weekly release 3.1dev
[moodle.git] / user / index.php
CommitLineData
aa6c1ced 1<?php
a2ed6e69
SH
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Lists all the users within a given course.
19 *
20 * @copyright 1999 Martin Dougiamas http://dougiamas.com
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 * @package core_user
23 */
24
25require_once('../config.php');
0ff203b6 26require_once($CFG->dirroot.'/user/lib.php');
a2ed6e69
SH
27require_once($CFG->libdir.'/tablelib.php');
28require_once($CFG->libdir.'/filelib.php');
29
30define('USER_SMALL_CLASS', 20); // Below this is considered small.
31define('USER_LARGE_CLASS', 200); // Above this is considered large.
32define('DEFAULT_PAGE_SIZE', 20);
33define('SHOW_ALL_PAGE_SIZE', 5000);
34define('MODE_BRIEF', 0);
35define('MODE_USERDETAILS', 1);
36
37$page = optional_param('page', 0, PARAM_INT); // Which page to show.
38$perpage = optional_param('perpage', DEFAULT_PAGE_SIZE, PARAM_INT); // How many per page.
39$mode = optional_param('mode', null, PARAM_INT); // Use the MODE_ constants.
40$accesssince = optional_param('accesssince', 0, PARAM_INT); // Filter by last access. -1 = never.
41$search = optional_param('search', '', PARAM_RAW); // Make sure it is processed with p() or s() when sending to output!
42$roleid = optional_param('roleid', 0, PARAM_INT); // Optional roleid, 0 means all enrolled users (or all on the frontpage).
43$contextid = optional_param('contextid', 0, PARAM_INT); // One of this or.
44$courseid = optional_param('id', 0, PARAM_INT); // This are required.
45
46$PAGE->set_url('/user/index.php', array(
47 'page' => $page,
48 'perpage' => $perpage,
49 'mode' => $mode,
50 'accesssince' => $accesssince,
51 'search' => $search,
52 'roleid' => $roleid,
53 'contextid' => $contextid,
54 'id' => $courseid));
55
56if ($contextid) {
57 $context = context::instance_by_id($contextid, MUST_EXIST);
58 if ($context->contextlevel != CONTEXT_COURSE) {
59 print_error('invalidcontext');
60 }
61 $course = $DB->get_record('course', array('id' => $context->instanceid), '*', MUST_EXIST);
62} else {
63 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
64 $context = context_course::instance($course->id, MUST_EXIST);
65}
66// Not needed anymore.
67unset($contextid);
68unset($courseid);
f9903ed0 69
a2ed6e69 70require_login($course);
f9903ed0 71
a2ed6e69
SH
72$systemcontext = context_system::instance();
73$isfrontpage = ($course->id == SITEID);
f9903ed0 74
a2ed6e69 75$frontpagectx = context_course::instance(SITEID);
4f0c2d00 76
a2ed6e69
SH
77if ($isfrontpage) {
78 $PAGE->set_pagelayout('admin');
79 require_capability('moodle/site:viewparticipants', $systemcontext);
80} else {
81 $PAGE->set_pagelayout('incourse');
82 require_capability('moodle/course:viewparticipants', $context);
83}
224aa44a 84
a2ed6e69 85$rolenamesurl = new moodle_url("$CFG->wwwroot/user/index.php?contextid=$context->id&sifirst=&silast=");
6d3c57f4 86
a2ed6e69
SH
87$rolenames = role_fix_names(get_profile_roles($context), $context, ROLENAME_ALIAS, true);
88if ($isfrontpage) {
89 $rolenames[0] = get_string('allsiteusers', 'role');
90} else {
91 $rolenames[0] = get_string('allparticipants');
92}
d7270311 93
a2ed6e69
SH
94// Make sure other roles may not be selected by any means.
95if (empty($rolenames[$roleid])) {
96 print_error('noparticipants');
97}
5f9e296a 98
a2ed6e69
SH
99// No roles to display yet?
100// frontpage course is an exception, on the front page course we should display all users.
101if (empty($rolenames) && !$isfrontpage) {
102 if (has_capability('moodle/role:assign', $context)) {
103 redirect($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id);
104 } else {
4f0c2d00 105 print_error('noparticipants');
5f9e296a 106 }
a2ed6e69 107}
5f9e296a 108
0ff203b6
JL
109// Trigger events.
110user_list_view($course, $context);
a2ed6e69
SH
111
112$bulkoperations = has_capability('moodle/course:bulkmessaging', $context);
113
114$countries = get_string_manager()->get_list_of_countries();
115
116$strnever = get_string('never');
117
118$datestring = new stdClass();
119$datestring->year = get_string('year');
120$datestring->years = get_string('years');
121$datestring->day = get_string('day');
122$datestring->days = get_string('days');
123$datestring->hour = get_string('hour');
124$datestring->hours = get_string('hours');
125$datestring->min = get_string('min');
126$datestring->mins = get_string('mins');
127$datestring->sec = get_string('sec');
128$datestring->secs = get_string('secs');
129
130if ($mode !== null) {
131 $mode = (int)$mode;
132 $SESSION->userindexmode = $mode;
133} else if (isset($SESSION->userindexmode)) {
134 $mode = (int)$SESSION->userindexmode;
135} else {
136 $mode = MODE_BRIEF;
137}
41d7209c 138
a2ed6e69
SH
139// Check to see if groups are being used in this course
140// and if so, set $currentgroup to reflect the current group.
ff3caf30 141
a2ed6e69
SH
142$groupmode = groups_get_course_groupmode($course); // Groups are being used.
143$currentgroup = groups_get_course_group($course, true);
ff3caf30 144
a2ed6e69
SH
145if (!$currentgroup) { // To make some other functions work better later.
146 $currentgroup = null;
147}
ff3caf30 148
a2ed6e69 149$isseparategroups = ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context));
ff3caf30 150
a2ed6e69
SH
151$PAGE->set_title("$course->shortname: ".get_string('participants'));
152$PAGE->set_heading($course->fullname);
153$PAGE->set_pagetype('course-view-' . $course->format);
154$PAGE->add_body_class('path-user'); // So we can style it independently.
155$PAGE->set_other_editing_capability('moodle/course:manageactivities');
2cb2ce61 156
a2ed6e69 157echo $OUTPUT->header();
4e1f6047 158echo $OUTPUT->heading(get_string('participants'));
caa8363f 159
a2ed6e69 160echo '<div class="userlist">';
0be6f678 161
a2ed6e69
SH
162if ($isseparategroups and (!$currentgroup) ) {
163 // The user is not in the group so show message and exit.
164 echo $OUTPUT->heading(get_string("notingroup"));
165 echo $OUTPUT->footer();
166 exit;
167}
99cca847 168
ff3caf30 169
a2ed6e69
SH
170// Should use this variable so that we don't break stuff every time a variable is added or changed.
171$baseurl = new moodle_url('/user/index.php', array(
172 'contextid' => $context->id,
173 'roleid' => $roleid,
174 'id' => $course->id,
175 'perpage' => $perpage,
176 'accesssince' => $accesssince,
177 'search' => s($search)));
178
179// Setting up tags.
180if ($course->id == SITEID) {
181 $filtertype = 'site';
182} else if ($course->id && !$currentgroup) {
183 $filtertype = 'course';
184 $filterselect = $course->id;
185} else {
186 $filtertype = 'group';
187 $filterselect = $currentgroup;
188}
03d9401e 189
1242eb8f 190
03d9401e 191
a2ed6e69
SH
192// Get the hidden field list.
193if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
194 $hiddenfields = array(); // Teachers and admins are allowed to see everything.
195} else {
c6b44cb4 196 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
a2ed6e69 197}
1242eb8f 198
a2ed6e69
SH
199if (isset($hiddenfields['lastaccess'])) {
200 // Do not allow access since filtering.
201 $accesssince = 0;
202}
3468d58a 203
a2ed6e69
SH
204// Print settings and things in a table across the top.
205$controlstable = new html_table();
206$controlstable->attributes['class'] = 'controls';
207$controlstable->cellspacing = 0;
208$controlstable->data[] = new html_table_row();
209
210// Print my course menus.
211if ($mycourses = enrol_get_my_courses()) {
212 $courselist = array();
213 $popupurl = new moodle_url('/user/index.php?roleid='.$roleid.'&sifirst=&silast=');
214 foreach ($mycourses as $mycourse) {
215 $coursecontext = context_course::instance($mycourse->id);
216 $courselist[$mycourse->id] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
217 }
218 if (has_capability('moodle/site:viewparticipants', $systemcontext)) {
219 unset($courselist[SITEID]);
220 $courselist = array(SITEID => format_string($SITE->shortname, true, array('context' => $systemcontext))) + $courselist;
221 }
222 $select = new single_select($popupurl, 'id', $courselist, $course->id, null, 'courseform');
223 $select->set_label(get_string('mycourses'));
224 $controlstable->data[0]->cells[] = $OUTPUT->render($select);
225}
bbbf2d40 226
24c3db91
DP
227if ($groupmenu = groups_print_course_menu($course, $baseurl->out(), true)) {
228 $controlstable->data[0]->cells[] = $groupmenu;
229}
a2ed6e69
SH
230
231if (!isset($hiddenfields['lastaccess'])) {
232 // Get minimum lastaccess for this course and display a dropbox to filter by lastaccess going back this far.
233 // We need to make it diferently for normal courses and site course.
234 if (!$isfrontpage) {
235 $minlastaccess = $DB->get_field_sql('SELECT min(timeaccess)
236 FROM {user_lastaccess}
237 WHERE courseid = ?
238 AND timeaccess != 0', array($course->id));
239 $lastaccess0exists = $DB->record_exists('user_lastaccess', array('courseid' => $course->id, 'timeaccess' => 0));
240 } else {
241 $minlastaccess = $DB->get_field_sql('SELECT min(lastaccess)
242 FROM {user}
243 WHERE lastaccess != 0');
244 $lastaccess0exists = $DB->record_exists('user', array('lastaccess' => 0));
7da0af9f 245 }
87a13824 246
a2ed6e69
SH
247 $now = usergetmidnight(time());
248 $timeaccess = array();
249 $baseurl->remove_params('accesssince');
87a13824 250
a2ed6e69
SH
251 // Makes sense for this to go first.
252 $timeoptions[0] = get_string('selectperiod');
87a13824 253
a2ed6e69
SH
254 // Days.
255 for ($i = 1; $i < 7; $i++) {
256 if (strtotime('-'.$i.' days', $now) >= $minlastaccess) {
257 $timeoptions[strtotime('-'.$i.' days', $now)] = get_string('numdays', 'moodle', $i);
ca792680 258 }
a2ed6e69
SH
259 }
260 // Weeks.
261 for ($i = 1; $i < 10; $i++) {
262 if (strtotime('-'.$i.' weeks', $now) >= $minlastaccess) {
263 $timeoptions[strtotime('-'.$i.' weeks', $now)] = get_string('numweeks', 'moodle', $i);
5ff311f0 264 }
a2ed6e69
SH
265 }
266 // Months.
267 for ($i = 2; $i < 12; $i++) {
268 if (strtotime('-'.$i.' months', $now) >= $minlastaccess) {
269 $timeoptions[strtotime('-'.$i.' months', $now)] = get_string('nummonths', 'moodle', $i);
31b71336 270 }
a2ed6e69
SH
271 }
272 // Try a year.
273 if (strtotime('-1 year', $now) >= $minlastaccess) {
274 $timeoptions[strtotime('-1 year', $now)] = get_string('lastyear');
275 }
87a13824 276
a2ed6e69
SH
277 if (!empty($lastaccess0exists)) {
278 $timeoptions[-1] = get_string('never');
279 }
87a13824 280
a2ed6e69
SH
281 if (count($timeoptions) > 1) {
282 $select = new single_select($baseurl, 'accesssince', $timeoptions, $accesssince, null, 'timeoptions');
283 $select->set_label(get_string('usersnoaccesssince'));
284 $controlstable->data[0]->cells[] = $OUTPUT->render($select);
77c645df 285 }
a2ed6e69 286}
87a13824 287
a2ed6e69
SH
288$formatmenu = array( '0' => get_string('brief'),
289 '1' => get_string('userdetails'));
290$select = new single_select($baseurl, 'mode', $formatmenu, $mode, null, 'formatmenu');
291$select->set_label(get_string('userlist'));
292$userlistcell = new html_table_cell();
293$userlistcell->attributes['class'] = 'right';
294$userlistcell->text = $OUTPUT->render($select);
295$controlstable->data[0]->cells[] = $userlistcell;
296
297echo html_writer::table($controlstable);
298
299if ($currentgroup and (!$isseparategroups or has_capability('moodle/site:accessallgroups', $context))) {
300 // Display info about the group.
301 if ($group = groups_get_group($currentgroup)) {
302 if (!empty($group->description) or (!empty($group->picture) and empty($group->hidepicture))) {
303 $groupinfotable = new html_table();
304 $groupinfotable->attributes['class'] = 'groupinfobox';
305 $picturecell = new html_table_cell();
306 $picturecell->attributes['class'] = 'left side picture';
307 $picturecell->text = print_group_picture($group, $course->id, true, true, false);
308
309 $contentcell = new html_table_cell();
310 $contentcell->attributes['class'] = 'content';
311
312 $contentheading = $group->name;
313 if (has_capability('moodle/course:managegroups', $context)) {
314 $aurl = new moodle_url('/group/group.php', array('id' => $group->id, 'courseid' => $group->courseid));
315 $contentheading .= '&nbsp;' . $OUTPUT->action_icon($aurl, new pix_icon('t/edit', get_string('editgroupprofile')));
316 }
8bdc9cac 317
a2ed6e69
SH
318 $group->description = file_rewrite_pluginfile_urls($group->description, 'pluginfile.php', $context->id, 'group',
319 'description', $group->id);
320 if (!isset($group->descriptionformat)) {
321 $group->descriptionformat = FORMAT_MOODLE;
ff3caf30 322 }
a2ed6e69
SH
323 $options = array('overflowdiv' => true);
324 $formatteddesc = format_text($group->description, $group->descriptionformat, $options);
325 $contentcell->text = $OUTPUT->heading($contentheading, 3) . $formatteddesc;
326 $groupinfotable->data[] = new html_table_row(array($picturecell, $contentcell));
327 echo html_writer::table($groupinfotable);
ff3caf30 328 }
329 }
a2ed6e69 330}
ff3caf30 331
a2ed6e69
SH
332// Define a table showing a list of users in the current role selection.
333$tablecolumns = array();
334$tableheaders = array();
335if ($bulkoperations && $mode === MODE_BRIEF) {
336 $tablecolumns[] = 'select';
337 $tableheaders[] = get_string('select');
338}
339$tablecolumns[] = 'userpic';
340$tablecolumns[] = 'fullname';
c238e1e2 341
a2ed6e69
SH
342$extrafields = get_extra_user_fields($context);
343$tableheaders[] = get_string('userpic');
344$tableheaders[] = get_string('fullnameuser');
77c645df 345
a2ed6e69
SH
346if ($mode === MODE_BRIEF) {
347 foreach ($extrafields as $field) {
348 $tablecolumns[] = $field;
349 $tableheaders[] = get_user_field_name($field);
77c645df 350 }
a2ed6e69
SH
351}
352if ($mode === MODE_BRIEF && !isset($hiddenfields['city'])) {
353 $tablecolumns[] = 'city';
354 $tableheaders[] = get_string('city');
355}
356if ($mode === MODE_BRIEF && !isset($hiddenfields['country'])) {
357 $tablecolumns[] = 'country';
358 $tableheaders[] = get_string('country');
359}
360if (!isset($hiddenfields['lastaccess'])) {
361 $tablecolumns[] = 'lastaccess';
e89682d8
DC
362 if ($course->id == SITEID) {
363 // Exception case for viewing participants on site home.
364 $tableheaders[] = get_string('lastsiteaccess');
365 } else {
366 $tableheaders[] = get_string('lastcourseaccess');
367 }
a2ed6e69 368}
77c645df 369
a2ed6e69
SH
370if ($bulkoperations && $mode === MODE_USERDETAILS) {
371 $tablecolumns[] = 'select';
372 $tableheaders[] = get_string('select');
373}
0be6f678 374
a2ed6e69
SH
375$table = new flexible_table('user-index-participants-'.$course->id);
376$table->define_columns($tablecolumns);
377$table->define_headers($tableheaders);
378$table->define_baseurl($baseurl->out());
5ff311f0 379
28d27e85 380if (!isset($hiddenfields['lastaccess'])) {
381 $table->sortable(true, 'lastaccess', SORT_DESC);
a2ed6e69
SH
382} else {
383 $table->sortable(true, 'firstname', SORT_ASC);
384}
4f0c2d00 385
a2ed6e69
SH
386$table->no_sorting('roles');
387$table->no_sorting('groups');
388$table->no_sorting('groupings');
389$table->no_sorting('select');
390
391$table->set_attribute('cellspacing', '0');
392$table->set_attribute('id', 'participants');
393$table->set_attribute('class', 'generaltable generalbox');
394
395$table->set_control_variables(array(
396 TABLE_VAR_SORT => 'ssort',
397 TABLE_VAR_HIDE => 'shide',
398 TABLE_VAR_SHOW => 'sshow',
399 TABLE_VAR_IFIRST => 'sifirst',
400 TABLE_VAR_ILAST => 'silast',
401 TABLE_VAR_PAGE => 'spage'
402 ));
403$table->setup();
404
405list($esql, $params) = get_enrolled_sql($context, null, $currentgroup, true);
406$joins = array("FROM {user} u");
407$wheres = array();
408
368f0bf8
DC
409$userfields = array('username', 'email', 'city', 'country', 'lang', 'timezone', 'maildisplay');
410$mainuserfields = user_picture::fields('u', $userfields);
411$extrasql = get_extra_user_fields_sql($context, 'u', '', $userfields);
a2ed6e69
SH
412
413if ($isfrontpage) {
414 $select = "SELECT $mainuserfields, u.lastaccess$extrasql";
415 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Everybody on the frontpage usually.
416 if ($accesssince) {
417 $wheres[] = get_user_lastaccess_sql($accesssince);
418 }
419
420} else {
421 $select = "SELECT $mainuserfields, COALESCE(ul.timeaccess, 0) AS lastaccess$extrasql";
422 $joins[] = "JOIN ($esql) e ON e.id = u.id"; // Course enrolled users only.
423 $joins[] = "LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)"; // Not everybody accessed course yet.
424 $params['courseid'] = $course->id;
425 if ($accesssince) {
426 $wheres[] = get_course_lastaccess_sql($accesssince);
165088f6 427 }
a2ed6e69 428}
5f9e296a 429
a2ed6e69
SH
430// Performance hacks - we preload user contexts together with accounts.
431$ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
432$ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
433$params['contextlevel'] = CONTEXT_USER;
434$select .= $ccselect;
435$joins[] = $ccjoin;
c0527567 436
4f0c2d00 437
a2ed6e69
SH
438// Limit list to users with some role only.
439if ($roleid) {
419d1abd
DW
440 // We want to query both the current context and parent contexts.
441 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
442
a2ed6e69 443 $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid $relatedctxsql)";
419d1abd 444 $params = array_merge($params, array('roleid' => $roleid), $relatedctxparams);
a2ed6e69 445}
0be6f678 446
a2ed6e69
SH
447$from = implode("\n", $joins);
448if ($wheres) {
449 $where = "WHERE " . implode(" AND ", $wheres);
450} else {
451 $where = "";
452}
4f0c2d00 453
a2ed6e69 454$totalcount = $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
77c645df 455
a2ed6e69
SH
456if (!empty($search)) {
457 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
458 $wheres[] = "(". $DB->sql_like($fullname, ':search1', false, false) .
459 " OR ". $DB->sql_like('email', ':search2', false, false) .
460 " OR ". $DB->sql_like('idnumber', ':search3', false, false) .") ";
461 $params['search1'] = "%$search%";
462 $params['search2'] = "%$search%";
463 $params['search3'] = "%$search%";
464}
77c645df 465
a2ed6e69
SH
466list($twhere, $tparams) = $table->get_sql_where();
467if ($twhere) {
468 $wheres[] = $twhere;
469 $params = array_merge($params, $tparams);
470}
77c645df 471
a2ed6e69
SH
472$from = implode("\n", $joins);
473if ($wheres) {
474 $where = "WHERE " . implode(" AND ", $wheres);
475} else {
476 $where = "";
477}
77c645df 478
a2ed6e69
SH
479if ($table->get_sql_sort()) {
480 $sort = ' ORDER BY '.$table->get_sql_sort();
481} else {
482 $sort = '';
483}
77c645df 484
a2ed6e69 485$matchcount = $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
77c645df 486
a2ed6e69
SH
487$table->initialbars(true);
488$table->pagesize($perpage, $matchcount);
77c645df 489
a2ed6e69
SH
490// List of users at the current visible page - paging makes it relatively short.
491$userlist = $DB->get_recordset_sql("$select $from $where $sort", $params, $table->get_page_start(), $table->get_page_size());
3e219038 492
a2ed6e69
SH
493// If there are multiple Roles in the course, then show a drop down menu for switching.
494if (count($rolenames) > 1) {
495 echo '<div class="rolesform">';
32bd11cb
BB
496 echo $OUTPUT->single_select($rolenamesurl, 'roleid', $rolenames, $roleid, null,
497 'rolesform', array('label' => get_string('currentrole', 'role')));
a2ed6e69 498 echo '</div>';
5f9e296a 499
a2ed6e69
SH
500} else if (count($rolenames) == 1) {
501 // When all users with the same role - print its name.
502 echo '<div class="rolesform">';
503 echo get_string('role').get_string('labelsep', 'langconfig');
504 $rolename = reset($rolenames);
505 echo $rolename;
506 echo '</div>';
507}
3e219038 508
a2ed6e69
SH
509if ($roleid > 0) {
510 $a = new stdClass();
511 $a->number = $totalcount;
512 $a->role = $rolenames[$roleid];
513 $heading = format_string(get_string('xuserswiththerole', 'role', $a));
f642a21a 514
a2ed6e69
SH
515 if ($currentgroup and $group) {
516 $a->group = $group->name;
517 $heading .= ' ' . format_string(get_string('ingroup', 'role', $a));
518 }
f642a21a 519
a2ed6e69
SH
520 if ($accesssince) {
521 $a->timeperiod = $timeoptions[$accesssince];
522 $heading .= ' ' . format_string(get_string('inactiveformorethan', 'role', $a));
523 }
f642a21a 524
a2ed6e69 525 $heading .= ": $a->number";
b85b25eb 526
a2ed6e69
SH
527 if (user_can_assign($context, $roleid)) {
528 $headingurl = new moodle_url($CFG->wwwroot . '/' . $CFG->admin . '/roles/assign.php',
529 array('roleid' => $roleid, 'contextid' => $context->id));
530 $heading .= $OUTPUT->action_icon($headingurl, new pix_icon('t/edit', get_string('edit')));
531 }
532 echo $OUTPUT->heading($heading, 3);
533} else {
534 if ($course->id != SITEID && has_capability('moodle/course:enrolreview', $context)) {
535 $editlink = $OUTPUT->action_icon(new moodle_url('/enrol/users.php', array('id' => $course->id)),
536 new pix_icon('t/edit', get_string('edit')));
3e219038 537 } else {
a2ed6e69 538 $editlink = '';
3e219038 539 }
a2ed6e69
SH
540 if ($course->id == SITEID and $roleid < 0) {
541 $strallparticipants = get_string('allsiteusers', 'role');
542 } else {
543 $strallparticipants = get_string('allparticipants');
544 }
545 if ($matchcount < $totalcount) {
546 echo $OUTPUT->heading($strallparticipants.get_string('labelsep', 'langconfig').$matchcount.'/'.$totalcount . $editlink, 3);
547 } else {
548 echo $OUTPUT->heading($strallparticipants.get_string('labelsep', 'langconfig').$matchcount . $editlink, 3);
549 }
550}
3e219038 551
77c645df 552
a2ed6e69
SH
553if ($bulkoperations) {
554 echo '<form action="action_redir.php" method="post" id="participantsform">';
555 echo '<div>';
556 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
557 echo '<input type="hidden" name="returnto" value="'.s($PAGE->url->out(false)).'" />';
558}
77c645df 559
a2ed6e69
SH
560if ($mode === MODE_USERDETAILS) { // Print simple listing.
561 if ($totalcount < 1) {
562 echo $OUTPUT->heading(get_string('nothingtodisplay'));
563 } else {
564 if ($totalcount > $perpage) {
77c645df 565
a2ed6e69
SH
566 $firstinitial = $table->get_initial_first();
567 $lastinitial = $table->get_initial_last();
568 $strall = get_string('all');
c6b44cb4 569 $alpha = explode(',', get_string('alphabet', 'langconfig'));
77c645df 570
a2ed6e69 571 // Bar of first initials.
77c645df 572
a2ed6e69
SH
573 echo '<div class="initialbar firstinitial">'.get_string('firstname').' : ';
574 if (!empty($firstinitial)) {
575 echo '<a href="'.$baseurl->out().'&amp;sifirst=">'.$strall.'</a>';
576 } else {
577 echo '<strong>'.$strall.'</strong>';
578 }
579 foreach ($alpha as $letter) {
580 if ($letter == $firstinitial) {
581 echo ' <strong>'.$letter.'</strong>';
77c645df 582 } else {
a2ed6e69 583 echo ' <a href="'.$baseurl->out().'&amp;sifirst='.$letter.'">'.$letter.'</a>';
ee4a52c5 584 }
a2ed6e69
SH
585 }
586 echo '</div>';
77c645df 587
a2ed6e69 588 // Bar of last initials.
77c645df 589
a2ed6e69
SH
590 echo '<div class="initialbar lastinitial">'.get_string('lastname').' : ';
591 if (!empty($lastinitial)) {
592 echo '<a href="'.$baseurl->out().'&amp;silast=">'.$strall.'</a>';
593 } else {
594 echo '<strong>'.$strall.'</strong>';
595 }
596 foreach ($alpha as $letter) {
597 if ($letter == $lastinitial) {
598 echo ' <strong>'.$letter.'</strong>';
77c645df 599 } else {
a2ed6e69 600 echo ' <a href="'.$baseurl->out().'&amp;silast='.$letter.'">'.$letter.'</a>';
ee4a52c5 601 }
77c645df 602 }
a2ed6e69 603 echo '</div>';
77c645df 604
a2ed6e69
SH
605 $pagingbar = new paging_bar($matchcount, intval($table->get_page_start() / $perpage), $perpage, $baseurl);
606 $pagingbar->pagevar = 'spage';
607 echo $OUTPUT->render($pagingbar);
608 }
609
610 if ($matchcount > 0) {
611 $usersprinted = array();
612 foreach ($userlist as $user) {
613 if (in_array($user->id, $usersprinted)) { // Prevent duplicates by r.hidden - MDL-13935.
614 continue;
615 }
616 $usersprinted[] = $user->id; // Add new user to the array of users printed.
1f807bc4 617
a2ed6e69 618 context_helper::preload_from_record($user);
c351150f 619
a2ed6e69
SH
620 $context = context_course::instance($course->id);
621 $usercontext = context_user::instance($user->id);
c351150f 622
a2ed6e69 623 $countries = get_string_manager()->get_list_of_countries();
c351150f 624
a2ed6e69
SH
625 // Get the hidden field list.
626 if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
627 $hiddenfields = array();
628 } else {
c6b44cb4 629 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
a2ed6e69
SH
630 }
631 $table = new html_table();
632 $table->attributes['class'] = 'userinfobox';
c351150f 633
a2ed6e69
SH
634 $row = new html_table_row();
635 $row->cells[0] = new html_table_cell();
636 $row->cells[0]->attributes['class'] = 'left side';
f2f085ee 637
a2ed6e69
SH
638 $row->cells[0]->text = $OUTPUT->user_picture($user, array('size' => 100, 'courseid' => $course->id));
639 $row->cells[1] = new html_table_cell();
640 $row->cells[1]->attributes['class'] = 'content';
c351150f 641
a2ed6e69
SH
642 $row->cells[1]->text = $OUTPUT->container(fullname($user, has_capability('moodle/site:viewfullnames', $context)), 'username');
643 $row->cells[1]->text .= $OUTPUT->container_start('info');
c351150f 644
a2ed6e69
SH
645 if (!empty($user->role)) {
646 $row->cells[1]->text .= get_string('role').get_string('labelsep', 'langconfig').$user->role.'<br />';
647 }
648 if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguestuser()) or
649 has_capability('moodle/course:viewhiddenuserfields', $context) or
650 in_array('email', $extrafields) or ($user->id == $USER->id)) {
651 $row->cells[1]->text .= get_string('email').get_string('labelsep', 'langconfig').html_writer::link("mailto:$user->email", $user->email) . '<br />';
652 }
653 foreach ($extrafields as $field) {
654 if ($field === 'email') {
655 // Skip email because it was displayed with different logic above
656 // because this page is intended for students too.
657 continue;
c351150f 658 }
a2ed6e69
SH
659 $row->cells[1]->text .= get_user_field_name($field) .
660 get_string('labelsep', 'langconfig') . s($user->{$field}) . '<br />';
661 }
662 if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
663 $row->cells[1]->text .= get_string('city').get_string('labelsep', 'langconfig');
664 if ($user->city && !isset($hiddenfields['city'])) {
665 $row->cells[1]->text .= $user->city;
43aa295b 666 }
a2ed6e69 667 if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
c351150f 668 if ($user->city && !isset($hiddenfields['city'])) {
a2ed6e69 669 $row->cells[1]->text .= ', ';
c351150f 670 }
a2ed6e69 671 $row->cells[1]->text .= $countries[$user->country];
c351150f 672 }
a2ed6e69
SH
673 $row->cells[1]->text .= '<br />';
674 }
c351150f 675
a2ed6e69
SH
676 if (!isset($hiddenfields['lastaccess'])) {
677 if ($user->lastaccess) {
678 $row->cells[1]->text .= get_string('lastaccess').get_string('labelsep', 'langconfig').userdate($user->lastaccess);
679 $row->cells[1]->text .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
680 } else {
681 $row->cells[1]->text .= get_string('lastaccess').get_string('labelsep', 'langconfig').get_string('never');
c351150f 682 }
a2ed6e69 683 }
c351150f 684
a2ed6e69 685 $row->cells[1]->text .= $OUTPUT->container_end();
3aac07d8 686
a2ed6e69
SH
687 $row->cells[2] = new html_table_cell();
688 $row->cells[2]->attributes['class'] = 'links';
689 $row->cells[2]->text = '';
3aac07d8 690
a2ed6e69 691 $links = array();
c351150f 692
66b864c7 693 if ($CFG->enableblogs && ($CFG->bloglevel != BLOG_USER_LEVEL || $USER->id == $user->id)) {
a2ed6e69
SH
694 $links[] = html_writer::link(new moodle_url('/blog/index.php?userid='.$user->id), get_string('blogs', 'blog'));
695 }
c351150f 696
a2ed6e69
SH
697 if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
698 $links[] = html_writer::link(new moodle_url('/notes/index.php?course=' . $course->id. '&user='.$user->id), get_string('notes', 'notes'));
699 }
c351150f 700
a2ed6e69
SH
701 if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
702 $links[] = html_writer::link(new moodle_url('/course/user.php?id='. $course->id .'&user='. $user->id), get_string('activity'));
703 }
c351150f 704
a2ed6e69
SH
705 if ($USER->id != $user->id && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $context) && !is_siteadmin($user->id)) {
706 $links[] = html_writer::link(new moodle_url('/course/loginas.php?id='. $course->id .'&user='. $user->id .'&sesskey='. sesskey()), get_string('loginas'));
707 }
c351150f 708
a2ed6e69 709 $links[] = html_writer::link(new moodle_url('/user/view.php?id='. $user->id .'&course='. $course->id), get_string('fullprofile') . '...');
3aac07d8 710
a2ed6e69 711 $row->cells[2]->text .= implode('', $links);
c351150f 712
a2ed6e69
SH
713 if ($bulkoperations) {
714 $row->cells[2]->text .= '<br /><input type="checkbox" class="usercheckbox" name="user'.$user->id.'" /> ';
ee4a52c5 715 }
a2ed6e69
SH
716 $table->data = array($row);
717 echo html_writer::table($table);
ee4a52c5 718 }
a2ed6e69
SH
719
720 } else {
721 echo $OUTPUT->heading(get_string('nothingtodisplay'));
ee4a52c5 722 }
a2ed6e69 723 }
77c645df 724
a2ed6e69
SH
725} else {
726 $countrysort = (strpos($sort, 'country') !== false);
727 $timeformat = get_string('strftimedate');
3997cb40 728
729
a2ed6e69 730 if ($userlist) {
664fe87f 731
a2ed6e69
SH
732 $usersprinted = array();
733 foreach ($userlist as $user) {
734 if (in_array($user->id, $usersprinted)) { // Prevent duplicates by r.hidden - MDL-13935.
735 continue;
736 }
737 $usersprinted[] = $user->id; // Add new user to the array of users printed.
1f807bc4 738
a2ed6e69 739 context_helper::preload_from_record($user);
0be6f678 740
a2ed6e69
SH
741 if ($user->lastaccess) {
742 $lastaccess = format_time(time() - $user->lastaccess, $datestring);
743 } else {
744 $lastaccess = $strnever;
745 }
77c645df 746
a2ed6e69
SH
747 if (empty($user->country)) {
748 $country = '';
77c645df 749
a2ed6e69
SH
750 } else {
751 if ($countrysort) {
752 $country = '('.$user->country.') '.$countries[$user->country];
77c645df 753 } else {
a2ed6e69 754 $country = $countries[$user->country];
77c645df 755 }
a2ed6e69 756 }
0be6f678 757
a2ed6e69 758 $usercontext = context_user::instance($user->id);
0be6f678 759
a2ed6e69
SH
760 if ($piclink = ($USER->id == $user->id || has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext))) {
761 $profilelink = '<strong><a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.fullname($user).'</a></strong>';
762 } else {
763 $profilelink = '<strong>'.fullname($user).'</strong>';
764 }
0be6f678 765
a2ed6e69
SH
766 $data = array();
767 if ($bulkoperations) {
768 $data[] = '<input type="checkbox" class="usercheckbox" name="user'.$user->id.'" />';
769 }
770 $data[] = $OUTPUT->user_picture($user, array('size' => 35, 'courseid' => $course->id));
771 $data[] = $profilelink;
22ae509e 772
a2ed6e69
SH
773 if ($mode === MODE_BRIEF) {
774 foreach ($extrafields as $field) {
775 $data[] = $user->{$field};
77c645df 776 }
a2ed6e69
SH
777 }
778 if ($mode === MODE_BRIEF && !isset($hiddenfields['city'])) {
779 $data[] = $user->city;
780 }
781 if ($mode === MODE_BRIEF && !isset($hiddenfields['country'])) {
782 $data[] = $country;
783 }
784 if (!isset($hiddenfields['lastaccess'])) {
785 $data[] = $lastaccess;
786 }
664fe87f 787
a2ed6e69 788 $table->add_data($data);
eca3af25 789 }
a2ed6e69 790 }
576ad290 791
a2ed6e69 792 $table->print_html();
d88c5043 793
a2ed6e69 794}
b90e2f19 795
a2ed6e69
SH
796if ($bulkoperations) {
797 echo '<br /><div class="buttons">';
798 echo '<input type="button" id="checkall" value="'.get_string('selectall').'" /> ';
799 echo '<input type="button" id="checknone" value="'.get_string('deselectall').'" /> ';
800 $displaylist = array();
801 $displaylist['messageselect.php'] = get_string('messageselectadd');
802 if (!empty($CFG->enablenotes) && has_capability('moodle/notes:manage', $context) && $context->id != $frontpagectx->id) {
803 $displaylist['addnote.php'] = get_string('addnewnote', 'notes');
804 $displaylist['groupaddnote.php'] = get_string('groupaddnewnote', 'notes');
805 }
806
807 echo $OUTPUT->help_icon('withselectedusers');
808 echo html_writer::tag('label', get_string("withselectedusers"), array('for' => 'formactionid'));
809 echo html_writer::select($displaylist, 'formaction', '', array('' => 'choosedots'), array('id' => 'formactionid'));
810
811 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
812 echo '<noscript style="display:inline">';
813 echo '<div><input type="submit" value="'.get_string('ok').'" /></div>';
814 echo '</noscript>';
815 echo '</div></div>';
816 echo '</form>';
817
818 $module = array('name' => 'core_user', 'fullpath' => '/user/module.js');
819 $PAGE->requires->js_init_call('M.core_user.init_participation', null, false, $module);
820}
b90e2f19 821
a2ed6e69
SH
822// Show a search box if all participants don't fit on a single screen.
823if ($totalcount > $perpage) {
824 echo '<form action="index.php" class="searchform"><div><input type="hidden" name="id" value="'.$course->id.'" />';
825 echo '<label for="search">' . get_string('search', 'search') . ' </label>';
826 echo '<input type="text" id="search" name="search" value="'.s($search).'" />&nbsp;<input type="submit" value="'.get_string('search').'" /></div></form>'."\n";
827}
77c645df 828
a2ed6e69
SH
829$perpageurl = clone($baseurl);
830$perpageurl->remove_params('perpage');
831if ($perpage == SHOW_ALL_PAGE_SIZE) {
832 $perpageurl->param('perpage', DEFAULT_PAGE_SIZE);
833 echo $OUTPUT->container(html_writer::link($perpageurl, get_string('showperpage', '', DEFAULT_PAGE_SIZE)), array(), 'showall');
77c645df 834
a2ed6e69
SH
835} else if ($matchcount > 0 && $perpage < $matchcount) {
836 $perpageurl->param('perpage', SHOW_ALL_PAGE_SIZE);
837 echo $OUTPUT->container(html_writer::link($perpageurl, get_string('showall', '', $matchcount)), array(), 'showall');
838}
99cca847 839
a2ed6e69 840echo '</div>'; // Userlist.
f9903ed0 841
a2ed6e69 842echo $OUTPUT->footer();
77c645df 843
a2ed6e69
SH
844if ($userlist) {
845 $userlist->close();
846}
77c645df 847
a2ed6e69
SH
848/**
849 * Returns SQL that can be used to limit a query to a period where the user last accessed a course..
850 *
851 * @param string $accesssince
852 * @return string
853 */
0749caef 854function get_course_lastaccess_sql($accesssince='') {
31b71336 855 if (empty($accesssince)) {
856 return '';
857 }
a2ed6e69 858 if ($accesssince == -1) { // Never.
4f0c2d00 859 return 'ul.timeaccess = 0';
31b71336 860 } else {
4f0c2d00 861 return 'ul.timeaccess != 0 AND ul.timeaccess < '.$accesssince;
0749caef 862 }
863}
864
a2ed6e69
SH
865/**
866 * Returns SQL that can be used to limit a query to a period where the user last accessed the system.
867 *
868 * @param string $accesssince
869 * @return string
870 */
0749caef 871function get_user_lastaccess_sql($accesssince='') {
872 if (empty($accesssince)) {
873 return '';
874 }
a2ed6e69 875 if ($accesssince == -1) { // Never.
4f0c2d00 876 return 'u.lastaccess = 0';
0749caef 877 } else {
4f0c2d00 878 return 'u.lastaccess != 0 AND u.lastaccess < '.$accesssince;
31b71336 879 }
880}