Merge branch 'MDL-30738' of git://github.com/kiklop74/moodle
[moodle.git] / user / index.php
1 <?php
3 //  Lists all the users within a given course
5     require_once('../config.php');
6     require_once($CFG->libdir.'/tablelib.php');
7     require_once($CFG->libdir.'/filelib.php');
9     define('USER_SMALL_CLASS', 20);   // Below this is considered small
10     define('USER_LARGE_CLASS', 200);  // Above this is considered large
11     define('DEFAULT_PAGE_SIZE', 20);
12     define('SHOW_ALL_PAGE_SIZE', 5000);
13     define('MODE_BRIEF', 0);
14     define('MODE_USERDETAILS', 1);
16     $page         = optional_param('page', 0, PARAM_INT);                     // which page to show
17     $perpage      = optional_param('perpage', DEFAULT_PAGE_SIZE, PARAM_INT);  // how many per page
18     $mode         = optional_param('mode', NULL, PARAM_INT);                  // use the MODE_ constants
19     $accesssince  = optional_param('accesssince',0,PARAM_INT);                // filter by last access. -1 = never
20     $search       = optional_param('search','',PARAM_RAW);                    // make sure it is processed with p() or s() when sending to output!
21     $roleid       = optional_param('roleid', 0, PARAM_INT);                   // optional roleid, 0 means all enrolled users (or all on the frontpage)
23     $contextid    = optional_param('contextid', 0, PARAM_INT);                // one of this or
24     $courseid     = optional_param('id', 0, PARAM_INT);                       // this are required
26     $PAGE->set_url('/user/index.php', array(
27             'page' => $page,
28             'perpage' => $perpage,
29             'mode' => $mode,
30             'accesssince' => $accesssince,
31             'search' => $search,
32             'roleid' => $roleid,
33             'contextid' => $contextid,
34             'id' => $courseid));
36     if ($contextid) {
37         $context = get_context_instance_by_id($contextid, MUST_EXIST);
38         if ($context->contextlevel != CONTEXT_COURSE) {
39             print_error('invalidcontext');
40         }
41         $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
42     } else {
43         $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
44         $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
45     }
46     // not needed anymore
47     unset($contextid);
48     unset($courseid);
50     require_login($course);
52     $systemcontext = get_context_instance(CONTEXT_SYSTEM);
53     $isfrontpage = ($course->id == SITEID);
55     $frontpagectx = get_context_instance(CONTEXT_COURSE, SITEID);
57     if ($isfrontpage) {
58         $PAGE->set_pagelayout('admin');
59         require_capability('moodle/site:viewparticipants', $systemcontext);
60     } else {
61         $PAGE->set_pagelayout('incourse');
62         require_capability('moodle/course:viewparticipants', $context);
63     }
65     $rolenamesurl = new moodle_url("$CFG->wwwroot/user/index.php?contextid=$context->id&sifirst=&silast=");
67     $allroles = get_all_roles();
68     $roles = get_profile_roles($context);
69     $allrolenames = array();
70     if ($isfrontpage) {
71         $rolenames = array(0=>get_string('allsiteusers', 'role'));
72     } else {
73         $rolenames = array(0=>get_string('allparticipants'));
74     }
76     foreach ($allroles as $role) {
77         $allrolenames[$role->id] = strip_tags(role_get_name($role, $context));   // Used in menus etc later on
78         if (isset($roles[$role->id])) {
79             $rolenames[$role->id] = $allrolenames[$role->id];
80         }
81     }
83     // make sure other roles may not be selected by any means
84     if (empty($rolenames[$roleid])) {
85         print_error('noparticipants');
86     }
88     // no roles to display yet?
89     // frontpage course is an exception, on the front page course we should display all users
90     if (empty($rolenames) && !$isfrontpage) {
91         if (has_capability('moodle/role:assign', $context)) {
92             redirect($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id);
93         } else {
94             print_error('noparticipants');
95         }
96     }
98     add_to_log($course->id, 'user', 'view all', 'index.php?id='.$course->id, '');
100     $bulkoperations = has_capability('moodle/course:bulkmessaging', $context);
102     $countries = get_string_manager()->get_list_of_countries();
104     $strnever = get_string('never');
106     $datestring->year  = get_string('year');
107     $datestring->years = get_string('years');
108     $datestring->day   = get_string('day');
109     $datestring->days  = get_string('days');
110     $datestring->hour  = get_string('hour');
111     $datestring->hours = get_string('hours');
112     $datestring->min   = get_string('min');
113     $datestring->mins  = get_string('mins');
114     $datestring->sec   = get_string('sec');
115     $datestring->secs  = get_string('secs');
117     if ($mode !== NULL) {
118         $mode = (int)$mode;
119         $SESSION->userindexmode = $mode;
120     } else if (isset($SESSION->userindexmode)) {
121         $mode = (int)$SESSION->userindexmode;
122     } else {
123         $mode = MODE_BRIEF;
124     }
126 /// Check to see if groups are being used in this course
127 /// and if so, set $currentgroup to reflect the current group
129     $groupmode    = groups_get_course_groupmode($course);   // Groups are being used
130     $currentgroup = groups_get_course_group($course, true);
132     if (!$currentgroup) {      // To make some other functions work better later
133         $currentgroup  = NULL;
134     }
136     $isseparategroups = ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context));
138     $PAGE->set_title("$course->shortname: ".get_string('participants'));
139     $PAGE->set_heading($course->fullname);
140     $PAGE->set_pagetype('course-view-' . $course->format);
141     $PAGE->add_body_class('path-user');                     // So we can style it independently
142     $PAGE->set_other_editing_capability('moodle/course:manageactivities');
144     echo $OUTPUT->header();
146     echo '<div class="userlist">';
148     if ($isseparategroups and (!$currentgroup) ) {
149         // The user is not in the group so show message and exit
150         echo $OUTPUT->heading(get_string("notingroup"));
151         echo $OUTPUT->footer();
152         exit;
153     }
156     // Should use this variable so that we don't break stuff every time a variable is added or changed.
157     $baseurl = new moodle_url('/user/index.php', array(
158             'contextid' => $context->id,
159             'roleid' => $roleid,
160             'id' => $course->id,
161             'perpage' => $perpage,
162             'accesssince' => $accesssince,
163             'search' => s($search)));
165 /// setting up tags
166     if ($course->id == SITEID) {
167         $filtertype = 'site';
168     } else if ($course->id && !$currentgroup) {
169         $filtertype = 'course';
170         $filterselect = $course->id;
171     } else {
172         $filtertype = 'group';
173         $filterselect = $currentgroup;
174     }
178 /// Get the hidden field list
179     if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
180         $hiddenfields = array();  // teachers and admins are allowed to see everything
181     } else {
182         $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
183     }
185     if (isset($hiddenfields['lastaccess'])) {
186         // do not allow access since filtering
187         $accesssince = 0;
188     }
190 /// Print settings and things in a table across the top
191     $controlstable = new html_table();
192     $controlstable->attributes['class'] = 'controls';
193     $controlstable->cellspacing = 0;
194     $controlstable->data[] = new html_table_row();
196 /// Print my course menus
197     if ($mycourses = enrol_get_my_courses()) {
198         $courselist = array();
199         $popupurl = new moodle_url('/user/index.php?roleid='.$roleid.'&sifirst=&silast=');
200         foreach ($mycourses as $mycourse) {
201             $coursecontext = get_context_instance(CONTEXT_COURSE, $mycourse->id);
202             $courselist[$mycourse->id] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
203         }
204         if (has_capability('moodle/site:viewparticipants', $systemcontext)) {
205             unset($courselist[SITEID]);
206             $courselist = array(SITEID => format_string($SITE->shortname, true, array('context' => $systemcontext))) + $courselist;
207         }
208         $select = new single_select($popupurl, 'id', $courselist, $course->id, array(''=>'choosedots'), 'courseform');
209         $select->set_label(get_string('mycourses'));
210         $controlstable->data[0]->cells[] = $OUTPUT->render($select);
211     }
213     $controlstable->data[0]->cells[] = groups_print_course_menu($course, $baseurl->out(), true);
215     if (!isset($hiddenfields['lastaccess'])) {
216         // get minimum lastaccess for this course and display a dropbox to filter by lastaccess going back this far.
217         // we need to make it diferently for normal courses and site course
218         if (!$isfrontpage) {
219             $minlastaccess = $DB->get_field_sql('SELECT min(timeaccess)
220                                                    FROM {user_lastaccess}
221                                                   WHERE courseid = ?
222                                                         AND timeaccess != 0', array($course->id));
223             $lastaccess0exists = $DB->record_exists('user_lastaccess', array('courseid'=>$course->id, 'timeaccess'=>0));
224         } else {
225             $minlastaccess = $DB->get_field_sql('SELECT min(lastaccess)
226                                                    FROM {user}
227                                                   WHERE lastaccess != 0');
228             $lastaccess0exists = $DB->record_exists('user', array('lastaccess'=>0));
229         }
231         $now = usergetmidnight(time());
232         $timeaccess = array();
233         $baseurl->remove_params('accesssince');
235         // makes sense for this to go first.
236         $timeoptions[0] = get_string('selectperiod');
238         // days
239         for ($i = 1; $i < 7; $i++) {
240             if (strtotime('-'.$i.' days',$now) >= $minlastaccess) {
241                 $timeoptions[strtotime('-'.$i.' days',$now)] = get_string('numdays','moodle',$i);
242             }
243         }
244         // weeks
245         for ($i = 1; $i < 10; $i++) {
246             if (strtotime('-'.$i.' weeks',$now) >= $minlastaccess) {
247                 $timeoptions[strtotime('-'.$i.' weeks',$now)] = get_string('numweeks','moodle',$i);
248             }
249         }
250         // months
251         for ($i = 2; $i < 12; $i++) {
252             if (strtotime('-'.$i.' months',$now) >= $minlastaccess) {
253                 $timeoptions[strtotime('-'.$i.' months',$now)] = get_string('nummonths','moodle',$i);
254             }
255         }
256         // try a year
257         if (strtotime('-1 year',$now) >= $minlastaccess) {
258             $timeoptions[strtotime('-1 year',$now)] = get_string('lastyear');
259         }
261         if (!empty($lastaccess0exists)) {
262             $timeoptions[-1] = get_string('never');
263         }
265         if (count($timeoptions) > 1) {
266             $select = new single_select($baseurl, 'accesssince', $timeoptions, $accesssince, null, 'timeoptions');
267             $select->set_label(get_string('usersnoaccesssince'));
268             $controlstable->data[0]->cells[] = $OUTPUT->render($select);
269         }
270     }
272     $formatmenu = array( '0' => get_string('brief'),
273                          '1' => get_string('userdetails'));
274     $select = new single_select($baseurl, 'mode', $formatmenu, $mode, null, 'formatmenu');
275     $select->set_label(get_string('userlist'));
276     $userlistcell = new html_table_cell();
277     $userlistcell->attributes['class'] = 'right';
278     $userlistcell->text = $OUTPUT->render($select);
279     $controlstable->data[0]->cells[] = $userlistcell;
281     echo html_writer::table($controlstable);
283     if ($currentgroup and (!$isseparategroups or has_capability('moodle/site:accessallgroups', $context))) {    /// Display info about the group
284         if ($group = groups_get_group($currentgroup)) {
285             if (!empty($group->description) or (!empty($group->picture) and empty($group->hidepicture))) {
286                 $groupinfotable = new html_table();
287                 $groupinfotable->attributes['class'] = 'groupinfobox';
288                 $picturecell = new html_table_cell();
289                 $picturecell->attributes['class'] = 'left side picture';
290                 $picturecell->text = print_group_picture($group, $course->id, true, true, false);
292                 $contentcell = new html_table_cell();
293                 $contentcell->attributes['class'] = 'content';
295                 $contentheading = $group->name;
296                 if (has_capability('moodle/course:managegroups', $context)) {
297                     $aurl = new moodle_url('/group/group.php', array('id' => $group->id, 'courseid' => $group->courseid));
298                     $contentheading .= '&nbsp;' . $OUTPUT->action_icon($aurl, new pix_icon('t/edit', get_string('editgroupprofile')));
299                 }
301                 $group->description = file_rewrite_pluginfile_urls($group->description, 'pluginfile.php', $context->id, 'group', 'description', $group->id);
302                 if (!isset($group->descriptionformat)) {
303                     $group->descriptionformat = FORMAT_MOODLE;
304                 }
305                 $options = array('overflowdiv'=>true);
306                 $contentcell->text = $OUTPUT->heading($contentheading, 3) . format_text($group->description, $group->descriptionformat, $options);
307                 $groupinfotable->data[] = new html_table_row(array($picturecell, $contentcell));
308                 echo html_writer::table($groupinfotable);
309             }
310         }
311     }
313     /// Define a table showing a list of users in the current role selection
315     $tablecolumns = array('userpic', 'fullname');
316     $extrafields = get_extra_user_fields($context);
317     $tableheaders = array(get_string('userpic'), get_string('fullnameuser'));
318     if ($mode === MODE_BRIEF) {
319         foreach ($extrafields as $field) {
320             $tablecolumns[] = $field;
321             $tableheaders[] = get_user_field_name($field);
322         }
323     }
324     if ($mode === MODE_BRIEF && !isset($hiddenfields['city'])) {
325         $tablecolumns[] = 'city';
326         $tableheaders[] = get_string('city');
327     }
328     if ($mode === MODE_BRIEF && !isset($hiddenfields['country'])) {
329         $tablecolumns[] = 'country';
330         $tableheaders[] = get_string('country');
331     }
332     if (!isset($hiddenfields['lastaccess'])) {
333         $tablecolumns[] = 'lastaccess';
334         $tableheaders[] = get_string('lastaccess');
335     }
337     if ($bulkoperations) {
338         $tablecolumns[] = 'select';
339         $tableheaders[] = get_string('select');
340     }
342     $table = new flexible_table('user-index-participants-'.$course->id);
343     $table->define_columns($tablecolumns);
344     $table->define_headers($tableheaders);
345     $table->define_baseurl($baseurl->out());
347     if (!isset($hiddenfields['lastaccess'])) {
348         $table->sortable(true, 'lastaccess', SORT_DESC);
349     } else {
350         $table->sortable(true, 'firstname', SORT_ASC);
351     }
353     $table->no_sorting('roles');
354     $table->no_sorting('groups');
355     $table->no_sorting('groupings');
356     $table->no_sorting('select');
358     $table->set_attribute('cellspacing', '0');
359     $table->set_attribute('id', 'participants');
360     $table->set_attribute('class', 'generaltable generalbox');
362     $table->set_control_variables(array(
363                 TABLE_VAR_SORT    => 'ssort',
364                 TABLE_VAR_HIDE    => 'shide',
365                 TABLE_VAR_SHOW    => 'sshow',
366                 TABLE_VAR_IFIRST  => 'sifirst',
367                 TABLE_VAR_ILAST   => 'silast',
368                 TABLE_VAR_PAGE    => 'spage'
369                 ));
370     $table->setup();
372     // we are looking for all users with this role assigned in this context or higher
373     $contextlist = get_related_contexts_string($context);
375     list($esql, $params) = get_enrolled_sql($context, NULL, $currentgroup, true);
376     $joins = array("FROM {user} u");
377     $wheres = array();
379     $extrasql = get_extra_user_fields_sql($context, 'u', '', array(
380             'id', 'username', 'firstname', 'lastname', 'email', 'city', 'country',
381             'picture', 'lang', 'timezone', 'maildisplay', 'imagealt', 'lastaccess'));
383     if ($isfrontpage) {
384         $select = "SELECT u.id, u.username, u.firstname, u.lastname,
385                           u.email, u.city, u.country, u.picture,
386                           u.lang, u.timezone, u.maildisplay, u.imagealt,
387                           u.lastaccess$extrasql";
388         $joins[] = "JOIN ($esql) e ON e.id = u.id"; // everybody on the frontpage usually
389         if ($accesssince) {
390             $wheres[] = get_user_lastaccess_sql($accesssince);
391         }
393     } else {
394         $select = "SELECT u.id, u.username, u.firstname, u.lastname,
395                           u.email, u.city, u.country, u.picture,
396                           u.lang, u.timezone, u.maildisplay, u.imagealt,
397                           COALESCE(ul.timeaccess, 0) AS lastaccess$extrasql";
398         $joins[] = "JOIN ($esql) e ON e.id = u.id"; // course enrolled users only
399         $joins[] = "LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)"; // not everybody accessed course yet
400         $params['courseid'] = $course->id;
401         if ($accesssince) {
402             $wheres[] = get_course_lastaccess_sql($accesssince);
403         }
404     }
406     // performance hacks - we preload user contexts together with accounts
407     list($ccselect, $ccjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
408     $select .= $ccselect;
409     $joins[] = $ccjoin;
412     // limit list to users with some role only
413     if ($roleid) {
414         $wheres[] = "u.id IN (SELECT userid FROM {role_assignments} WHERE roleid = :roleid AND contextid $contextlist)";
415         $params['roleid'] = $roleid;
416     }
418     $from = implode("\n", $joins);
419     if ($wheres) {
420         $where = "WHERE " . implode(" AND ", $wheres);
421     } else {
422         $where = "";
423     }
425     $totalcount = $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
427     if (!empty($search)) {
428         $fullname = $DB->sql_fullname('u.firstname','u.lastname');
429         $wheres[] = "(". $DB->sql_like($fullname, ':search1', false, false) .
430                     " OR ". $DB->sql_like('email', ':search2', false, false) .
431                     " OR ". $DB->sql_like('idnumber', ':search3', false, false) .") ";
432         $params['search1'] = "%$search%";
433         $params['search2'] = "%$search%";
434         $params['search3'] = "%$search%";
435     }
437     list($twhere, $tparams) = $table->get_sql_where();
438     if ($twhere) {
439         $wheres[] = $twhere;
440         $params = array_merge($params, $tparams);
441     }
443     $from = implode("\n", $joins);
444     if ($wheres) {
445         $where = "WHERE " . implode(" AND ", $wheres);
446     } else {
447         $where = "";
448     }
450     if ($table->get_sql_sort()) {
451         $sort = ' ORDER BY '.$table->get_sql_sort();
452     } else {
453         $sort = '';
454     }
456     $matchcount = $DB->count_records_sql("SELECT COUNT(u.id) $from $where", $params);
458     $table->initialbars(true);
459     $table->pagesize($perpage, $matchcount);
461     // list of users at the current visible page - paging makes it relatively short
462     $userlist = $DB->get_recordset_sql("$select $from $where $sort", $params, $table->get_page_start(), $table->get_page_size());
464     /// If there are multiple Roles in the course, then show a drop down menu for switching
465     if (count($rolenames) > 1) {
466         echo '<div class="rolesform">';
467         echo '<label for="rolesform_jump">'.get_string('currentrole', 'role').'&nbsp;</label>';
468         echo $OUTPUT->single_select($rolenamesurl, 'roleid', $rolenames, $roleid, null, 'rolesform');
469         echo '</div>';
471     } else if (count($rolenames) == 1) {
472         // when all users with the same role - print its name
473         echo '<div class="rolesform">';
474         echo get_string('role').get_string('labelsep', 'langconfig');
475         $rolename = reset($rolenames);
476         echo $rolename;
477         echo '</div>';
478     }
480     if ($roleid > 0) {
481         $a->number = $totalcount;
482         $a->role = $rolenames[$roleid];
483         $heading = format_string(get_string('xuserswiththerole', 'role', $a));
485         if ($currentgroup and $group) {
486             $a->group = $group->name;
487             $heading .= ' ' . format_string(get_string('ingroup', 'role', $a));
488         }
490         if ($accesssince) {
491             $a->timeperiod = $timeoptions[$accesssince];
492             $heading .= ' ' . format_string(get_string('inactiveformorethan', 'role', $a));
493         }
495         $heading .= ": $a->number";
496         if (user_can_assign($context, $roleid)) {
497             $heading .= ' <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?roleid='.$roleid.'&amp;contextid='.$context->id.'">';
498             $heading .= '<img src="'.$OUTPUT->pix_url('i/edit') . '" class="icon" alt="" /></a>';
499         }
500         echo $OUTPUT->heading($heading, 3);
501     } else {
502         if ($course->id != SITEID && has_capability('moodle/course:enrolreview', $context)) {
503             $editlink = $OUTPUT->action_icon(new moodle_url('/enrol/users.php', array('id' => $course->id)),
504                                              new pix_icon('i/edit', get_string('edit')));
505         } else {
506             $editlink = '';
507         }
508         if ($course->id == SITEID and $roleid < 0) {
509             $strallparticipants = get_string('allsiteusers', 'role');
510         } else {
511             $strallparticipants = get_string('allparticipants');
512         }
513         if ($matchcount < $totalcount) {
514             echo $OUTPUT->heading($strallparticipants.get_string('labelsep', 'langconfig').$matchcount.'/'.$totalcount . $editlink, 3);
515         } else {
516             echo $OUTPUT->heading($strallparticipants.get_string('labelsep', 'langconfig').$matchcount . $editlink, 3);
517         }
518     }
521     if ($bulkoperations) {
522         echo '<form action="action_redir.php" method="post" id="participantsform">';
523         echo '<div>';
524         echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
525         echo '<input type="hidden" name="returnto" value="'.s(me()).'" />';
526     }
528     if ($mode === MODE_USERDETAILS) {    // Print simple listing
529         if ($totalcount < 1) {
530             echo $OUTPUT->heading(get_string('nothingtodisplay'));
531         } else {
532             if ($totalcount > $perpage) {
534                 $firstinitial = $table->get_initial_first();
535                 $lastinitial  = $table->get_initial_last();
536                 $strall = get_string('all');
537                 $alpha  = explode(',', get_string('alphabet', 'langconfig'));
539                 // Bar of first initials
541                 echo '<div class="initialbar firstinitial">'.get_string('firstname').' : ';
542                 if(!empty($firstinitial)) {
543                     echo '<a href="'.$baseurl->out().'&amp;sifirst=">'.$strall.'</a>';
544                 } else {
545                     echo '<strong>'.$strall.'</strong>';
546                 }
547                 foreach ($alpha as $letter) {
548                     if ($letter == $firstinitial) {
549                         echo ' <strong>'.$letter.'</strong>';
550                     } else {
551                         echo ' <a href="'.$baseurl->out().'&amp;sifirst='.$letter.'">'.$letter.'</a>';
552                     }
553                 }
554                 echo '</div>';
556                 // Bar of last initials
558                 echo '<div class="initialbar lastinitial">'.get_string('lastname').' : ';
559                 if(!empty($lastinitial)) {
560                     echo '<a href="'.$baseurl->out().'&amp;silast=">'.$strall.'</a>';
561                 } else {
562                     echo '<strong>'.$strall.'</strong>';
563                 }
564                 foreach ($alpha as $letter) {
565                     if ($letter == $lastinitial) {
566                         echo ' <strong>'.$letter.'</strong>';
567                     } else {
568                         echo ' <a href="'.$baseurl->out().'&amp;silast='.$letter.'">'.$letter.'</a>';
569                     }
570                 }
571                 echo '</div>';
573                 $pagingbar = new paging_bar($matchcount, intval($table->get_page_start() / $perpage), $perpage, $baseurl);
574                 $pagingbar->pagevar = 'spage';
575                 echo $OUTPUT->render($pagingbar);
576             }
578             if ($matchcount > 0) {
579                 $usersprinted = array();
580                 foreach ($userlist as $user) {
581                     if (in_array($user->id, $usersprinted)) { /// Prevent duplicates by r.hidden - MDL-13935
582                         continue;
583                     }
584                     $usersprinted[] = $user->id; /// Add new user to the array of users printed
586                     context_instance_preload($user);
588                     $context = get_context_instance(CONTEXT_COURSE, $course->id);
589                     $usercontext = get_context_instance(CONTEXT_USER, $user->id);
591                     $countries = get_string_manager()->get_list_of_countries();
593                     /// Get the hidden field list
594                     if (has_capability('moodle/course:viewhiddenuserfields', $context)) {
595                         $hiddenfields = array();
596                     } else {
597                         $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
598                     }
599                     $table = new html_table();
600                     $table->attributes['class'] = 'userinfobox';
602                     $row = new html_table_row();
603                     $row->cells[0] = new html_table_cell();
604                     $row->cells[0]->attributes['class'] = 'left side';
606                     $row->cells[0]->text = $OUTPUT->user_picture($user, array('size' => 100, 'courseid'=>$course->id));
607                     $row->cells[1] = new html_table_cell();
608                     $row->cells[1]->attributes['class'] = 'content';
610                     $row->cells[1]->text = $OUTPUT->container(fullname($user, has_capability('moodle/site:viewfullnames', $context)), 'username');
611                     $row->cells[1]->text .= $OUTPUT->container_start('info');
613                     if (!empty($user->role)) {
614                         $row->cells[1]->text .= get_string('role').get_string('labelsep', 'langconfig').$user->role.'<br />';
615                     }
616                     if ($user->maildisplay == 1 or ($user->maildisplay == 2 and ($course->id != SITEID) and !isguestuser()) or
617                                 has_capability('moodle/course:viewhiddenuserfields', $context) or
618                                 in_array('email', $extrafields)) {
619                         $row->cells[1]->text .= get_string('email').get_string('labelsep', 'langconfig').html_writer::link("mailto:$user->email", $user->email) . '<br />';
620                     }
621                     foreach ($extrafields as $field) {
622                         if ($field === 'email') {
623                             // Skip email because it was displayed with different
624                             // logic above (because this page is intended for
625                             // students too)
626                             continue;
627                         }
628                         $row->cells[1]->text .= get_user_field_name($field) .
629                                 get_string('labelsep', 'langconfig') . s($user->{$field}) . '<br />';
630                     }
631                     if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) {
632                         $row->cells[1]->text .= get_string('city').get_string('labelsep', 'langconfig');
633                         if ($user->city && !isset($hiddenfields['city'])) {
634                             $row->cells[1]->text .= $user->city;
635                         }
636                         if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) {
637                             if ($user->city && !isset($hiddenfields['city'])) {
638                                 $row->cells[1]->text .= ', ';
639                             }
640                             $row->cells[1]->text .= $countries[$user->country];
641                         }
642                         $row->cells[1]->text .= '<br />';
643                     }
645                     if (!isset($hiddenfields['lastaccess'])) {
646                         if ($user->lastaccess) {
647                             $row->cells[1]->text .= get_string('lastaccess').get_string('labelsep', 'langconfig').userdate($user->lastaccess);
648                             $row->cells[1]->text .= '&nbsp; ('. format_time(time() - $user->lastaccess, $datestring) .')';
649                         } else {
650                             $row->cells[1]->text .= get_string('lastaccess').get_string('labelsep', 'langconfig').get_string('never');
651                         }
652                     }
654                     $row->cells[1]->text .= $OUTPUT->container_end();
656                     $row->cells[2] = new html_table_cell();
657                     $row->cells[2]->attributes['class'] = 'links';
658                     $row->cells[2]->text = '';
660                     $links = array();
662                     if ($CFG->bloglevel > 0) {
663                         $links[] = html_writer::link(new moodle_url('/blog/index.php?userid='.$user->id), get_string('blogs','blog'));
664                     }
666                     if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) {
667                         $links[] = html_writer::link(new moodle_url('/notes/index.php?course=' . $course->id. '&user='.$user->id), get_string('notes','notes'));
668                     }
670                     if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) {
671                         $links[] = html_writer::link(new moodle_url('/course/user.php?id='. $course->id .'&user='. $user->id), get_string('activity'));
672                     }
674                     if ($USER->id != $user->id && !session_is_loggedinas() && has_capability('moodle/user:loginas', $context) && !is_siteadmin($user->id)) {
675                         $links[] = html_writer::link(new moodle_url('/course/loginas.php?id='. $course->id .'&user='. $user->id .'&sesskey='. sesskey()), get_string('loginas'));
676                     }
678                     $links[] = html_writer::link(new moodle_url('/user/view.php?id='. $user->id .'&course='. $course->id), get_string('fullprofile') . '...');
680                     $row->cells[2]->text .= implode('', $links);
682                     if (!empty($messageselect)) {
683                         $row->cells[2]->text .= '<br /><input type="checkbox" name="user'.$user->id.'" /> ';
684                     }
685                     $table->data = array($row);
686                     echo html_writer::table($table);
687                 }
689             } else {
690                 echo $OUTPUT->heading(get_string('nothingtodisplay'));
691             }
692         }
694     } else {
695         $countrysort = (strpos($sort, 'country') !== false);
696         $timeformat = get_string('strftimedate');
699         if ($userlist)  {
701             $usersprinted = array();
702             foreach ($userlist as $user) {
703                 if (in_array($user->id, $usersprinted)) { /// Prevent duplicates by r.hidden - MDL-13935
704                     continue;
705                 }
706                 $usersprinted[] = $user->id; /// Add new user to the array of users printed
708                 context_instance_preload($user);
710                 if ($user->lastaccess) {
711                     $lastaccess = format_time(time() - $user->lastaccess, $datestring);
712                 } else {
713                     $lastaccess = $strnever;
714                 }
716                 if (empty($user->country)) {
717                     $country = '';
719                 } else {
720                     if($countrysort) {
721                         $country = '('.$user->country.') '.$countries[$user->country];
722                     }
723                     else {
724                         $country = $countries[$user->country];
725                     }
726                 }
728                 $usercontext = get_context_instance(CONTEXT_USER, $user->id);
730                 if ($piclink = ($USER->id == $user->id || has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext))) {
731                     $profilelink = '<strong><a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.fullname($user).'</a></strong>';
732                 } else {
733                     $profilelink = '<strong>'.fullname($user).'</strong>';
734                 }
736                 $data = array ($OUTPUT->user_picture($user, array('size' => 35, 'courseid'=>$course->id)), $profilelink);
738                 if ($mode === MODE_BRIEF) {
739                     foreach ($extrafields as $field) {
740                         $data[] = $user->{$field};
741                     }
742                 }
743                 if ($mode === MODE_BRIEF && !isset($hiddenfields['city'])) {
744                     $data[] = $user->city;
745                 }
746                 if ($mode === MODE_BRIEF && !isset($hiddenfields['country'])) {
747                     $data[] = $country;
748                 }
749                 if (!isset($hiddenfields['lastaccess'])) {
750                     $data[] = $lastaccess;
751                 }
753                 if (isset($userlist_extra) && isset($userlist_extra[$user->id])) {
754                     $ras = $userlist_extra[$user->id]['ra'];
755                     $rastring = '';
756                     foreach ($ras AS $key=>$ra) {
757                         $rolename = $allrolenames[$ra['roleid']] ;
758                         if ($ra['ctxlevel'] == CONTEXT_COURSECAT) {
759                             $rastring .= $rolename. ' @ ' . '<a href="'.$CFG->wwwroot.'/course/category.php?id='.$ra['ctxinstanceid'].'">'.s($ra['ccname']).'</a>';
760                         } elseif ($ra['ctxlevel'] == CONTEXT_SYSTEM) {
761                             $rastring .= $rolename. ' - ' . get_string('globalrole','role');
762                         } else {
763                             $rastring .= $rolename;
764                         }
765                     }
766                     $data[] = $rastring;
767                     if ($groupmode != 0) {
768                         // htmlescape with s() and implode the array
769                         $data[] = implode(', ', array_map('s',$userlist_extra[$user->id]['group']));
770                         $data[] = implode(', ', array_map('s', $userlist_extra[$user->id]['gping']));
771                     }
772                 }
774                 if ($bulkoperations) {
775                     $data[] = '<input type="checkbox" class="usercheckbox" name="user'.$user->id.'" />';
776                 }
777                 $table->add_data($data);
778             }
779         }
781         $table->print_html();
783     }
785     if ($bulkoperations) {
786         echo '<br /><div class="buttons">';
787         echo '<input type="button" id="checkall" value="'.get_string('selectall').'" /> ';
788         echo '<input type="button" id="checknone" value="'.get_string('deselectall').'" /> ';
789         $displaylist = array();
790         $displaylist['messageselect.php'] = get_string('messageselectadd');
791         if (!empty($CFG->enablenotes) && has_capability('moodle/notes:manage', $context) && $context->id != $frontpagectx->id) {
792             $displaylist['addnote.php'] = get_string('addnewnote', 'notes');
793             $displaylist['groupaddnote.php'] = get_string('groupaddnewnote', 'notes');
794         }
796         echo $OUTPUT->help_icon('withselectedusers');
797         echo html_writer::tag('label', get_string("withselectedusers"), array('for'=>'formactionid'));
798         echo html_writer::select($displaylist, 'formaction', '', array(''=>'choosedots'), array('id'=>'formactionid'));
800         echo '<input type="hidden" name="id" value="'.$course->id.'" />';
801         echo '<noscript style="display:inline">';
802         echo '<div><input type="submit" value="'.get_string('ok').'" /></div>';
803         echo '</noscript>';
804         echo '</div></div>';
805         echo '</form>';
807         $module = array('name'=>'core_user', 'fullpath'=>'/user/module.js');
808         $PAGE->requires->js_init_call('M.core_user.init_participation', null, false, $module);
809     }
811     if (has_capability('moodle/site:viewparticipants', $context) && $totalcount > ($perpage*3)) {
812         echo '<form action="index.php" class="searchform"><div><input type="hidden" name="id" value="'.$course->id.'" />'.get_string('search').':&nbsp;'."\n";
813         echo '<input type="text" name="search" value="'.s($search).'" />&nbsp;<input type="submit" value="'.get_string('search').'" /></div></form>'."\n";
814     }
816     $perpageurl = clone($baseurl);
817     $perpageurl->remove_params('perpage');
818     if ($perpage == SHOW_ALL_PAGE_SIZE) {
819         $perpageurl->param('perpage', DEFAULT_PAGE_SIZE);
820         echo $OUTPUT->container(html_writer::link($perpageurl, get_string('showperpage', '', DEFAULT_PAGE_SIZE)), array(), 'showall');
822     } else if ($matchcount > 0 && $perpage < $matchcount) {
823         $perpageurl->param('perpage', SHOW_ALL_PAGE_SIZE);
824         echo $OUTPUT->container(html_writer::link($perpageurl, get_string('showall', '', $matchcount)), array(), 'showall');
825     }
827     echo '</div>';  // userlist
829     echo $OUTPUT->footer();
831     if ($userlist) {
832         $userlist->close();
833     }
836 function get_course_lastaccess_sql($accesssince='') {
837     if (empty($accesssince)) {
838         return '';
839     }
840     if ($accesssince == -1) { // never
841         return 'ul.timeaccess = 0';
842     } else {
843         return 'ul.timeaccess != 0 AND ul.timeaccess < '.$accesssince;
844     }
847 function get_user_lastaccess_sql($accesssince='') {
848     if (empty($accesssince)) {
849         return '';
850     }
851     if ($accesssince == -1) { // never
852         return 'u.lastaccess = 0';
853     } else {
854         return 'u.lastaccess != 0 AND u.lastaccess < '.$accesssince;
855     }