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