MDL-62618 user: Display full names consistently on users page
[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':
c157e137
MH
1224 // Check the full name display for sortable fields.
1225 if (has_capability('moodle/site:viewfullnames', context_system::instance())) {
1226 $nameformat = $CFG->alternativefullnameformat;
1227 } else {
1228 $nameformat = $CFG->fullnamedisplay;
1229 }
a327f25e 1230
c157e137
MH
1231 if ($nameformat == 'language') {
1232 $nameformat = get_string('fullnamedisplay');
1233 }
1234
1235 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1236
1237 if (!empty($requirednames)) {
1238 if ($this->is_sortable($column)) {
1239 // Done this way for the possibility of more than two sortable full name display fields.
1240 $this->headers[$index] = '';
1241 foreach ($requirednames as $name) {
1242 $sortname = $this->sort_link(get_string($name),
1243 $name, $primarysortcolumn === $name, $primarysortorder);
1244 $this->headers[$index] .= $sortname . ' / ';
1245 }
1246 $helpicon = '';
1247 if (isset($this->helpforheaders[$index])) {
1248 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1249 }
1250 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
edbea936 1251 }
78bfb562 1252 }
7270d81f 1253 break;
1254
1d40c70b 1255 case 'userpic':
9cf4a18b 1256 // do nothing, do not display sortable links
1d40c70b 1257 break;
1258
7270d81f 1259 default:
c157e137
MH
1260 if ($this->is_sortable($column)) {
1261 $helpicon = '';
1262 if (isset($this->helpforheaders[$index])) {
1263 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1264 }
1265 $this->headers[$index] = $this->sort_link($this->headers[$index],
1266 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
3fed76e4 1267 }
7270d81f 1268 }
1e42af27 1269
76dc1e25
TH
1270 $attributes = array(
1271 'class' => 'header c' . $index . $this->column_class[$column],
1272 'scope' => 'col',
1273 );
9683db71 1274 if ($this->headers[$index] === NULL) {
76dc1e25 1275 $content = '&nbsp;';
f5ba1b93 1276 } else if (!empty($this->prefs['collapse'][$column])) {
76dc1e25 1277 $content = $icon_hide;
9683db71 1278 } else {
76dc1e25
TH
1279 if (is_array($this->column_style[$column])) {
1280 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1281 }
3fed76e4
SR
1282 $helpicon = '';
1283 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
edbea936 1284 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
3fed76e4
SR
1285 }
1286 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
76dc1e25 1287 $icon_hide, array('class' => 'commands'));
7270d81f 1288 }
76dc1e25
TH
1289 echo html_writer::tag('th', $content, $attributes);
1290 }
1291
1292 echo html_writer::end_tag('tr');
28932052 1293 echo html_writer::end_tag('thead');
76dc1e25
TH
1294 }
1295
ba9164e5
TH
1296 /**
1297 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1298 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1299 * @param int $order SORT_ASC or SORT_DESC
1300 * @return string HTML fragment.
1301 */
76dc1e25
TH
1302 protected function sort_icon($isprimary, $order) {
1303 global $OUTPUT;
7270d81f 1304
76dc1e25
TH
1305 if (!$isprimary) {
1306 return '';
1307 }
1308
1309 if ($order == SORT_ASC) {
663640f5 1310 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
76dc1e25 1311 } else {
663640f5 1312 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
76dc1e25
TH
1313 }
1314 }
1315
ba9164e5
TH
1316 /**
1317 * Generate the correct tool tip for changing the sort order. This is a
1318 * helper method used by {@link sort_link()}.
1319 * @param bool $isprimary whether the is column is the current primary sort column.
1320 * @param int $order SORT_ASC or SORT_DESC
1321 * @return string the correct title.
1322 */
76dc1e25
TH
1323 protected function sort_order_name($isprimary, $order) {
1324 if ($isprimary && $order != SORT_ASC) {
1325 return get_string('desc');
1326 } else {
1327 return get_string('asc');
7270d81f 1328 }
76dc1e25
TH
1329 }
1330
ba9164e5
TH
1331 /**
1332 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1333 * @param string $text the text for the link.
1334 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1335 * @param bool $isprimary whether the is column is the current primary sort column.
1336 * @param int $order SORT_ASC or SORT_DESC
1337 * @return string HTML fragment.
1338 */
edbea936 1339 protected function sort_link($text, $column, $isprimary, $order) {
76dc1e25
TH
1340 return html_writer::link($this->baseurl->out(false,
1341 array($this->request[TABLE_VAR_SORT] => $column)),
1342 $text . get_accesshide(get_string('sortby') . ' ' .
1343 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
edbea936 1344 $this->sort_icon($isprimary, $order);
20e1f1c0 1345 }
9cf4a18b 1346
20e1f1c0 1347 /**
1348 * This function is not part of the public api.
1349 */
9683db71 1350 function start_html() {
b28c784f 1351 global $OUTPUT;
bf7c844e
TB
1352
1353 // Render button to allow user to reset table preferences.
1354 echo $this->render_reset_button();
1355
20e1f1c0 1356 // Do we need to print initial bars?
1357 $this->print_initials_bar();
7270d81f 1358
1e42af27 1359 // Paging bar
9683db71 1360 if ($this->use_pages) {
929d7a83 1361 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
b28c784f 1362 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
929d7a83 1363 echo $OUTPUT->render($pagingbar);
1e42af27 1364 }
9cf4a18b 1365
9683db71 1366 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
20e1f1c0 1367 echo $this->download_buttons();
1368 }
9cf4a18b 1369
20e1f1c0 1370 $this->wrap_html_start();
1371 // Start of main data table
1372
76dc1e25
TH
1373 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1374 echo html_writer::start_tag('table', $this->attributes);
9cf4a18b 1375
7270d81f 1376 }
1377
561d406b 1378 /**
20e1f1c0 1379 * This function is not part of the public api.
76dc1e25
TH
1380 * @param array $styles CSS-property => value
1381 * @return string values suitably to go in a style="" attribute in HTML.
561d406b 1382 */
76dc1e25 1383 function make_styles_string($styles) {
9683db71 1384 if (empty($styles)) {
76dc1e25 1385 return null;
20e1f1c0 1386 }
1387
76dc1e25
TH
1388 $string = '';
1389 foreach($styles as $property => $value) {
1390 $string .= $property . ':' . $value . ';';
7270d81f 1391 }
20e1f1c0 1392 return $string;
1393 }
bf7c844e
TB
1394
1395 /**
1396 * Generate the HTML for the table preferences reset button.
1397 *
19168d09 1398 * @return string HTML fragment, empty string if no need to reset
bf7c844e 1399 */
19168d09
DM
1400 protected function render_reset_button() {
1401
1402 if (!$this->can_be_reset()) {
b5987836
AG
1403 return '';
1404 }
1405
bf7c844e
TB
1406 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1407
19168d09 1408 $html = html_writer::start_div('resettable mdl-right');
bf7c844e
TB
1409 $html .= html_writer::link($url, get_string('resettable'));
1410 $html .= html_writer::end_div();
1411
1412 return $html;
1413 }
19168d09
DM
1414
1415 /**
1416 * Are there some table preferences that can be reset?
1417 *
1418 * If true, then the "reset table preferences" widget should be displayed.
1419 *
1420 * @return bool
1421 */
1422 protected function can_be_reset() {
1423
1424 // Loop through preferences and make sure they are empty or set to the default value.
1425 foreach ($this->prefs as $prefname => $prefval) {
1426
1427 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1428 // Check if the actual sorting differs from the default one.
1429 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1430 return true;
1431 }
1432
1433 } else if ($prefname === 'collapse' and !empty($prefval)) {
1434 // Check if there are some collapsed columns (all are expanded by default).
1435 foreach ($prefval as $columnname => $iscollapsed) {
1436 if ($iscollapsed) {
1437 return true;
1438 }
1439 }
1440
1441 } else if (!empty($prefval)) {
1442 // For all other cases, we just check if some preference is set.
1443 return true;
1444 }
1445 }
1446
1447 return false;
1448 }
20e1f1c0 1449}
1450
9683db71 1451
72fb21b6 1452/**
1453 * @package moodlecore
1454 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1456 */
9683db71 1457class table_sql extends flexible_table {
9cf4a18b 1458
1459 public $countsql = NULL;
1460 public $countparams = NULL;
20e1f1c0 1461 /**
9cf4a18b 1462 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
20e1f1c0 1463 */
9cf4a18b 1464 public $sql = NULL;
20e1f1c0 1465 /**
1cfce08e 1466 * @var array|\Traversable Data fetched from the db.
20e1f1c0 1467 */
9cf4a18b 1468 public $rawdata = NULL;
1469
20e1f1c0 1470 /**
ba9164e5 1471 * @var bool Overriding default for this.
20e1f1c0 1472 */
9cf4a18b 1473 public $is_sortable = true;
20e1f1c0 1474 /**
ba9164e5 1475 * @var bool Overriding default for this.
20e1f1c0 1476 */
9cf4a18b 1477 public $is_collapsible = true;
1478
20e1f1c0 1479 /**
1480 * @param string $uniqueid a string identifying this table.Used as a key in
1481 * session vars.
1482 */
a49c17b4
TH
1483 function __construct($uniqueid) {
1484 parent::__construct($uniqueid);
20e1f1c0 1485 // some sensible defaults
1486 $this->set_attribute('cellspacing', '0');
1487 $this->set_attribute('class', 'generaltable generalbox');
7270d81f 1488 }
9cf4a18b 1489
20e1f1c0 1490 /**
1491 * Take the data returned from the db_query and go through all the rows
1492 * processing each col using either col_{columnname} method or other_cols
1493 * method or if other_cols returns NULL then put the data straight into the
1494 * table.
1cfce08e 1495 *
a938e409 1496 * After calling this function, don't forget to call close_recordset.
20e1f1c0 1497 */
a938e409 1498 public function build_table() {
1cfce08e
DM
1499
1500 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1501 return;
1502 }
1503 if (!$this->rawdata) {
1504 return;
1505 }
1506
1507 foreach ($this->rawdata as $row) {
1508 $formattedrow = $this->format_row($row);
1509 $this->add_data_keyed($formattedrow,
1510 $this->get_row_class($row));
1511 }
a938e409 1512 }
1cfce08e 1513
a938e409 1514 /**
1515 * Closes recordset (for use after building the table).
1516 */
1517 public function close_recordset() {
1518 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1519 $this->rawdata instanceof moodle_recordset)) {
1cfce08e 1520 $this->rawdata->close();
a938e409 1521 $this->rawdata = null;
20e1f1c0 1522 }
1523 }
1524
b08fb128
TH
1525 /**
1526 * Get any extra classes names to add to this row in the HTML.
1527 * @param $row array the data for this row.
1528 * @return string added to the class="" attribute of the tr.
1529 */
1530 function get_row_class($row) {
1531 return '';
1532 }
1533
20e1f1c0 1534 /**
1535 * This is only needed if you want to use different sql to count rows.
1536 * Used for example when perhaps all db JOINS are not needed when counting
1537 * records. You don't need to call this function the count_sql
1538 * will be generated automatically.
9cf4a18b 1539 *
20e1f1c0 1540 * We need to count rows returned by the db seperately to the query itself
1541 * as we need to know how many pages of data we have to display.
1542 */
9683db71 1543 function set_count_sql($sql, array $params = NULL) {
20e1f1c0 1544 $this->countsql = $sql;
9cf4a18b 1545 $this->countparams = $params;
20e1f1c0 1546 }
9cf4a18b 1547
20e1f1c0 1548 /**
1549 * Set the sql to query the db. Query will be :
1550 * SELECT $fields FROM $from WHERE $where
1551 * Of course you can use sub-queries, JOINS etc. by putting them in the
1552 * appropriate clause of the query.
1553 */
4acb33f6 1554 function set_sql($fields, $from, $where, array $params = array()) {
365a5941 1555 $this->sql = new stdClass();
20e1f1c0 1556 $this->sql->fields = $fields;
1557 $this->sql->from = $from;
1558 $this->sql->where = $where;
9cf4a18b 1559 $this->sql->params = $params;
20e1f1c0 1560 }
9cf4a18b 1561
20e1f1c0 1562 /**
1563 * Query the db. Store results in the table object for use by build_table.
9cf4a18b 1564 *
ba9164e5
TH
1565 * @param int $pagesize size of page for paginated displayed table.
1566 * @param bool $useinitialsbar do you want to use the initials bar. Bar
20e1f1c0 1567 * will only be used if there is a fullname column defined for the table.
1568 */
9683db71 1569 function query_db($pagesize, $useinitialsbar=true) {
9cf4a18b 1570 global $DB;
20e1f1c0 1571 if (!$this->is_downloading()) {
9683db71 1572 if ($this->countsql === NULL) {
20e1f1c0 1573 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
71811083 1574 $this->countparams = $this->sql->params;
20e1f1c0 1575 }
d8a3b87c 1576 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
20e1f1c0 1577 if ($useinitialsbar && !$this->is_downloading()) {
d8a3b87c 1578 $this->initialbars($grandtotal > $pagesize);
20e1f1c0 1579 }
9cf4a18b 1580
20a79b43
PS
1581 list($wsql, $wparams) = $this->get_sql_where();
1582 if ($wsql) {
1583 $this->countsql .= ' AND '.$wsql;
23040521 1584 $this->countparams = array_merge($this->countparams, $wparams);
20a79b43
PS
1585
1586 $this->sql->where .= ' AND '.$wsql;
1587 $this->sql->params = array_merge($this->sql->params, $wparams);
1588
0fa4107d 1589 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1590 } else {
d8a3b87c 1591 $total = $grandtotal;
20e1f1c0 1592 }
20e1f1c0 1593
20e1f1c0 1594 $this->pagesize($pagesize, $total);
1595 }
1596
1597 // Fetch the attempts
1598 $sort = $this->get_sql_sort();
e81eed54
TH
1599 if ($sort) {
1600 $sort = "ORDER BY $sort";
1601 }
1602 $sql = "SELECT
1603 {$this->sql->fields}
1604 FROM {$this->sql->from}
1605 WHERE {$this->sql->where}
1606 {$sort}";
1607
20e1f1c0 1608 if (!$this->is_downloading()) {
9cf4a18b 1609 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
20e1f1c0 1610 } else {
9cf4a18b 1611 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
20e1f1c0 1612 }
1613 }
9cf4a18b 1614
20e1f1c0 1615 /**
1616 * Convenience method to call a number of methods for you to display the
1617 * table.
1618 */
9683db71 1619 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
9cf4a18b 1620 global $DB;
9683db71 1621 if (!$this->columns) {
4e96165e
DM
1622 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1623 $this->sql->params, IGNORE_MULTIPLE);
20e1f1c0 1624 //if columns is not set then define columns as the keys of the rows returned
1625 //from the db.
1626 $this->define_columns(array_keys((array)$onerow));
1627 $this->define_headers(array_keys((array)$onerow));
1628 }
1629 $this->setup();
1630 $this->query_db($pagesize, $useinitialsbar);
1631 $this->build_table();
a938e409 1632 $this->close_recordset();
20e1f1c0 1633 $this->finish_output();
1634 }
1635}
1636
9683db71 1637
72fb21b6 1638/**
1639 * @package moodlecore
1640 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1641 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1642 */
9683db71 1643class table_default_export_format_parent {
20e1f1c0 1644 /**
1645 * @var flexible_table or child class reference pointing to table class
1646 * object from which to export data.
1647 */
1648 var $table;
117bd748 1649
43ec99aa 1650 /**
ba9164e5 1651 * @var bool output started. Keeps track of whether any output has been
43ec99aa 1652 * started yet.
1653 */
1654 var $documentstarted = false;
c4d0b752
MG
1655
1656 /**
1657 * Constructor
1658 *
1659 * @param flexible_table $table
1660 */
1661 public function __construct(&$table) {
20e1f1c0 1662 $this->table =& $table;
c4d0b752
MG
1663 }
1664
1665 /**
1666 * Old syntax of class constructor. Deprecated in PHP7.
1667 *
1668 * @deprecated since Moodle 3.1
1669 */
1670 public function table_default_export_format_parent(&$table) {
1671 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1672 self::__construct($table);
20e1f1c0 1673 }
117bd748 1674
9683db71 1675 function set_table(&$table) {
43ec99aa 1676 $this->table =& $table;
1677 }
20e1f1c0 1678
1679 function add_data($row) {
1680 return false;
1681 }
9683db71 1682
20e1f1c0 1683 function add_seperator() {
1684 return false;
1685 }
9683db71
TH
1686
1687 function document_started() {
43ec99aa 1688 return $this->documentstarted;
20e1f1c0 1689 }
ef27e742 1690 /**
1691 * Given text in a variety of format codings, this function returns
1692 * the text as safe HTML or as plain text dependent on what is appropriate
1693 * for the download format. The default removes all tags.
1694 */
9683db71 1695 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
ef27e742 1696 //use some whitespace to indicate where there was some line spacing.
1697 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1698 return strip_tags($text);
1699 }
7270d81f 1700}
1701
bdb80f6a
BH
1702/**
1703 * Dataformat exporter
1704 *
1705 * @package core
1706 * @subpackage tablelib
1707 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1709 */
1710class table_dataformat_export_format extends table_default_export_format_parent {
1711
1712 /** @var $dataformat */
1713 protected $dataformat;
1714
1715 /** @var $rownum */
1716 protected $rownum = 0;
1717
1718 /** @var $columns */
1719 protected $columns;
1720
1721 /**
1722 * Constructor
1723 *
1724 * @param string $table An sql table
1725 * @param string $dataformat type of dataformat for export
1726 */
1727 public function __construct(&$table, $dataformat) {
1728 parent::__construct($table);
1729
9df4ae41
DM
1730 if (ob_get_length()) {
1731 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
bdb80f6a
BH
1732 }
1733
1734 $classname = 'dataformat_' . $dataformat . '\writer';
1735 if (!class_exists($classname)) {
1736 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1737 }
1738 $this->dataformat = new $classname;
1739
1740 // The dataformat export time to first byte could take a while to generate...
1741 set_time_limit(0);
1742
1743 // Close the session so that the users other tabs in the same session are not blocked.
1744 \core\session\manager::write_close();
1745 }
1746
1747 /**
1748 * Start document
1749 *
1750 * @param string $filename
faf45f9c 1751 * @param string $sheettitle
bdb80f6a 1752 */
faf45f9c 1753 public function start_document($filename, $sheettitle) {
bdb80f6a
BH
1754 $this->documentstarted = true;
1755 $this->dataformat->set_filename($filename);
faf45f9c
MN
1756 $this->dataformat->send_http_headers();
1757 $this->dataformat->set_sheettitle($sheettitle);
1758 $this->dataformat->start_output();
bdb80f6a
BH
1759 }
1760
1761 /**
1762 * Start export
1763 *
1764 * @param string $sheettitle optional spreadsheet worksheet title
1765 */
1766 public function start_table($sheettitle) {
1767 $this->dataformat->set_sheettitle($sheettitle);
1768 }
1769
1770 /**
1771 * Output headers
1772 *
1773 * @param array $headers
1774 */
1775 public function output_headers($headers) {
1776 $this->columns = $headers;
faf45f9c 1777 if (method_exists($this->dataformat, 'write_header')) {
e0ee37e4 1778 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
faf45f9c
MN
1779 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1780 $this->dataformat->write_header($headers);
1781 } else {
1782 $this->dataformat->start_sheet($headers);
1783 }
bdb80f6a
BH
1784 }
1785
1786 /**
1787 * Add a row of data
1788 *
1789 * @param array $row One record of data
1790 */
1791 public function add_data($row) {
1792 $this->dataformat->write_record($row, $this->rownum++);
1793 return true;
1794 }
1795
1796 /**
1797 * Finish export
1798 */
1799 public function finish_table() {
faf45f9c 1800 if (method_exists($this->dataformat, 'write_footer')) {
e0ee37e4 1801 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
faf45f9c
MN
1802 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1803 $this->dataformat->write_footer($this->columns);
1804 } else {
1805 $this->dataformat->close_sheet($this->columns);
1806 }
bdb80f6a
BH
1807 }
1808
1809 /**
1810 * Finish download
1811 */
1812 public function finish_document() {
faf45f9c
MN
1813 $this->dataformat->close_output();
1814 exit();
bdb80f6a 1815 }
bdb80f6a 1816}
9683db71 1817