MDL-67913 core_table: introduce dynamic table interface
[moodle.git] / user / classes / participants_table.php
CommitLineData
bc47b706
MN
1<?php
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 * Contains the class used for the displaying the participants table.
19 *
20 * @package core_user
21 * @copyright 2017 Mark Nelson <markn@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_user;
26
fb792967 27use context;
90ffcfa8 28use core_user\output\status_field;
fb792967 29use DateTime;
fb792967 30
bc47b706
MN
31defined('MOODLE_INTERNAL') || die;
32
33global $CFG;
34
35require_once($CFG->libdir . '/tablelib.php');
36require_once($CFG->dirroot . '/user/lib.php');
37
38/**
39 * Class for the displaying the participants table.
40 *
41 * @package core_user
42 * @copyright 2017 Mark Nelson <markn@moodle.com>
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 */
45class participants_table extends \table_sql {
46
47 /**
48 * @var int $courseid The course id
49 */
50 protected $courseid;
51
52 /**
53 * @var int|false False if groups not used, int if groups used, 0 for all groups.
54 */
55 protected $currentgroup;
56
57 /**
58 * @var int $accesssince The time the user last accessed the site
59 */
60 protected $accesssince;
61
62 /**
63 * @var int $roleid The role we are including, 0 means all enrolled users
64 */
65 protected $roleid;
66
9651e491
JP
67 /**
68 * @var int $enrolid The applied filter for the user enrolment ID.
69 */
70 protected $enrolid;
71
72 /**
73 * @var int $status The applied filter for the user's enrolment status.
74 */
75 protected $status;
76
bc47b706
MN
77 /**
78 * @var string $search The string being searched.
79 */
80 protected $search;
81
82 /**
83 * @var bool $selectall Has the user selected all users on the page?
84 */
85 protected $selectall;
86
87 /**
88 * @var string[] The list of countries.
89 */
90 protected $countries;
91
2fa35b8d 92 /**
f3ecea3a 93 * @var \stdClass[] The list of groups with membership info for the course.
2fa35b8d
DW
94 */
95 protected $groups;
96
bc47b706
MN
97 /**
98 * @var string[] Extra fields to display.
99 */
100 protected $extrafields;
101
2fa35b8d 102 /**
fb792967 103 * @var \stdClass $course The course details.
2fa35b8d
DW
104 */
105 protected $course;
106
107 /**
fb792967 108 * @var context $context The course context.
2fa35b8d
DW
109 */
110 protected $context;
111
73d0d562
DW
112 /**
113 * @var \stdClass[] List of roles indexed by roleid.
114 */
115 protected $allroles;
116
0ae28fad
DW
117 /**
118 * @var \stdClass[] List of roles indexed by roleid.
119 */
120 protected $allroleassignments;
121
73d0d562
DW
122 /**
123 * @var \stdClass[] Assignable roles in this course.
124 */
125 protected $assignableroles;
126
9df2fdec
DW
127 /**
128 * @var \stdClass[] Profile roles in this course.
129 */
130 protected $profileroles;
131
a63cd3e2
AH
132 /** @var \stdClass[] $viewableroles */
133 private $viewableroles;
134
bc47b706
MN
135 /**
136 * Sets up the table.
137 *
138 * @param int $courseid
5290d060 139 * @param int|false $currentgroup False if groups not used, int if groups used, 0 all groups, USERSWITHOUTGROUP for no group
bc47b706
MN
140 * @param int $accesssince The time the user last accessed the site
141 * @param int $roleid The role we are including, 0 means all enrolled users
9651e491
JP
142 * @param int $enrolid The applied filter for the user enrolment ID.
143 * @param int $status The applied filter for the user's enrolment status.
144 * @param string|array $search The search string(s)
bc47b706
MN
145 * @param bool $bulkoperations Is the user allowed to perform bulk operations?
146 * @param bool $selectall Has the user selected all users on the page?
147 */
9651e491 148 public function __construct($courseid, $currentgroup, $accesssince, $roleid, $enrolid, $status, $search,
bc47b706 149 $bulkoperations, $selectall) {
df92be9d 150 global $CFG, $OUTPUT;
bc47b706
MN
151
152 parent::__construct('user-index-participants-' . $courseid);
153
df92be9d
JP
154 $this->selectall = $selectall;
155
bc47b706 156 // Get the context.
2fa35b8d 157 $this->course = get_course($courseid);
bc47b706 158 $context = \context_course::instance($courseid, MUST_EXIST);
fb792967 159 $this->context = $context;
bc47b706
MN
160
161 // Define the headers and columns.
162 $headers = [];
163 $columns = [];
164
165 if ($bulkoperations) {
df92be9d
JP
166 $mastercheckbox = new \core\output\checkbox_toggleall('participants-table', true, [
167 'id' => 'select-all-participants',
168 'name' => 'select-all-participants',
169 'label' => $this->selectall ? get_string('deselectall') : get_string('selectall'),
170 'labelclasses' => 'sr-only',
171 'classes' => 'm-1',
172 'checked' => $this->selectall
173 ]);
174 $headers[] = $OUTPUT->render($mastercheckbox);
bc47b706
MN
175 $columns[] = 'select';
176 }
177
178 $headers[] = get_string('fullname');
179 $columns[] = 'fullname';
180
181 $extrafields = get_extra_user_fields($context);
182 foreach ($extrafields as $field) {
183 $headers[] = get_user_field_name($field);
184 $columns[] = $field;
185 }
186
5d0b4765
DW
187 $headers[] = get_string('roles');
188 $columns[] = 'roles';
189
bc47b706
MN
190 // Get the list of fields we have to hide.
191 $hiddenfields = array();
192 if (!has_capability('moodle/course:viewhiddenuserfields', $context)) {
193 $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
194 }
195
359e9d83
MN
196 // Add column for groups if the user can view them.
197 $canseegroups = !isset($hiddenfields['groups']);
198 if ($canseegroups) {
199 $headers[] = get_string('groups');
200 $columns[] = 'groups';
201 }
202
bc47b706 203 // Do not show the columns if it exists in the hiddenfields array.
bc47b706
MN
204 if (!isset($hiddenfields['lastaccess'])) {
205 if ($courseid == SITEID) {
206 $headers[] = get_string('lastsiteaccess');
207 } else {
208 $headers[] = get_string('lastcourseaccess');
209 }
210 $columns[] = 'lastaccess';
211 }
212
fb792967 213 $canreviewenrol = has_capability('moodle/course:enrolreview', $context);
ca560952 214 if ($canreviewenrol && $courseid != SITEID) {
fb792967
JP
215 $columns[] = 'status';
216 $headers[] = get_string('participationstatus', 'enrol');
217 $this->no_sorting('status');
218 };
219
bc47b706
MN
220 $this->define_columns($columns);
221 $this->define_headers($headers);
222
1e67849c
AZ
223 // Make this table sorted by last name by default.
224 $this->sortable(true, 'lastname');
f7cd3bc0 225
bc47b706 226 $this->no_sorting('select');
cd3f250f 227 $this->no_sorting('roles');
359e9d83
MN
228 if ($canseegroups) {
229 $this->no_sorting('groups');
230 }
bc47b706
MN
231
232 $this->set_attribute('id', 'participants');
233
234 // Set the variables we need to use later.
bc47b706
MN
235 $this->currentgroup = $currentgroup;
236 $this->accesssince = $accesssince;
237 $this->roleid = $roleid;
238 $this->search = $search;
9651e491
JP
239 $this->enrolid = $enrolid;
240 $this->status = $status;
0c98acef 241 $this->countries = get_string_manager()->get_list_of_countries(true);
bc47b706 242 $this->extrafields = $extrafields;
f3ecea3a 243 $this->context = $context;
359e9d83
MN
244 if ($canseegroups) {
245 $this->groups = groups_get_all_groups($courseid, 0, 0, 'g.*', true);
246 }
5d0b4765
DW
247 $this->allroles = role_fix_names(get_all_roles($this->context), $this->context);
248 $this->assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false);
9df2fdec 249 $this->profileroles = get_profile_roles($this->context);
a63cd3e2 250 $this->viewableroles = get_viewable_roles($this->context);
bc47b706
MN
251 }
252
80d13bfe
JP
253 /**
254 * Render the participants table.
255 *
256 * @param int $pagesize Size of page for paginated displayed table.
257 * @param bool $useinitialsbar Whether to use the initials bar which will only be used if there is a fullname column defined.
258 * @param string $downloadhelpbutton
259 */
260 public function out($pagesize, $useinitialsbar, $downloadhelpbutton = '') {
261 global $PAGE;
262
263 parent::out($pagesize, $useinitialsbar, $downloadhelpbutton);
264
265 if (has_capability('moodle/course:enrolreview', $this->context)) {
266 $params = ['contextid' => $this->context->id, 'courseid' => $this->course->id];
267 $PAGE->requires->js_call_amd('core_user/status_field', 'init', [$params]);
268 }
269 }
270
bc47b706
MN
271 /**
272 * Generate the select column.
273 *
274 * @param \stdClass $data
275 * @return string
276 */
277 public function col_select($data) {
df92be9d
JP
278 global $OUTPUT;
279
280 $checkbox = new \core\output\checkbox_toggleall('participants-table', false, [
281 'classes' => 'usercheckbox m-1',
1cac0870 282 'id' => 'user' . $data->id,
df92be9d 283 'name' => 'user' . $data->id,
1cac0870
JP
284 'checked' => $this->selectall,
285 'label' => get_string('selectitem', 'moodle', fullname($data)),
286 'labelclasses' => 'accesshide',
df92be9d
JP
287 ]);
288
289 return $OUTPUT->render($checkbox);
bc47b706
MN
290 }
291
292 /**
293 * Generate the fullname column.
294 *
295 * @param \stdClass $data
296 * @return string
297 */
298 public function col_fullname($data) {
299 global $OUTPUT;
300
c5d59db9 301 return $OUTPUT->user_picture($data, array('size' => 35, 'courseid' => $this->course->id, 'includefullname' => true));
bc47b706
MN
302 }
303
5d0b4765
DW
304 /**
305 * User roles column.
306 *
307 * @param \stdClass $data
308 * @return string
309 */
310 public function col_roles($data) {
311 global $OUTPUT;
312
0ae28fad 313 $roles = isset($this->allroleassignments[$data->id]) ? $this->allroleassignments[$data->id] : [];
5d0b4765
DW
314 $editable = new \core_user\output\user_roles_editable($this->course,
315 $this->context,
316 $data,
317 $this->allroles,
318 $this->assignableroles,
9df2fdec 319 $this->profileroles,
a63cd3e2
AH
320 $roles,
321 $this->viewableroles);
5d0b4765
DW
322
323 return $OUTPUT->render_from_template('core/inplace_editable', $editable->export_for_template($OUTPUT));
324 }
325
2fa35b8d
DW
326 /**
327 * Generate the groups column.
328 *
f3ecea3a 329 * @param \stdClass $data
2fa35b8d
DW
330 * @return string
331 */
f3ecea3a 332 public function col_groups($data) {
2fa35b8d
DW
333 global $OUTPUT;
334
335 $usergroups = [];
336 foreach ($this->groups as $coursegroup) {
f3ecea3a 337 if (isset($coursegroup->members[$data->id])) {
2fa35b8d
DW
338 $usergroups[] = $coursegroup->id;
339 }
340 }
f3ecea3a 341 $editable = new \core_group\output\user_groups_editable($this->course, $this->context, $data, $this->groups, $usergroups);
2fa35b8d
DW
342 return $OUTPUT->render_from_template('core/inplace_editable', $editable->export_for_template($OUTPUT));
343 }
344
bc47b706
MN
345 /**
346 * Generate the country column.
347 *
348 * @param \stdClass $data
349 * @return string
350 */
351 public function col_country($data) {
352 if (!empty($this->countries[$data->country])) {
353 return $this->countries[$data->country];
354 }
355 return '';
356 }
357
358 /**
359 * Generate the last access column.
360 *
361 * @param \stdClass $data
362 * @return string
363 */
364 public function col_lastaccess($data) {
365 if ($data->lastaccess) {
366 return format_time(time() - $data->lastaccess);
367 }
368
369 return get_string('never');
370 }
371
fb792967
JP
372 /**
373 * Generate the status column.
374 *
80d13bfe 375 * @param \stdClass $data The data object.
fb792967
JP
376 * @return string
377 */
378 public function col_status($data) {
379 global $CFG, $OUTPUT, $PAGE;
380
381 $enrolstatusoutput = '';
382 $canreviewenrol = has_capability('moodle/course:enrolreview', $this->context);
383 if ($canreviewenrol) {
c157e137
MH
384 $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->context);
385 $fullname = fullname($data, $canviewfullnames);
4a42d3de 386 $coursename = format_string($this->course->fullname, true, array('context' => $this->context));
fb792967
JP
387 require_once($CFG->dirroot . '/enrol/locallib.php');
388 $manager = new \course_enrolment_manager($PAGE, $this->course);
389 $userenrolments = $manager->get_user_enrolments($data->id);
390 foreach ($userenrolments as $ue) {
fb792967
JP
391 $timestart = $ue->timestart;
392 $timeend = $ue->timeend;
6676f202 393 $timeenrolled = $ue->timecreated;
90ffcfa8
JP
394 $actions = $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue);
395 $instancename = $ue->enrolmentinstancename;
396
397 // Default status field label and value.
398 $status = get_string('participationactive', 'enrol');
399 $statusval = status_field::STATUS_ACTIVE;
fb792967
JP
400 switch ($ue->status) {
401 case ENROL_USER_ACTIVE:
402 $currentdate = new DateTime();
403 $now = $currentdate->getTimestamp();
3449816e
SA
404 $isexpired = $timestart > $now || ($timeend > 0 && $timeend < $now);
405 $enrolmentdisabled = $ue->enrolmentinstance->status == ENROL_INSTANCE_DISABLED;
406 // If user enrolment status has not yet started/already ended or the enrolment instance is disabled.
407 if ($isexpired || $enrolmentdisabled) {
fb792967 408 $status = get_string('participationnotcurrent', 'enrol');
90ffcfa8 409 $statusval = status_field::STATUS_NOT_CURRENT;
fb792967
JP
410 }
411 break;
412 case ENROL_USER_SUSPENDED:
413 $status = get_string('participationsuspended', 'enrol');
90ffcfa8 414 $statusval = status_field::STATUS_SUSPENDED;
fb792967
JP
415 break;
416 }
90ffcfa8 417
26b34c30
AA
418 $statusfield = new status_field($instancename, $coursename, $fullname, $status, $timestart, $timeend,
419 $actions, $timeenrolled);
90ffcfa8 420 $statusfielddata = $statusfield->set_status($statusval)->export_for_template($OUTPUT);
80d13bfe 421 $enrolstatusoutput .= $OUTPUT->render_from_template('core_user/status_field', $statusfielddata);
fb792967
JP
422 }
423 }
424 return $enrolstatusoutput;
425 }
426
bc47b706
MN
427 /**
428 * This function is used for the extra user fields.
429 *
430 * These are being dynamically added to the table so there are no functions 'col_<userfieldname>' as
431 * the list has the potential to increase in the future and we don't want to have to remember to add
432 * a new method to this class. We also don't want to pollute this class with unnecessary methods.
433 *
434 * @param string $colname The column name
435 * @param \stdClass $data
436 * @return string
437 */
438 public function other_cols($colname, $data) {
439 // Do not process if it is not a part of the extra fields.
440 if (!in_array($colname, $this->extrafields)) {
441 return '';
442 }
443
444 return s($data->{$colname});
445 }
446
447 /**
448 * Query the database for results to display in the table.
449 *
450 * @param int $pagesize size of page for paginated displayed table.
451 * @param bool $useinitialsbar do you want to use the initials bar.
452 */
453 public function query_db($pagesize, $useinitialsbar = true) {
454 list($twhere, $tparams) = $this->get_sql_where();
455
f3ecea3a 456 $total = user_get_total_participants($this->course->id, $this->currentgroup, $this->accesssince,
9651e491 457 $this->roleid, $this->enrolid, $this->status, $this->search, $twhere, $tparams);
bc47b706
MN
458
459 $this->pagesize($pagesize, $total);
460
461 $sort = $this->get_sql_sort();
462 if ($sort) {
463 $sort = 'ORDER BY ' . $sort;
464 }
465
5359c517 466 $rawdata = user_get_participants($this->course->id, $this->currentgroup, $this->accesssince,
9651e491 467 $this->roleid, $this->enrolid, $this->status, $this->search, $twhere, $tparams, $sort, $this->get_page_start(),
bc47b706 468 $this->get_page_size());
5359c517
TH
469 $this->rawdata = [];
470 foreach ($rawdata as $user) {
471 $this->rawdata[$user->id] = $user;
472 }
473 $rawdata->close();
474
475 if ($this->rawdata) {
476 $this->allroleassignments = get_users_roles($this->context, array_keys($this->rawdata),
477 true, 'c.contextlevel DESC, r.sortorder ASC');
478 } else {
479 $this->allroleassignments = [];
480 }
bc47b706
MN
481
482 // Set initial bars.
483 if ($useinitialsbar) {
484 $this->initialbars(true);
485 }
486 }
df92be9d
JP
487
488 /**
489 * Override the table show_hide_link to not show for select column.
490 *
491 * @param string $column the column name, index into various names.
492 * @param int $index numerical index of the column.
493 * @return string HTML fragment.
494 */
495 protected function show_hide_link($column, $index) {
496 if ($index > 0) {
497 return parent::show_hide_link($column, $index);
498 }
499 return '';
500 }
bc47b706
MN
501}
502