MDL-60681 lib/tablelib.php: Make flexible_table class better extendable
[moodle.git] / lib / tablelib.php
CommitLineData
72fb21b6 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
78bfb562
PS
19 * @package core
20 * @subpackage lib
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
72fb21b6 23 */
24
9683db71 25
78bfb562
PS
26defined('MOODLE_INTERNAL') || die();
27
4b7079c1
TH
28/**#@+
29 * These constants relate to the table's handling of URL parameters.
30 */
e2ba85e9 31define('TABLE_VAR_SORT', 1);
32define('TABLE_VAR_HIDE', 2);
33define('TABLE_VAR_SHOW', 3);
34define('TABLE_VAR_IFIRST', 4);
35define('TABLE_VAR_ILAST', 5);
36define('TABLE_VAR_PAGE', 6);
bf7c844e 37define('TABLE_VAR_RESET', 7);
4b7079c1 38/**#@-*/
e2ba85e9 39
4b7079c1
TH
40/**#@+
41 * Constants that indicate whether the paging bar for the table
42 * appears above or below the table.
43 */
44define('TABLE_P_TOP', 1);
45define('TABLE_P_BOTTOM', 2);
46/**#@-*/
20e1f1c0 47
9683db71 48
72fb21b6 49/**
50 * @package moodlecore
51 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 */
7270d81f 54class flexible_table {
55
56 var $uniqueid = NULL;
57 var $attributes = array();
58 var $headers = array();
3fed76e4
SR
59
60 /**
61 * @var string For create header with help icon.
62 */
63 private $helpforheaders = array();
7270d81f 64 var $columns = array();
65 var $column_style = array();
554906f6 66 var $column_class = array();
7270d81f 67 var $column_suppress = array();
353f3f20 68 var $column_nosort = array('userpic');
1e4bd9fe 69 private $column_textsort = array();
3fca6937 70 /** @var boolean Stores if setup has already been called on this flixible table. */
7270d81f 71 var $setup = false;
7270d81f 72 var $baseurl = NULL;
e2ba85e9 73 var $request = array();
7270d81f 74
f5ba1b93
TB
75 /**
76 * @var bool Whether or not to store table properties in the user_preferences table.
77 */
78 private $persistent = false;
7270d81f 79 var $is_collapsible = false;
80 var $is_sortable = false;
81 var $use_pages = false;
82 var $use_initials = false;
83
73e4f589 84 var $maxsortkeys = 2;
85 var $pagesize = 30;
86 var $currpage = 0;
87 var $totalrows = 0;
fdf70473 88 var $currentrow = 0;
a5a3f48a 89 var $sort_default_column = NULL;
90 var $sort_default_order = SORT_ASC;
9cf4a18b 91
20e1f1c0 92 /**
93 * Array of positions in which to display download controls.
94 */
95 var $showdownloadbuttonsat= array(TABLE_P_TOP);
96
1f9ca535 97 /**
98 * @var string Key of field returned by db query that is the id field of the
99 * user table or equivalent.
100 */
101 public $useridfield = 'id';
102
20e1f1c0 103 /**
104 * @var string which download plugin to use. Default '' means none - print
105 * html table with paging. Property set by is_downloading which typically
106 * passes in cleaned data from $
107 */
108 var $download = '';
9cf4a18b 109
20e1f1c0 110 /**
ba9164e5 111 * @var bool whether data is downloadable from table. Determines whether
20e1f1c0 112 * to display download buttons. Set by method downloadable().
113 */
114 var $downloadable = false;
9cf4a18b 115
20e1f1c0 116 /**
ba9164e5 117 * @var bool Has start output been called yet?
20e1f1c0 118 */
119 var $started_output = false;
9cf4a18b 120
20e1f1c0 121 var $exportclass = null;
9cf4a18b 122
f5ba1b93
TB
123 /**
124 * @var array For storing user-customised table properties in the user_preferences db table.
125 */
126 private $prefs = array();
127
faf45f9c
MN
128 /** @var $sheettitle */
129 protected $sheettitle;
130
131 /** @var $filename */
132 protected $filename;
133
561d406b 134 /**
135 * Constructor
29406dde 136 * @param string $uniqueid all tables have to have a unique id, this is used
ba9164e5 137 * as a key when storing table properties like sort order in the session.
561d406b 138 */
a49c17b4 139 function __construct($uniqueid) {
7270d81f 140 $this->uniqueid = $uniqueid;
e2ba85e9 141 $this->request = array(
ba9164e5
TH
142 TABLE_VAR_SORT => 'tsort',
143 TABLE_VAR_HIDE => 'thide',
144 TABLE_VAR_SHOW => 'tshow',
145 TABLE_VAR_IFIRST => 'tifirst',
146 TABLE_VAR_ILAST => 'tilast',
147 TABLE_VAR_PAGE => 'page',
bf7c844e 148 TABLE_VAR_RESET => 'treset'
e2ba85e9 149 );
7270d81f 150 }
20e1f1c0 151
152 /**
153 * Call this to pass the download type. Use :
154 * $download = optional_param('download', '', PARAM_ALPHA);
155 * To get the download type. We assume that if you call this function with
156 * params that this table's data is downloadable, so we call is_downloadable
157 * for you (even if the param is '', which means no download this time.
158 * Also you can call this method with no params to get the current set
159 * download type.
bdb80f6a 160 * @param string $download dataformat type. One of csv, xhtml, ods, etc
20e1f1c0 161 * @param string $filename filename for downloads without file extension.
162 * @param string $sheettitle title for downloaded data.
bdb80f6a 163 * @return string download dataformat type. One of csv, xhtml, ods, etc
20e1f1c0 164 */
9683db71
TH
165 function is_downloading($download = null, $filename='', $sheettitle='') {
166 if ($download!==null) {
20e1f1c0 167 $this->sheettitle = $sheettitle;
168 $this->is_downloadable(true);
169 $this->download = $download;
43ec99aa 170 $this->filename = clean_filename($filename);
171 $this->export_class_instance();
20e1f1c0 172 }
173 return $this->download;
174 }
117bd748 175
ba9164e5
TH
176 /**
177 * Get, and optionally set, the export class.
178 * @param $exportclass (optional) if passed, set the table to use this export class.
179 * @return table_default_export_format_parent the export class in use (after any set).
180 */
181 function export_class_instance($exportclass = null) {
9683db71 182 if (!is_null($exportclass)) {
869309b8 183 $this->started_output = true;
ba9164e5
TH
184 $this->exportclass = $exportclass;
185 $this->exportclass->table = $this;
186 } else if (is_null($this->exportclass) && !empty($this->download)) {
bdb80f6a 187 $this->exportclass = new table_dataformat_export_format($this, $this->download);
9683db71 188 if (!$this->exportclass->document_started()) {
faf45f9c 189 $this->exportclass->start_document($this->filename, $this->sheettitle);
43ec99aa 190 }
191 }
192 return $this->exportclass;
193 }
117bd748 194
20e1f1c0 195 /**
196 * Probably don't need to call this directly. Calling is_downloading with a
197 * param automatically sets table as downloadable.
9cf4a18b 198 *
ba9164e5 199 * @param bool $downloadable optional param to set whether data from
20e1f1c0 200 * table is downloadable. If ommitted this function can be used to get
201 * current state of table.
ba9164e5 202 * @return bool whether table data is set to be downloadable.
20e1f1c0 203 */
9683db71
TH
204 function is_downloadable($downloadable = null) {
205 if ($downloadable !== null) {
20e1f1c0 206 $this->downloadable = $downloadable;
207 }
208 return $this->downloadable;
209 }
9cf4a18b 210
f5ba1b93
TB
211 /**
212 * Call with boolean true to store table layout changes in the user_preferences table.
213 * Note: user_preferences.value has a maximum length of 1333 characters.
214 * Call with no parameter to get current state of table persistence.
215 *
216 * @param bool $persistent Optional parameter to set table layout persistence.
217 * @return bool Whether or not the table layout preferences will persist.
218 */
219 public function is_persistent($persistent = null) {
220 if ($persistent == true) {
221 $this->persistent = true;
222 }
223 return $this->persistent;
224 }
225
20e1f1c0 226 /**
227 * Where to show download buttons.
228 * @param array $showat array of postions in which to show download buttons.
229 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
230 */
9683db71 231 function show_download_buttons_at($showat) {
20e1f1c0 232 $this->showdownloadbuttonsat = $showat;
233 }
9cf4a18b 234
561d406b 235 /**
9cf4a18b 236 * Sets the is_sortable variable to the given boolean, sort_default_column to
561d406b 237 * the given string, and the sort_default_order to the given integer.
238 * @param bool $bool
239 * @param string $defaultcolumn
240 * @param int $defaultorder
241 * @return void
242 */
a5a3f48a 243 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
7270d81f 244 $this->is_sortable = $bool;
a5a3f48a 245 $this->sort_default_column = $defaultcolumn;
246 $this->sort_default_order = $defaultorder;
7270d81f 247 }
248
1e4bd9fe
DW
249 /**
250 * Use text sorting functions for this column (required for text columns with Oracle).
94ffbef1
TH
251 * Be warned that you cannot use this with column aliases. You can only do this
252 * with real columns. See MDL-40481 for an example.
1e4bd9fe
DW
253 * @param string column name
254 */
255 function text_sorting($column) {
256 $this->column_textsort[] = $column;
257 }
258
353f3f20 259 /**
260 * Do not sort using this column
261 * @param string column name
262 */
263 function no_sorting($column) {
264 $this->column_nosort[] = $column;
265 }
266
267 /**
268 * Is the column sortable?
269 * @param string column name, null means table
270 * @return bool
271 */
9683db71 272 function is_sortable($column = null) {
353f3f20 273 if (empty($column)) {
274 return $this->is_sortable;
275 }
276 if (!$this->is_sortable) {
277 return false;
278 }
279 return !in_array($column, $this->column_nosort);
280 }
9683db71 281
561d406b 282 /**
283 * Sets the is_collapsible variable to the given boolean.
284 * @param bool $bool
285 * @return void
286 */
7270d81f 287 function collapsible($bool) {
288 $this->is_collapsible = $bool;
289 }
290
561d406b 291 /**
292 * Sets the use_pages variable to the given boolean.
293 * @param bool $bool
294 * @return void
295 */
7270d81f 296 function pageable($bool) {
297 $this->use_pages = $bool;
298 }
299
561d406b 300 /**
301 * Sets the use_initials variable to the given boolean.
302 * @param bool $bool
303 * @return void
304 */
7270d81f 305 function initialbars($bool) {
306 $this->use_initials = $bool;
307 }
308
561d406b 309 /**
310 * Sets the pagesize variable to the given integer, the totalrows variable
311 * to the given integer, and the use_pages variable to true.
312 * @param int $perpage
313 * @param int $total
314 * @return void
315 */
7270d81f 316 function pagesize($perpage, $total) {
317 $this->pagesize = $perpage;
318 $this->totalrows = $total;
319 $this->use_pages = true;
320 }
321
561d406b 322 /**
323 * Assigns each given variable in the array to the corresponding index
324 * in the request class variable.
325 * @param array $variables
326 * @return void
327 */
e2ba85e9 328 function set_control_variables($variables) {
9683db71
TH
329 foreach ($variables as $what => $variable) {
330 if (isset($this->request[$what])) {
e2ba85e9 331 $this->request[$what] = $variable;
332 }
333 }
334 }
335
561d406b 336 /**
337 * Gives the given $value to the $attribute index of $this->attributes.
338 * @param string $attribute
339 * @param mixed $value
340 * @return void
341 */
7270d81f 342 function set_attribute($attribute, $value) {
343 $this->attributes[$attribute] = $value;
344 }
345
561d406b 346 /**
9cf4a18b 347 * What this method does is set the column so that if the same data appears in
901e25d4 348 * consecutive rows, then it is not repeated.
9cf4a18b 349 *
901e25d4 350 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
351 * that when one student has made multiple attempts, their name is only printed in the row
352 * for their first attempt.
ba9164e5 353 * @param int $column the index of a column.
561d406b 354 */
7270d81f 355 function column_suppress($column) {
9683db71 356 if (isset($this->column_suppress[$column])) {
7270d81f 357 $this->column_suppress[$column] = true;
358 }
359 }
360
561d406b 361 /**
362 * Sets the given $column index to the given $classname in $this->column_class.
ba9164e5 363 * @param int $column
561d406b 364 * @param string $classname
365 * @return void
366 */
554906f6 367 function column_class($column, $classname) {
9683db71 368 if (isset($this->column_class[$column])) {
554906f6 369 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
370 }
371 }
372
561d406b 373 /**
374 * Sets the given $column index and $property index to the given $value in $this->column_style.
ba9164e5 375 * @param int $column
561d406b 376 * @param string $property
377 * @param mixed $value
378 * @return void
379 */
7270d81f 380 function column_style($column, $property, $value) {
9683db71 381 if (isset($this->column_style[$column])) {
7270d81f 382 $this->column_style[$column][$property] = $value;
383 }
384 }
385
561d406b 386 /**
20e1f1c0 387 * Sets all columns' $propertys to the given $value in $this->column_style.
ba9164e5 388 * @param int $property
561d406b 389 * @param string $value
390 * @return void
391 */
7270d81f 392 function column_style_all($property, $value) {
9683db71 393 foreach (array_keys($this->columns) as $column) {
7270d81f 394 $this->column_style[$column][$property] = $value;
395 }
396 }
397
561d406b 398 /**
59f392b3
TH
399 * Sets $this->baseurl.
400 * @param moodle_url|string $url the url with params needed to call up this page
561d406b 401 */
7270d81f 402 function define_baseurl($url) {
59f392b3 403 $this->baseurl = new moodle_url($url);
7270d81f 404 }
405
561d406b 406 /**
20e1f1c0 407 * @param array $columns an array of identifying names for columns. If
408 * columns are sorted then column names must correspond to a field in sql.
561d406b 409 */
7270d81f 410 function define_columns($columns) {
411 $this->columns = array();
412 $this->column_style = array();
554906f6 413 $this->column_class = array();
7270d81f 414 $colnum = 0;
415
9683db71 416 foreach ($columns as $column) {
7270d81f 417 $this->columns[$column] = $colnum++;
418 $this->column_style[$column] = array();
554906f6 419 $this->column_class[$column] = '';
7270d81f 420 $this->column_suppress[$column] = false;
421 }
422 }
423
561d406b 424 /**
20e1f1c0 425 * @param array $headers numerical keyed array of displayed string titles
426 * for each column.
561d406b 427 */
7270d81f 428 function define_headers($headers) {
429 $this->headers = $headers;
430 }
9cf4a18b 431
3fed76e4 432 /**
edbea936
MG
433 * Defines a help icon for the header
434 *
3fed76e4 435 * Always use this function if you need to create header with sorting and help icon.
edbea936 436 *
dd106c88 437 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
3fed76e4 438 */
dd106c88
JO
439 public function define_help_for_headers($helpicons) {
440 $this->helpforheaders = $helpicons;
3fed76e4
SR
441 }
442
561d406b 443 /**
20e1f1c0 444 * Must be called after table is defined. Use methods above first. Cannot
445 * use functions below till after calling this method.
561d406b 446 * @return type?
447 */
7270d81f 448 function setup() {
f5ba1b93 449 global $SESSION;
7270d81f 450
9683db71 451 if (empty($this->columns) || empty($this->uniqueid)) {
7270d81f 452 return false;
453 }
1e42af27 454
f5ba1b93
TB
455 // Load any existing user preferences.
456 if ($this->persistent) {
457 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
b6b38f77 458 $oldprefs = $this->prefs;
f5ba1b93
TB
459 } else if (isset($SESSION->flextable[$this->uniqueid])) {
460 $this->prefs = $SESSION->flextable[$this->uniqueid];
b6b38f77 461 $oldprefs = $this->prefs;
7270d81f 462 }
19168d09
DM
463
464 // Set up default preferences if needed.
465 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
f5ba1b93
TB
466 $this->prefs = array(
467 'collapse' => array(),
468 'sortby' => array(),
469 'i_first' => '',
470 'i_last' => '',
471 'textsort' => $this->column_textsort,
472 );
0ce8ba58 473 }
b6b38f77
IT
474
475 if (!isset($oldprefs)) {
476 $oldprefs = $this->prefs;
477 }
7270d81f 478
59f392b3
TH
479 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
480 isset($this->columns[$showcol])) {
f5ba1b93 481 $this->prefs['collapse'][$showcol] = false;
59f392b3 482
8b05c5e2 483 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
59f392b3 484 isset($this->columns[$hidecol])) {
f5ba1b93
TB
485 $this->prefs['collapse'][$hidecol] = true;
486 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
487 unset($this->prefs['sortby'][$hidecol]);
7270d81f 488 }
489 }
1e42af27 490
7270d81f 491 // Now, update the column attributes for collapsed columns
9683db71 492 foreach (array_keys($this->columns) as $column) {
f5ba1b93 493 if (!empty($this->prefs['collapse'][$column])) {
7270d81f 494 $this->column_style[$column]['width'] = '10px';
495 }
496 }
497
59f392b3 498 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
f5ba1b93 499 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
143aacae
AG
500 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
501 && isset($this->columns['fullname']))) {
59f392b3 502
f5ba1b93 503 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
59f392b3 504 // This key already exists somewhere. Change its sortorder and bring it to the top.
f5ba1b93
TB
505 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
506 unset($this->prefs['sortby'][$sortcol]);
507 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
59f392b3
TH
508 } else {
509 // Key doesn't exist, so just add it to the beginning of the array, ascending order
f5ba1b93 510 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
7270d81f 511 }
59f392b3
TH
512
513 // Finally, make sure that no more than $this->maxsortkeys are present into the array
f5ba1b93 514 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
7270d81f 515 }
516
f9e62127
DW
517 // MDL-35375 - If a default order is defined and it is not in the current list of order by columns, add it at the end.
518 // This prevents results from being returned in a random order if the only order by column contains equal values.
519 if (!empty($this->sort_default_column)) {
f5ba1b93 520 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
f9e62127 521 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
f5ba1b93 522 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
f9e62127 523 }
a5a3f48a 524 }
525
59f392b3
TH
526 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
527 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
f5ba1b93 528 $this->prefs['i_last'] = $ilast;
7270d81f 529 }
530
59f392b3
TH
531 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
532 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
f5ba1b93 533 $this->prefs['i_first'] = $ifirst;
7270d81f 534 }
535
f5ba1b93
TB
536 // Save user preferences if they have changed.
537 if ($this->prefs != $oldprefs) {
538 if ($this->persistent) {
539 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
540 } else {
541 $SESSION->flextable[$this->uniqueid] = $this->prefs;
542 }
543 }
544 unset($oldprefs);
545
9683db71 546 if (empty($this->baseurl)) {
59f392b3
TH
547 debugging('You should set baseurl when using flexible_table.');
548 global $PAGE;
549 $this->baseurl = $PAGE->url;
7270d81f 550 }
551
92ebcabe 552 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
7270d81f 553 $this->setup = true;
d1b523b7 554
59f392b3 555 // Always introduce the "flexible" class for the table if not specified
d1b523b7 556 if (empty($this->attributes)) {
557 $this->attributes['class'] = 'flexible';
d1b523b7 558 } else if (!isset($this->attributes['class'])) {
559 $this->attributes['class'] = 'flexible';
d1b523b7 560 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
561 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
562 }
9baf2670
TH
563 }
564
565 /**
f5ba1b93 566 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
9baf2670
TH
567 * @param string $uniqueid the identifier for a table.
568 * @return SQL fragment that can be used in an ORDER BY clause.
569 */
570 public static function get_sort_for_table($uniqueid) {
571 global $SESSION;
f5ba1b93
TB
572 if (isset($SESSION->flextable[$uniqueid])) {
573 $prefs = $SESSION->flextable[$uniqueid];
574 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
575 return '';
9baf2670 576 }
d1b523b7 577
f5ba1b93 578 if (empty($prefs['sortby'])) {
9baf2670
TH
579 return '';
580 }
f5ba1b93
TB
581 if (empty($prefs['textsort'])) {
582 $prefs['textsort'] = array();
d495f2d7 583 }
9baf2670 584
f5ba1b93 585 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
7270d81f 586 }
587
561d406b 588 /**
9baf2670
TH
589 * Prepare an an order by clause from the list of columns to be sorted.
590 * @param array $cols column name => SORT_ASC or SORT_DESC
591 * @return SQL fragment that can be used in an ORDER BY clause.
561d406b 592 */
1e4bd9fe
DW
593 public static function construct_order_by($cols, $textsortcols=array()) {
594 global $DB;
9baf2670
TH
595 $bits = array();
596
9683db71 597 foreach ($cols as $column => $order) {
1e4bd9fe
DW
598 if (in_array($column, $textsortcols)) {
599 $column = $DB->sql_order_by_text($column);
600 }
9baf2670
TH
601 if ($order == SORT_ASC) {
602 $bits[] = $column . ' ASC';
603 } else {
604 $bits[] = $column . ' DESC';
9013e4ad 605 }
9013e4ad 606 }
9baf2670
TH
607
608 return implode(', ', $bits);
609 }
610
611 /**
612 * @return SQL fragment that can be used in an ORDER BY clause.
613 */
614 public function get_sql_sort() {
1e4bd9fe 615 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
9baf2670
TH
616 }
617
618 /**
619 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
620 * @return array column name => SORT_... constant.
621 */
622 public function get_sort_columns() {
623 if (!$this->setup) {
624 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
7270d81f 625 }
9013e4ad 626
f5ba1b93 627 if (empty($this->prefs['sortby'])) {
9baf2670 628 return array();
7270d81f 629 }
9baf2670 630
f5ba1b93 631 foreach ($this->prefs['sortby'] as $column => $notused) {
e81eed54
TH
632 if (isset($this->columns[$column])) {
633 continue; // This column is OK.
634 }
143aacae 635 if (in_array($column, get_all_user_name_fields()) &&
e81eed54
TH
636 isset($this->columns['fullname'])) {
637 continue; // This column is OK.
638 }
639 // This column is not OK.
f5ba1b93 640 unset($this->prefs['sortby'][$column]);
e81eed54
TH
641 }
642
f5ba1b93 643 return $this->prefs['sortby'];
7270d81f 644 }
645
561d406b 646 /**
ba9164e5 647 * @return int the offset for LIMIT clause of SQL
561d406b 648 */
7270d81f 649 function get_page_start() {
9683db71 650 if (!$this->use_pages) {
7270d81f 651 return '';
652 }
653 return $this->currpage * $this->pagesize;
654 }
655
561d406b 656 /**
ba9164e5 657 * @return int the pagesize for LIMIT clause of SQL
561d406b 658 */
7270d81f 659 function get_page_size() {
9683db71 660 if (!$this->use_pages) {
7270d81f 661 return '';
662 }
663 return $this->pagesize;
664 }
665
561d406b 666 /**
e81eed54 667 * @return string sql to add to where statement.
561d406b 668 */
7270d81f 669 function get_sql_where() {
7e60297f 670 global $DB;
7270d81f 671
20a79b43
PS
672 $conditions = array();
673 $params = array();
674
ee70439a
PS
675 if (isset($this->columns['fullname'])) {
676 static $i = 0;
677 $i++;
678
f5ba1b93 679 if (!empty($this->prefs['i_first'])) {
ee70439a 680 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
f5ba1b93 681 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
ee70439a 682 }
f5ba1b93 683 if (!empty($this->prefs['i_last'])) {
ee70439a 684 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
f5ba1b93 685 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
ee70439a 686 }
7270d81f 687 }
688
20a79b43 689 return array(implode(" AND ", $conditions), $params);
7270d81f 690 }
691
561d406b 692 /**
ac3e5ed7
JP
693 * Add a row of data to the table. This function takes an array or object with
694 * column names as keys or property names.
695 *
20e1f1c0 696 * It ignores any elements with keys that are not defined as columns. It
697 * puts in empty strings into the row when there is no element in the passed
698 * array corresponding to a column in the table. It puts the row elements in
ac3e5ed7
JP
699 * the proper order (internally row table data is stored by in arrays with
700 * a numerical index corresponding to the column number).
701 *
702 * @param object|array $rowwithkeys array keys or object property names are column names,
703 * as defined in call to define_columns.
c7ecf78e 704 * @param string $classname CSS class name to add to this row's tr tag.
20e1f1c0 705 */
9683db71 706 function add_data_keyed($rowwithkeys, $classname = '') {
c7ecf78e 707 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
20e1f1c0 708 }
9cf4a18b 709
ac3e5ed7
JP
710 /**
711 * Add a number of rows to the table at once. And optionally finish output after they have been added.
712 *
713 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
714 * object or array is added to table. We expect properties for the row array as would be
715 * passed to add_data_keyed.
716 * @param bool $finish
717 */
718 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
719 foreach ($rowstoadd as $row) {
720 if (is_null($row)) {
721 $this->add_separator();
722 } else {
723 $this->add_data_keyed($this->format_row($row));
724 }
725 }
726 if ($finish) {
727 $this->finish_output(!$this->is_downloading());
728 }
729 }
730
20e1f1c0 731 /**
732 * Add a seperator line to table.
733 */
734 function add_separator() {
9683db71 735 if (!$this->setup) {
20e1f1c0 736 return false;
737 }
738 $this->add_data(NULL);
739 }
9cf4a18b 740
20e1f1c0 741 /**
742 * This method actually directly echoes the row passed to it now or adds it
743 * to the download. If this is the first row and start_output has not
744 * already been called this method also calls start_output to open the table
745 * or send headers for the downloaded.
746 * Can be used as before. print_html now calls finish_html to close table.
9cf4a18b 747 *
20e1f1c0 748 * @param array $row a numerically keyed row of data to add to the table.
c7ecf78e 749 * @param string $classname CSS class name to add to this row's tr tag.
ba9164e5 750 * @return bool success.
20e1f1c0 751 */
c7ecf78e 752 function add_data($row, $classname = '') {
9683db71 753 if (!$this->setup) {
20e1f1c0 754 return false;
755 }
9683db71 756 if (!$this->started_output) {
20e1f1c0 757 $this->start_output();
758 }
9683db71
TH
759 if ($this->exportclass!==null) {
760 if ($row === null) {
20e1f1c0 761 $this->exportclass->add_seperator();
762 } else {
763 $this->exportclass->add_data($row);
764 }
765 } else {
c7ecf78e 766 $this->print_row($row, $classname);
20e1f1c0 767 }
768 return true;
769 }
770
20e1f1c0 771 /**
772 * You should call this to finish outputting the table data after adding
773 * data to the table with add_data or add_data_keyed.
9cf4a18b 774 *
20e1f1c0 775 */
9683db71
TH
776 function finish_output($closeexportclassdoc = true) {
777 if ($this->exportclass!==null) {
43ec99aa 778 $this->exportclass->finish_table();
9683db71 779 if ($closeexportclassdoc) {
43ec99aa 780 $this->exportclass->finish_document();
781 }
9683db71 782 } else {
20e1f1c0 783 $this->finish_html();
784 }
785 }
9cf4a18b 786
20e1f1c0 787 /**
788 * Hook that can be overridden in child classes to wrap a table in a form
789 * for example. Called only when there is data to display and not
790 * downloading.
791 */
9683db71 792 function wrap_html_start() {
20e1f1c0 793 }
794
795 /**
796 * Hook that can be overridden in child classes to wrap a table in a form
797 * for example. Called only when there is data to display and not
798 * downloading.
799 */
9683db71 800 function wrap_html_finish() {
20e1f1c0 801 }
9cf4a18b 802
1f9ca535 803 /**
ac3e5ed7
JP
804 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
805 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
806 * displaying table as html, adding a div wrap, etc.
807 *
808 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
1f9ca535 809 *
ac3e5ed7 810 * @param array|object $row row of data from db used to make one row of the table.
1f9ca535 811 * @return array one row for the table, added using add_data_keyed method.
812 */
9683db71 813 function format_row($row) {
ac3e5ed7
JP
814 if (is_array($row)) {
815 $row = (object)$row;
816 }
1f9ca535 817 $formattedrow = array();
9683db71 818 foreach (array_keys($this->columns) as $column) {
1f9ca535 819 $colmethodname = 'col_'.$column;
9683db71 820 if (method_exists($this, $colmethodname)) {
1f9ca535 821 $formattedcolumn = $this->$colmethodname($row);
822 } else {
823 $formattedcolumn = $this->other_cols($column, $row);
9683db71 824 if ($formattedcolumn===NULL) {
1f9ca535 825 $formattedcolumn = $row->$column;
826 }
827 }
828 $formattedrow[$column] = $formattedcolumn;
829 }
830 return $formattedrow;
831 }
832
833 /**
834 * Fullname is treated as a special columname in tablelib and should always
835 * be treated the same as the fullname of a user.
836 * @uses $this->useridfield if the userid field is not expected to be id
837 * then you need to override $this->useridfield to point at the correct
838 * field for the user id.
839 *
ac3e5ed7
JP
840 * @param object $row the data from the db containing all fields from the
841 * users table necessary to construct the full name of the user in
842 * current language.
843 * @return string contents of cell in column 'fullname', for this row.
1f9ca535 844 */
9683db71 845 function col_fullname($row) {
ac3e5ed7 846 global $COURSE;
1f9ca535 847
4726ad4f
TH
848 $name = fullname($row);
849 if ($this->download) {
850 return $name;
851 }
abf72969 852
4726ad4f
TH
853 $userid = $row->{$this->useridfield};
854 if ($COURSE->id == SITEID) {
855 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
1f9ca535 856 } else {
4726ad4f
TH
857 $profileurl = new moodle_url('/user/view.php',
858 array('id' => $userid, 'course' => $COURSE->id));
1f9ca535 859 }
4726ad4f 860 return html_writer::link($profileurl, $name);
1f9ca535 861 }
862
863 /**
864 * You can override this method in a child class. See the description of
865 * build_table which calls this method.
866 */
9683db71 867 function other_cols($column, $row) {
1f9ca535 868 return NULL;
869 }
870
ef27e742 871 /**
872 * Used from col_* functions when text is to be displayed. Does the
873 * right thing - either converts text to html or strips any html tags
874 * depending on if we are downloading and what is the download type. Params
875 * are the same as format_text function in weblib.php but some default
876 * options are changed.
877 */
9683db71
TH
878 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
879 if (!$this->is_downloading()) {
880 if (is_null($options)) {
ef27e742 881 $options = new stdClass;
882 }
883 //some sensible defaults
9683db71 884 if (!isset($options->para)) {
ef27e742 885 $options->para = false;
886 }
9683db71 887 if (!isset($options->newlines)) {
ef27e742 888 $options->newlines = false;
889 }
890 if (!isset($options->smiley)) {
891 $options->smiley = false;
892 }
893 if (!isset($options->filter)) {
894 $options->filter = false;
895 }
896 return format_text($text, $format, $options);
897 } else {
1b17f2b0 898 $eci = $this->export_class_instance();
ef27e742 899 return $eci->format_text($text, $format, $options, $courseid);
900 }
901 }
20e1f1c0 902 /**
903 * This method is deprecated although the old api is still supported.
904 * @deprecated 1.9.2 - Jun 2, 2008
905 */
906 function print_html() {
9683db71 907 if (!$this->setup) {
20e1f1c0 908 return false;
909 }
910 $this->finish_html();
911 }
912
913 /**
914 * This function is not part of the public api.
915 * @return string initial of first name we are currently filtering by
561d406b 916 */
91bb59f4 917 function get_initial_first() {
9683db71 918 if (!$this->use_initials) {
91bb59f4 919 return NULL;
920 }
921
f5ba1b93 922 return $this->prefs['i_first'];
91bb59f4 923 }
924
561d406b 925 /**
20e1f1c0 926 * This function is not part of the public api.
927 * @return string initial of last name we are currently filtering by
561d406b 928 */
91bb59f4 929 function get_initial_last() {
9683db71 930 if (!$this->use_initials) {
91bb59f4 931 return NULL;
932 }
933
f5ba1b93 934 return $this->prefs['i_last'];
91bb59f4 935 }
9cf4a18b 936
ba9164e5
TH
937 /**
938 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
939 * @param array $alpha of letters in the alphabet.
940 * @param string $current the currently selected letter.
941 * @param string $class class name to add to this initial bar.
942 * @param string $title the name to put in front of this initial bar.
943 * @param string $urlvar URL parameter name for this initial.
8b844f70
IT
944 *
945 * @deprecated since Moodle 3.3
ba9164e5 946 */
6f0d3480 947 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
8b844f70
IT
948
949 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
950 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
951
6f0d3480 952 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
8b844f70 953 $title . ' : ';
6f0d3480 954 if ($current) {
8b844f70 955 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
6f0d3480 956 } else {
8b844f70 957 echo html_writer::tag('strong', get_string('all'));
d2df1109
BH
958 }
959
6f0d3480
TH
960 foreach ($alpha as $letter) {
961 if ($letter === $current) {
962 echo html_writer::tag('strong', $letter);
963 } else {
964 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
965 }
966 }
967
968 echo html_writer::end_tag('div');
969 }
970
561d406b 971 /**
20e1f1c0 972 * This function is not part of the public api.
561d406b 973 */
9683db71 974 function print_initials_bar() {
8b844f70 975 global $OUTPUT;
9cf4a18b 976
1480277c
TS
977 $ifirst = $this->get_initial_first();
978 $ilast = $this->get_initial_last();
979 if (is_null($ifirst)) {
980 $ifirst = '';
981 }
982 if (is_null($ilast)) {
983 $ilast = '';
984 }
8b844f70 985
1480277c
TS
986 if ((!empty($ifirst) || !empty($ilast) ||$this->use_initials)
987 && isset($this->columns['fullname'])) {
8b844f70
IT
988 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
989 $prefixlast = $this->request[TABLE_VAR_ILAST];
990 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
991 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
20e1f1c0 992 }
8b844f70 993
20e1f1c0 994 }
7270d81f 995
20e1f1c0 996 /**
997 * This function is not part of the public api.
998 */
9683db71 999 function print_nothing_to_display() {
3c159385 1000 global $OUTPUT;
bf7c844e
TB
1001
1002 // Render button to allow user to reset table preferences.
1003 echo $this->render_reset_button();
1004
db16ac50 1005 $this->print_initials_bar();
7270d81f 1006
3c159385 1007 echo $OUTPUT->heading(get_string('nothingtodisplay'));
20e1f1c0 1008 }
7270d81f 1009
20e1f1c0 1010 /**
1011 * This function is not part of the public api.
1012 */
9683db71
TH
1013 function get_row_from_keyed($rowwithkeys) {
1014 if (is_object($rowwithkeys)) {
20e1f1c0 1015 $rowwithkeys = (array)$rowwithkeys;
7270d81f 1016 }
f36a3308 1017 $row = array();
9683db71
TH
1018 foreach (array_keys($this->columns) as $column) {
1019 if (isset($rowwithkeys[$column])) {
20e1f1c0 1020 $row [] = $rowwithkeys[$column];
1021 } else {
1022 $row[] ='';
1023 }
7270d81f 1024 }
20e1f1c0 1025 return $row;
1026 }
9cf4a18b 1027
20e1f1c0 1028 /**
bdb80f6a
BH
1029 * Get the html for the download buttons
1030 *
1031 * Usually only use internally
20e1f1c0 1032 */
bdb80f6a
BH
1033 public function download_buttons() {
1034 global $OUTPUT;
1035
9683db71 1036 if ($this->is_downloadable() && !$this->is_downloading()) {
bdb80f6a
BH
1037 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1038 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
20e1f1c0 1039 } else {
1040 return '';
1041 }
1042 }
bdb80f6a 1043
20e1f1c0 1044 /**
1045 * This function is not part of the public api.
1046 * You don't normally need to call this. It is called automatically when
1047 * needed when you start adding data to the table.
9cf4a18b 1048 *
20e1f1c0 1049 */
9683db71 1050 function start_output() {
20e1f1c0 1051 $this->started_output = true;
9683db71 1052 if ($this->exportclass!==null) {
43ec99aa 1053 $this->exportclass->start_table($this->sheettitle);
20e1f1c0 1054 $this->exportclass->output_headers($this->headers);
1055 } else {
1056 $this->start_html();
1057 $this->print_headers();
46254044 1058 echo html_writer::start_tag('tbody');
20e1f1c0 1059 }
1060 }
7270d81f 1061
20e1f1c0 1062 /**
1063 * This function is not part of the public api.
1064 */
c7ecf78e 1065 function print_row($row, $classname = '') {
807241b9
AA
1066 echo $this->get_row_html($row, $classname);
1067 }
1068
1069 /**
1070 * Generate html code for the passed row.
1071 *
1072 * @param array $row Row data.
1073 * @param string $classname classes to add.
1074 *
1075 * @return string $html html code for the row passed.
1076 */
1077 public function get_row_html($row, $classname = '') {
20e1f1c0 1078 static $suppress_lastrow = NULL;
ba55be91 1079 $rowclasses = array();
c7ecf78e 1080
1081 if ($classname) {
1082 $rowclasses[] = $classname;
1083 }
1084
fdf70473 1085 $rowid = $this->uniqueid . '_r' . $this->currentrow;
807241b9 1086 $html = '';
fdf70473 1087
807241b9 1088 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
7270d81f 1089
20e1f1c0 1090 // If we have a separator, print it
eba40bfe 1091 if ($row === NULL) {
c7ecf78e 1092 $colcount = count($this->columns);
807241b9 1093 $html .= html_writer::tag('td', html_writer::tag('div', '',
76dc1e25
TH
1094 array('class' => 'tabledivider')), array('colspan' => $colcount));
1095
c7ecf78e 1096 } else {
1097 $colbyindex = array_flip($this->columns);
1098 foreach ($row as $index => $data) {
20e1f1c0 1099 $column = $colbyindex[$index];
76dc1e25 1100
f5ba1b93 1101 if (empty($this->prefs['collapse'][$column])) {
c7ecf78e 1102 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
76dc1e25 1103 $content = '&nbsp;';
c7ecf78e 1104 } else {
76dc1e25 1105 $content = $data;
20e1f1c0 1106 }
c7ecf78e 1107 } else {
76dc1e25 1108 $content = '&nbsp;';
20e1f1c0 1109 }
76dc1e25 1110
807241b9 1111 $html .= html_writer::tag('td', $content, array(
76dc1e25 1112 'class' => 'cell c' . $index . $this->column_class[$column],
fdf70473 1113 'id' => $rowid . '_c' . $index,
76dc1e25 1114 'style' => $this->make_styles_string($this->column_style[$column])));
20e1f1c0 1115 }
1116 }
c7ecf78e 1117
807241b9 1118 $html .= html_writer::end_tag('tr');
c7ecf78e 1119
7270d81f 1120 $suppress_enabled = array_sum($this->column_suppress);
c7ecf78e 1121 if ($suppress_enabled) {
20e1f1c0 1122 $suppress_lastrow = $row;
1123 }
fdf70473 1124 $this->currentrow++;
807241b9 1125 return $html;
20e1f1c0 1126 }
9683db71 1127
20e1f1c0 1128 /**
1129 * This function is not part of the public api.
1130 */
9683db71 1131 function finish_html() {
25911860 1132 global $OUTPUT;
20e1f1c0 1133 if (!$this->started_output) {
1134 //no data has been added to the table.
1135 $this->print_nothing_to_display();
76dc1e25 1136
20e1f1c0 1137 } else {
fdf70473
DW
1138 // Print empty rows to fill the table to the current pagesize.
1139 // This is done so the header aria-controls attributes do not point to
1140 // non existant elements.
3e227172 1141 $emptyrow = array_fill(0, count($this->columns), '');
fdf70473
DW
1142 while ($this->currentrow < $this->pagesize) {
1143 $this->print_row($emptyrow, 'emptyrow');
1144 }
1145
46254044 1146 echo html_writer::end_tag('tbody');
76dc1e25 1147 echo html_writer::end_tag('table');
f4136193 1148 echo html_writer::end_tag('div');
20e1f1c0 1149 $this->wrap_html_finish();
76dc1e25 1150
20e1f1c0 1151 // Paging bar
76dc1e25 1152 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
20e1f1c0 1153 echo $this->download_buttons();
1154 }
76dc1e25
TH
1155
1156 if($this->use_pages) {
929d7a83 1157 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
b28c784f 1158 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
929d7a83 1159 echo $OUTPUT->render($pagingbar);
20e1f1c0 1160 }
1161 }
9cf4a18b 1162 }
76dc1e25 1163
ba9164e5
TH
1164 /**
1165 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1166 * used by {@link print_headers()}.
1167 * @param string $column the column name, index into various names.
1168 * @param int $index numerical index of the column.
1169 * @return string HTML fragment.
1170 */
76dc1e25
TH
1171 protected function show_hide_link($column, $index) {
1172 global $OUTPUT;
1173 // Some headers contain <br /> tags, do not include in title, hence the
1174 // strip tags.
1175
fdf70473
DW
1176 $ariacontrols = '';
1177 for ($i = 0; $i < $this->pagesize; $i++) {
1178 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1179 }
1180
1181 $ariacontrols = trim($ariacontrols);
1182
f5ba1b93 1183 if (!empty($this->prefs['collapse'][$column])) {
fdf70473
DW
1184 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1185 'aria-expanded' => 'false',
1186 'aria-controls' => $ariacontrols);
76dc1e25 1187 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
663640f5 1188 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
76dc1e25
TH
1189
1190 } else if ($this->headers[$index] !== NULL) {
fdf70473
DW
1191 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1192 'aria-expanded' => 'true',
1193 'aria-controls' => $ariacontrols);
76dc1e25 1194 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
663640f5 1195 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
76dc1e25
TH
1196 }
1197 }
1198
20e1f1c0 1199 /**
1200 * This function is not part of the public api.
1201 */
9683db71 1202 function print_headers() {
f2a1963c 1203 global $CFG, $OUTPUT;
7270d81f 1204
28932052 1205 echo html_writer::start_tag('thead');
76dc1e25 1206 echo html_writer::start_tag('tr');
9683db71 1207 foreach ($this->columns as $column => $index) {
7270d81f 1208
76dc1e25 1209 $icon_hide = '';
9683db71 1210 if ($this->is_collapsible) {
76dc1e25 1211 $icon_hide = $this->show_hide_link($column, $index);
7270d81f 1212 }
1213
f5ba1b93
TB
1214 $primarysortcolumn = '';
1215 $primarysortorder = '';
1216 if (reset($this->prefs['sortby'])) {
1217 $primarysortcolumn = key($this->prefs['sortby']);
1218 $primarysortorder = current($this->prefs['sortby']);
73e4f589 1219 }
1220
9683db71 1221 switch ($column) {
7270d81f 1222
1223 case 'fullname':
a327f25e
AG
1224 // Check the full name display for sortable fields.
1225 $nameformat = $CFG->fullnamedisplay;
1226 if ($nameformat == 'language') {
1227 $nameformat = get_string('fullnamedisplay');
1228 }
143aacae 1229 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
a327f25e
AG
1230
1231 if (!empty($requirednames)) {
1232 if ($this->is_sortable($column)) {
1233 // Done this way for the possibility of more than two sortable full name display fields.
1234 $this->headers[$index] = '';
1235 foreach ($requirednames as $name) {
1236 $sortname = $this->sort_link(get_string($name),
edbea936 1237 $name, $primarysortcolumn === $name, $primarysortorder);
a327f25e
AG
1238 $this->headers[$index] .= $sortname . ' / ';
1239 }
edbea936
MG
1240 $helpicon = '';
1241 if (isset($this->helpforheaders[$index])) {
1242 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1243 }
1244 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
78bfb562 1245 }
7270d81f 1246 }
1247 break;
1248
1d40c70b 1249 case 'userpic':
9cf4a18b 1250 // do nothing, do not display sortable links
1d40c70b 1251 break;
1252
7270d81f 1253 default:
9683db71 1254 if ($this->is_sortable($column)) {
3fed76e4
SR
1255 $helpicon = '';
1256 if (isset($this->helpforheaders[$index])) {
edbea936 1257 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
3fed76e4 1258 }
76dc1e25 1259 $this->headers[$index] = $this->sort_link($this->headers[$index],
edbea936 1260 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
7270d81f 1261 }
1262 }
1e42af27 1263
76dc1e25
TH
1264 $attributes = array(
1265 'class' => 'header c' . $index . $this->column_class[$column],
1266 'scope' => 'col',
1267 );
9683db71 1268 if ($this->headers[$index] === NULL) {
76dc1e25 1269 $content = '&nbsp;';
f5ba1b93 1270 } else if (!empty($this->prefs['collapse'][$column])) {
76dc1e25 1271 $content = $icon_hide;
9683db71 1272 } else {
76dc1e25
TH
1273 if (is_array($this->column_style[$column])) {
1274 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1275 }
3fed76e4
SR
1276 $helpicon = '';
1277 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
edbea936 1278 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
3fed76e4
SR
1279 }
1280 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
76dc1e25 1281 $icon_hide, array('class' => 'commands'));
7270d81f 1282 }
76dc1e25
TH
1283 echo html_writer::tag('th', $content, $attributes);
1284 }
1285
1286 echo html_writer::end_tag('tr');
28932052 1287 echo html_writer::end_tag('thead');
76dc1e25
TH
1288 }
1289
ba9164e5
TH
1290 /**
1291 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1292 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1293 * @param int $order SORT_ASC or SORT_DESC
1294 * @return string HTML fragment.
1295 */
76dc1e25
TH
1296 protected function sort_icon($isprimary, $order) {
1297 global $OUTPUT;
7270d81f 1298
76dc1e25
TH
1299 if (!$isprimary) {
1300 return '';
1301 }
1302
1303 if ($order == SORT_ASC) {
663640f5 1304 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
76dc1e25 1305 } else {
663640f5 1306 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
76dc1e25
TH
1307 }
1308 }
1309
ba9164e5
TH
1310 /**
1311 * Generate the correct tool tip for changing the sort order. This is a
1312 * helper method used by {@link sort_link()}.
1313 * @param bool $isprimary whether the is column is the current primary sort column.
1314 * @param int $order SORT_ASC or SORT_DESC
1315 * @return string the correct title.
1316 */
76dc1e25
TH
1317 protected function sort_order_name($isprimary, $order) {
1318 if ($isprimary && $order != SORT_ASC) {
1319 return get_string('desc');
1320 } else {
1321 return get_string('asc');
7270d81f 1322 }
76dc1e25
TH
1323 }
1324
ba9164e5
TH
1325 /**
1326 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1327 * @param string $text the text for the link.
1328 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1329 * @param bool $isprimary whether the is column is the current primary sort column.
1330 * @param int $order SORT_ASC or SORT_DESC
1331 * @return string HTML fragment.
1332 */
edbea936 1333 protected function sort_link($text, $column, $isprimary, $order) {
76dc1e25
TH
1334 return html_writer::link($this->baseurl->out(false,
1335 array($this->request[TABLE_VAR_SORT] => $column)),
1336 $text . get_accesshide(get_string('sortby') . ' ' .
1337 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
edbea936 1338 $this->sort_icon($isprimary, $order);
20e1f1c0 1339 }
9cf4a18b 1340
20e1f1c0 1341 /**
1342 * This function is not part of the public api.
1343 */
9683db71 1344 function start_html() {
b28c784f 1345 global $OUTPUT;
bf7c844e
TB
1346
1347 // Render button to allow user to reset table preferences.
1348 echo $this->render_reset_button();
1349
20e1f1c0 1350 // Do we need to print initial bars?
1351 $this->print_initials_bar();
7270d81f 1352
1e42af27 1353 // Paging bar
9683db71 1354 if ($this->use_pages) {
929d7a83 1355 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
b28c784f 1356 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
929d7a83 1357 echo $OUTPUT->render($pagingbar);
1e42af27 1358 }
9cf4a18b 1359
9683db71 1360 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
20e1f1c0 1361 echo $this->download_buttons();
1362 }
9cf4a18b 1363
20e1f1c0 1364 $this->wrap_html_start();
1365 // Start of main data table
1366
76dc1e25
TH
1367 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1368 echo html_writer::start_tag('table', $this->attributes);
9cf4a18b 1369
7270d81f 1370 }
1371
561d406b 1372 /**
20e1f1c0 1373 * This function is not part of the public api.
76dc1e25
TH
1374 * @param array $styles CSS-property => value
1375 * @return string values suitably to go in a style="" attribute in HTML.
561d406b 1376 */
76dc1e25 1377 function make_styles_string($styles) {
9683db71 1378 if (empty($styles)) {
76dc1e25 1379 return null;
20e1f1c0 1380 }
1381
76dc1e25
TH
1382 $string = '';
1383 foreach($styles as $property => $value) {
1384 $string .= $property . ':' . $value . ';';
7270d81f 1385 }
20e1f1c0 1386 return $string;
1387 }
bf7c844e
TB
1388
1389 /**
1390 * Generate the HTML for the table preferences reset button.
1391 *
19168d09 1392 * @return string HTML fragment, empty string if no need to reset
bf7c844e 1393 */
19168d09
DM
1394 protected function render_reset_button() {
1395
1396 if (!$this->can_be_reset()) {
b5987836
AG
1397 return '';
1398 }
1399
bf7c844e
TB
1400 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1401
19168d09 1402 $html = html_writer::start_div('resettable mdl-right');
bf7c844e
TB
1403 $html .= html_writer::link($url, get_string('resettable'));
1404 $html .= html_writer::end_div();
1405
1406 return $html;
1407 }
19168d09
DM
1408
1409 /**
1410 * Are there some table preferences that can be reset?
1411 *
1412 * If true, then the "reset table preferences" widget should be displayed.
1413 *
1414 * @return bool
1415 */
1416 protected function can_be_reset() {
1417
1418 // Loop through preferences and make sure they are empty or set to the default value.
1419 foreach ($this->prefs as $prefname => $prefval) {
1420
1421 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1422 // Check if the actual sorting differs from the default one.
1423 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1424 return true;
1425 }
1426
1427 } else if ($prefname === 'collapse' and !empty($prefval)) {
1428 // Check if there are some collapsed columns (all are expanded by default).
1429 foreach ($prefval as $columnname => $iscollapsed) {
1430 if ($iscollapsed) {
1431 return true;
1432 }
1433 }
1434
1435 } else if (!empty($prefval)) {
1436 // For all other cases, we just check if some preference is set.
1437 return true;
1438 }
1439 }
1440
1441 return false;
1442 }
20e1f1c0 1443}
1444
9683db71 1445
72fb21b6 1446/**
1447 * @package moodlecore
1448 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1450 */
9683db71 1451class table_sql extends flexible_table {
9cf4a18b 1452
1453 public $countsql = NULL;
1454 public $countparams = NULL;
20e1f1c0 1455 /**
9cf4a18b 1456 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
20e1f1c0 1457 */
9cf4a18b 1458 public $sql = NULL;
20e1f1c0 1459 /**
1cfce08e 1460 * @var array|\Traversable Data fetched from the db.
20e1f1c0 1461 */
9cf4a18b 1462 public $rawdata = NULL;
1463
20e1f1c0 1464 /**
ba9164e5 1465 * @var bool Overriding default for this.
20e1f1c0 1466 */
9cf4a18b 1467 public $is_sortable = true;
20e1f1c0 1468 /**
ba9164e5 1469 * @var bool Overriding default for this.
20e1f1c0 1470 */
9cf4a18b 1471 public $is_collapsible = true;
1472
20e1f1c0 1473 /**
1474 * @param string $uniqueid a string identifying this table.Used as a key in
1475 * session vars.
1476 */
a49c17b4
TH
1477 function __construct($uniqueid) {
1478 parent::__construct($uniqueid);
20e1f1c0 1479 // some sensible defaults
1480 $this->set_attribute('cellspacing', '0');
1481 $this->set_attribute('class', 'generaltable generalbox');
7270d81f 1482 }
9cf4a18b 1483
20e1f1c0 1484 /**
1485 * Take the data returned from the db_query and go through all the rows
1486 * processing each col using either col_{columnname} method or other_cols
1487 * method or if other_cols returns NULL then put the data straight into the
1488 * table.
1cfce08e 1489 *
a938e409 1490 * After calling this function, don't forget to call close_recordset.
20e1f1c0 1491 */
a938e409 1492 public function build_table() {
1cfce08e
DM
1493
1494 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1495 return;
1496 }
1497 if (!$this->rawdata) {
1498 return;
1499 }
1500
1501 foreach ($this->rawdata as $row) {
1502 $formattedrow = $this->format_row($row);
1503 $this->add_data_keyed($formattedrow,
1504 $this->get_row_class($row));
1505 }
a938e409 1506 }
1cfce08e 1507
a938e409 1508 /**
1509 * Closes recordset (for use after building the table).
1510 */
1511 public function close_recordset() {
1512 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1513 $this->rawdata instanceof moodle_recordset)) {
1cfce08e 1514 $this->rawdata->close();
a938e409 1515 $this->rawdata = null;
20e1f1c0 1516 }
1517 }
1518
b08fb128
TH
1519 /**
1520 * Get any extra classes names to add to this row in the HTML.
1521 * @param $row array the data for this row.
1522 * @return string added to the class="" attribute of the tr.
1523 */
1524 function get_row_class($row) {
1525 return '';
1526 }
1527
20e1f1c0 1528 /**
1529 * This is only needed if you want to use different sql to count rows.
1530 * Used for example when perhaps all db JOINS are not needed when counting
1531 * records. You don't need to call this function the count_sql
1532 * will be generated automatically.
9cf4a18b 1533 *
20e1f1c0 1534 * We need to count rows returned by the db seperately to the query itself
1535 * as we need to know how many pages of data we have to display.
1536 */
9683db71 1537 function set_count_sql($sql, array $params = NULL) {
20e1f1c0 1538 $this->countsql = $sql;
9cf4a18b 1539 $this->countparams = $params;
20e1f1c0 1540 }
9cf4a18b 1541
20e1f1c0 1542 /**
1543 * Set the sql to query the db. Query will be :
1544 * SELECT $fields FROM $from WHERE $where
1545 * Of course you can use sub-queries, JOINS etc. by putting them in the
1546 * appropriate clause of the query.
1547 */
4acb33f6 1548 function set_sql($fields, $from, $where, array $params = array()) {
365a5941 1549 $this->sql = new stdClass();
20e1f1c0 1550 $this->sql->fields = $fields;
1551 $this->sql->from = $from;
1552 $this->sql->where = $where;
9cf4a18b 1553 $this->sql->params = $params;
20e1f1c0 1554 }
9cf4a18b 1555
20e1f1c0 1556 /**
1557 * Query the db. Store results in the table object for use by build_table.
9cf4a18b 1558 *
ba9164e5
TH
1559 * @param int $pagesize size of page for paginated displayed table.
1560 * @param bool $useinitialsbar do you want to use the initials bar. Bar
20e1f1c0 1561 * will only be used if there is a fullname column defined for the table.
1562 */
9683db71 1563 function query_db($pagesize, $useinitialsbar=true) {
9cf4a18b 1564 global $DB;
20e1f1c0 1565 if (!$this->is_downloading()) {
9683db71 1566 if ($this->countsql === NULL) {
20e1f1c0 1567 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
71811083 1568 $this->countparams = $this->sql->params;
20e1f1c0 1569 }
d8a3b87c 1570 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
20e1f1c0 1571 if ($useinitialsbar && !$this->is_downloading()) {
d8a3b87c 1572 $this->initialbars($grandtotal > $pagesize);
20e1f1c0 1573 }
9cf4a18b 1574
20a79b43
PS
1575 list($wsql, $wparams) = $this->get_sql_where();
1576 if ($wsql) {
1577 $this->countsql .= ' AND '.$wsql;
23040521 1578 $this->countparams = array_merge($this->countparams, $wparams);
20a79b43
PS
1579
1580 $this->sql->where .= ' AND '.$wsql;
1581 $this->sql->params = array_merge($this->sql->params, $wparams);
1582
0fa4107d 1583 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1584 } else {
d8a3b87c 1585 $total = $grandtotal;
20e1f1c0 1586 }
20e1f1c0 1587
20e1f1c0 1588 $this->pagesize($pagesize, $total);
1589 }
1590
1591 // Fetch the attempts
1592 $sort = $this->get_sql_sort();
e81eed54
TH
1593 if ($sort) {
1594 $sort = "ORDER BY $sort";
1595 }
1596 $sql = "SELECT
1597 {$this->sql->fields}
1598 FROM {$this->sql->from}
1599 WHERE {$this->sql->where}
1600 {$sort}";
1601
20e1f1c0 1602 if (!$this->is_downloading()) {
9cf4a18b 1603 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
20e1f1c0 1604 } else {
9cf4a18b 1605 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
20e1f1c0 1606 }
1607 }
9cf4a18b 1608
20e1f1c0 1609 /**
1610 * Convenience method to call a number of methods for you to display the
1611 * table.
1612 */
9683db71 1613 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
9cf4a18b 1614 global $DB;
9683db71 1615 if (!$this->columns) {
4e96165e
DM
1616 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1617 $this->sql->params, IGNORE_MULTIPLE);
20e1f1c0 1618 //if columns is not set then define columns as the keys of the rows returned
1619 //from the db.
1620 $this->define_columns(array_keys((array)$onerow));
1621 $this->define_headers(array_keys((array)$onerow));
1622 }
1623 $this->setup();
1624 $this->query_db($pagesize, $useinitialsbar);
1625 $this->build_table();
a938e409 1626 $this->close_recordset();
20e1f1c0 1627 $this->finish_output();
1628 }
1629}
1630
9683db71 1631
72fb21b6 1632/**
1633 * @package moodlecore
1634 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1636 */
9683db71 1637class table_default_export_format_parent {
20e1f1c0 1638 /**
1639 * @var flexible_table or child class reference pointing to table class
1640 * object from which to export data.
1641 */
1642 var $table;
117bd748 1643
43ec99aa 1644 /**
ba9164e5 1645 * @var bool output started. Keeps track of whether any output has been
43ec99aa 1646 * started yet.
1647 */
1648 var $documentstarted = false;
c4d0b752
MG
1649
1650 /**
1651 * Constructor
1652 *
1653 * @param flexible_table $table
1654 */
1655 public function __construct(&$table) {
20e1f1c0 1656 $this->table =& $table;
c4d0b752
MG
1657 }
1658
1659 /**
1660 * Old syntax of class constructor. Deprecated in PHP7.
1661 *
1662 * @deprecated since Moodle 3.1
1663 */
1664 public function table_default_export_format_parent(&$table) {
1665 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1666 self::__construct($table);
20e1f1c0 1667 }
117bd748 1668
9683db71 1669 function set_table(&$table) {
43ec99aa 1670 $this->table =& $table;
1671 }
20e1f1c0 1672
1673 function add_data($row) {
1674 return false;
1675 }
9683db71 1676
20e1f1c0 1677 function add_seperator() {
1678 return false;
1679 }
9683db71
TH
1680
1681 function document_started() {
43ec99aa 1682 return $this->documentstarted;
20e1f1c0 1683 }
ef27e742 1684 /**
1685 * Given text in a variety of format codings, this function returns
1686 * the text as safe HTML or as plain text dependent on what is appropriate
1687 * for the download format. The default removes all tags.
1688 */
9683db71 1689 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
ef27e742 1690 //use some whitespace to indicate where there was some line spacing.
1691 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1692 return strip_tags($text);
1693 }
7270d81f 1694}
1695
bdb80f6a
BH
1696/**
1697 * Dataformat exporter
1698 *
1699 * @package core
1700 * @subpackage tablelib
1701 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1703 */
1704class table_dataformat_export_format extends table_default_export_format_parent {
1705
1706 /** @var $dataformat */
1707 protected $dataformat;
1708
1709 /** @var $rownum */
1710 protected $rownum = 0;
1711
1712 /** @var $columns */
1713 protected $columns;
1714
1715 /**
1716 * Constructor
1717 *
1718 * @param string $table An sql table
1719 * @param string $dataformat type of dataformat for export
1720 */
1721 public function __construct(&$table, $dataformat) {
1722 parent::__construct($table);
1723
9df4ae41
DM
1724 if (ob_get_length()) {
1725 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
bdb80f6a
BH
1726 }
1727
1728 $classname = 'dataformat_' . $dataformat . '\writer';
1729 if (!class_exists($classname)) {
1730 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1731 }
1732 $this->dataformat = new $classname;
1733
1734 // The dataformat export time to first byte could take a while to generate...
1735 set_time_limit(0);
1736
1737 // Close the session so that the users other tabs in the same session are not blocked.
1738 \core\session\manager::write_close();
1739 }
1740
1741 /**
1742 * Start document
1743 *
1744 * @param string $filename
faf45f9c 1745 * @param string $sheettitle
bdb80f6a 1746 */
faf45f9c 1747 public function start_document($filename, $sheettitle) {
bdb80f6a
BH
1748 $this->documentstarted = true;
1749 $this->dataformat->set_filename($filename);
faf45f9c
MN
1750 $this->dataformat->send_http_headers();
1751 $this->dataformat->set_sheettitle($sheettitle);
1752 $this->dataformat->start_output();
bdb80f6a
BH
1753 }
1754
1755 /**
1756 * Start export
1757 *
1758 * @param string $sheettitle optional spreadsheet worksheet title
1759 */
1760 public function start_table($sheettitle) {
1761 $this->dataformat->set_sheettitle($sheettitle);
1762 }
1763
1764 /**
1765 * Output headers
1766 *
1767 * @param array $headers
1768 */
1769 public function output_headers($headers) {
1770 $this->columns = $headers;
faf45f9c 1771 if (method_exists($this->dataformat, 'write_header')) {
e0ee37e4 1772 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
faf45f9c
MN
1773 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1774 $this->dataformat->write_header($headers);
1775 } else {
1776 $this->dataformat->start_sheet($headers);
1777 }
bdb80f6a
BH
1778 }
1779
1780 /**
1781 * Add a row of data
1782 *
1783 * @param array $row One record of data
1784 */
1785 public function add_data($row) {
1786 $this->dataformat->write_record($row, $this->rownum++);
1787 return true;
1788 }
1789
1790 /**
1791 * Finish export
1792 */
1793 public function finish_table() {
faf45f9c 1794 if (method_exists($this->dataformat, 'write_footer')) {
e0ee37e4 1795 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
faf45f9c
MN
1796 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1797 $this->dataformat->write_footer($this->columns);
1798 } else {
1799 $this->dataformat->close_sheet($this->columns);
1800 }
bdb80f6a
BH
1801 }
1802
1803 /**
1804 * Finish download
1805 */
1806 public function finish_document() {
faf45f9c
MN
1807 $this->dataformat->close_output();
1808 exit();
bdb80f6a 1809 }
bdb80f6a 1810}
9683db71 1811