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