Merge branch 'MDL-76985-MOODLE_400_STABLE' of https://github.com/sh-csg/moodle into...
[moodle.git] / lib / tablelib.php
blob2488defbc0801f45d62b0db3d01ec463a23c669a
1 <?php
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.
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/>.
18 /**
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
26 defined('MOODLE_INTERNAL') || die();
28 /**#@+
29 * These constants relate to the table's handling of URL parameters.
31 define('TABLE_VAR_SORT', 1);
32 define('TABLE_VAR_HIDE', 2);
33 define('TABLE_VAR_SHOW', 3);
34 define('TABLE_VAR_IFIRST', 4);
35 define('TABLE_VAR_ILAST', 5);
36 define('TABLE_VAR_PAGE', 6);
37 define('TABLE_VAR_RESET', 7);
38 define('TABLE_VAR_DIR', 8);
39 /**#@-*/
41 /**#@+
42 * Constants that indicate whether the paging bar for the table
43 * appears above or below the table.
45 define('TABLE_P_TOP', 1);
46 define('TABLE_P_BOTTOM', 2);
47 /**#@-*/
49 /**
50 * Constant that defines the 'Show all' page size.
52 define('TABLE_SHOW_ALL_PAGE_SIZE', 5000);
54 use core_table\local\filter\filterset;
56 /**
57 * @package moodlecore
58 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 class flexible_table {
63 var $uniqueid = NULL;
64 var $attributes = array();
65 var $headers = array();
67 /**
68 * @var string A column which should be considered as a header column.
70 protected $headercolumn = null;
72 /**
73 * @var string For create header with help icon.
75 private $helpforheaders = array();
76 var $columns = array();
77 var $column_style = array();
78 var $column_class = array();
79 var $column_suppress = array();
80 var $column_nosort = array('userpic');
81 private $column_textsort = array();
82 /** @var boolean Stores if setup has already been called on this flixible table. */
83 var $setup = false;
84 var $baseurl = NULL;
85 var $request = array();
87 /** @var string[] Columns that are expected to contain a users fullname. */
88 protected $userfullnamecolumns = ['fullname'];
90 /** @var array[] Attributes for each column */
91 private $columnsattributes = [];
93 /**
94 * @var bool Whether or not to store table properties in the user_preferences table.
96 private $persistent = false;
97 var $is_collapsible = false;
98 var $is_sortable = false;
101 * @var array The fields to sort.
103 protected $sortdata;
105 /** @var string The manually set first name initial preference */
106 protected $ifirst;
108 /** @var string The manually set last name initial preference */
109 protected $ilast;
111 var $use_pages = false;
112 var $use_initials = false;
114 var $maxsortkeys = 2;
115 var $pagesize = 30;
116 var $currpage = 0;
117 var $totalrows = 0;
118 var $currentrow = 0;
119 var $sort_default_column = NULL;
120 var $sort_default_order = SORT_ASC;
122 /** @var integer The defeult per page size for the table. */
123 private $defaultperpage = 30;
126 * Array of positions in which to display download controls.
128 var $showdownloadbuttonsat= array(TABLE_P_TOP);
131 * @var string Key of field returned by db query that is the id field of the
132 * user table or equivalent.
134 public $useridfield = 'id';
137 * @var string which download plugin to use. Default '' means none - print
138 * html table with paging. Property set by is_downloading which typically
139 * passes in cleaned data from $
141 var $download = '';
144 * @var bool whether data is downloadable from table. Determines whether
145 * to display download buttons. Set by method downloadable().
147 var $downloadable = false;
150 * @var bool Has start output been called yet?
152 var $started_output = false;
154 var $exportclass = null;
157 * @var array For storing user-customised table properties in the user_preferences db table.
159 private $prefs = array();
161 /** @var $sheettitle */
162 protected $sheettitle;
164 /** @var $filename */
165 protected $filename;
167 /** @var array $hiddencolumns List of hidden columns. */
168 protected $hiddencolumns;
170 /** @var $resetting bool Whether the table preferences is resetting. */
171 protected $resetting;
174 * @var filterset The currently applied filerset
175 * This is required for dynamic tables, but can be used by other tables too if desired.
177 protected $filterset = null;
180 * Constructor
181 * @param string $uniqueid all tables have to have a unique id, this is used
182 * as a key when storing table properties like sort order in the session.
184 function __construct($uniqueid) {
185 $this->uniqueid = $uniqueid;
186 $this->request = array(
187 TABLE_VAR_SORT => 'tsort',
188 TABLE_VAR_HIDE => 'thide',
189 TABLE_VAR_SHOW => 'tshow',
190 TABLE_VAR_IFIRST => 'tifirst',
191 TABLE_VAR_ILAST => 'tilast',
192 TABLE_VAR_PAGE => 'page',
193 TABLE_VAR_RESET => 'treset',
194 TABLE_VAR_DIR => 'tdir',
199 * Call this to pass the download type. Use :
200 * $download = optional_param('download', '', PARAM_ALPHA);
201 * To get the download type. We assume that if you call this function with
202 * params that this table's data is downloadable, so we call is_downloadable
203 * for you (even if the param is '', which means no download this time.
204 * Also you can call this method with no params to get the current set
205 * download type.
206 * @param string $download dataformat type. One of csv, xhtml, ods, etc
207 * @param string $filename filename for downloads without file extension.
208 * @param string $sheettitle title for downloaded data.
209 * @return string download dataformat type. One of csv, xhtml, ods, etc
211 function is_downloading($download = null, $filename='', $sheettitle='') {
212 if ($download!==null) {
213 $this->sheettitle = $sheettitle;
214 $this->is_downloadable(true);
215 $this->download = $download;
216 $this->filename = clean_filename($filename);
217 $this->export_class_instance();
219 return $this->download;
223 * Get, and optionally set, the export class.
224 * @param $exportclass (optional) if passed, set the table to use this export class.
225 * @return table_default_export_format_parent the export class in use (after any set).
227 function export_class_instance($exportclass = null) {
228 if (!is_null($exportclass)) {
229 $this->started_output = true;
230 $this->exportclass = $exportclass;
231 $this->exportclass->table = $this;
232 } else if (is_null($this->exportclass) && !empty($this->download)) {
233 $this->exportclass = new table_dataformat_export_format($this, $this->download);
234 if (!$this->exportclass->document_started()) {
235 $this->exportclass->start_document($this->filename, $this->sheettitle);
238 return $this->exportclass;
242 * Probably don't need to call this directly. Calling is_downloading with a
243 * param automatically sets table as downloadable.
245 * @param bool $downloadable optional param to set whether data from
246 * table is downloadable. If ommitted this function can be used to get
247 * current state of table.
248 * @return bool whether table data is set to be downloadable.
250 function is_downloadable($downloadable = null) {
251 if ($downloadable !== null) {
252 $this->downloadable = $downloadable;
254 return $this->downloadable;
258 * Call with boolean true to store table layout changes in the user_preferences table.
259 * Note: user_preferences.value has a maximum length of 1333 characters.
260 * Call with no parameter to get current state of table persistence.
262 * @param bool $persistent Optional parameter to set table layout persistence.
263 * @return bool Whether or not the table layout preferences will persist.
265 public function is_persistent($persistent = null) {
266 if ($persistent == true) {
267 $this->persistent = true;
269 return $this->persistent;
273 * Where to show download buttons.
274 * @param array $showat array of postions in which to show download buttons.
275 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
277 function show_download_buttons_at($showat) {
278 $this->showdownloadbuttonsat = $showat;
282 * Sets the is_sortable variable to the given boolean, sort_default_column to
283 * the given string, and the sort_default_order to the given integer.
284 * @param bool $bool
285 * @param string $defaultcolumn
286 * @param int $defaultorder
287 * @return void
289 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
290 $this->is_sortable = $bool;
291 $this->sort_default_column = $defaultcolumn;
292 $this->sort_default_order = $defaultorder;
296 * Use text sorting functions for this column (required for text columns with Oracle).
297 * Be warned that you cannot use this with column aliases. You can only do this
298 * with real columns. See MDL-40481 for an example.
299 * @param string column name
301 function text_sorting($column) {
302 $this->column_textsort[] = $column;
306 * Do not sort using this column
307 * @param string column name
309 function no_sorting($column) {
310 $this->column_nosort[] = $column;
314 * Is the column sortable?
315 * @param string column name, null means table
316 * @return bool
318 function is_sortable($column = null) {
319 if (empty($column)) {
320 return $this->is_sortable;
322 if (!$this->is_sortable) {
323 return false;
325 return !in_array($column, $this->column_nosort);
329 * Sets the is_collapsible variable to the given boolean.
330 * @param bool $bool
331 * @return void
333 function collapsible($bool) {
334 $this->is_collapsible = $bool;
338 * Sets the use_pages variable to the given boolean.
339 * @param bool $bool
340 * @return void
342 function pageable($bool) {
343 $this->use_pages = $bool;
347 * Sets the use_initials variable to the given boolean.
348 * @param bool $bool
349 * @return void
351 function initialbars($bool) {
352 $this->use_initials = $bool;
356 * Sets the pagesize variable to the given integer, the totalrows variable
357 * to the given integer, and the use_pages variable to true.
358 * @param int $perpage
359 * @param int $total
360 * @return void
362 function pagesize($perpage, $total) {
363 $this->pagesize = $perpage;
364 $this->totalrows = $total;
365 $this->use_pages = true;
369 * Assigns each given variable in the array to the corresponding index
370 * in the request class variable.
371 * @param array $variables
372 * @return void
374 function set_control_variables($variables) {
375 foreach ($variables as $what => $variable) {
376 if (isset($this->request[$what])) {
377 $this->request[$what] = $variable;
383 * Gives the given $value to the $attribute index of $this->attributes.
384 * @param string $attribute
385 * @param mixed $value
386 * @return void
388 function set_attribute($attribute, $value) {
389 $this->attributes[$attribute] = $value;
393 * What this method does is set the column so that if the same data appears in
394 * consecutive rows, then it is not repeated.
396 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
397 * that when one student has made multiple attempts, their name is only printed in the row
398 * for their first attempt.
399 * @param int $column the index of a column.
401 function column_suppress($column) {
402 if (isset($this->column_suppress[$column])) {
403 $this->column_suppress[$column] = true;
408 * Sets the given $column index to the given $classname in $this->column_class.
409 * @param int $column
410 * @param string $classname
411 * @return void
413 function column_class($column, $classname) {
414 if (isset($this->column_class[$column])) {
415 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
420 * Sets the given $column index and $property index to the given $value in $this->column_style.
421 * @param int $column
422 * @param string $property
423 * @param mixed $value
424 * @return void
426 function column_style($column, $property, $value) {
427 if (isset($this->column_style[$column])) {
428 $this->column_style[$column][$property] = $value;
433 * Sets the given $attributes to $this->columnsattributes.
434 * Column attributes will be added to every cell in the column.
436 * @param array[] $attributes e.g. ['c0_firstname' => ['data-foo' => 'bar']]
438 public function set_columnsattributes(array $attributes): void {
439 $this->columnsattributes = $attributes;
443 * Sets all columns' $propertys to the given $value in $this->column_style.
444 * @param int $property
445 * @param string $value
446 * @return void
448 function column_style_all($property, $value) {
449 foreach (array_keys($this->columns) as $column) {
450 $this->column_style[$column][$property] = $value;
455 * Sets $this->baseurl.
456 * @param moodle_url|string $url the url with params needed to call up this page
458 function define_baseurl($url) {
459 $this->baseurl = new moodle_url($url);
463 * @param array $columns an array of identifying names for columns. If
464 * columns are sorted then column names must correspond to a field in sql.
466 function define_columns($columns) {
467 $this->columns = array();
468 $this->column_style = array();
469 $this->column_class = array();
470 $this->columnsattributes = [];
471 $colnum = 0;
473 foreach ($columns as $column) {
474 $this->columns[$column] = $colnum++;
475 $this->column_style[$column] = array();
476 $this->column_class[$column] = '';
477 $this->columnsattributes[$column] = [];
478 $this->column_suppress[$column] = false;
483 * @param array $headers numerical keyed array of displayed string titles
484 * for each column.
486 function define_headers($headers) {
487 $this->headers = $headers;
491 * Mark a specific column as being a table header using the column name defined in define_columns.
493 * Note: Only one column can be a header, and it will be rendered using a th tag.
495 * @param string $column
497 public function define_header_column(string $column) {
498 $this->headercolumn = $column;
502 * Defines a help icon for the header
504 * Always use this function if you need to create header with sorting and help icon.
506 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
508 public function define_help_for_headers($helpicons) {
509 $this->helpforheaders = $helpicons;
513 * Mark the table preferences to be reset.
515 public function mark_table_to_reset(): void {
516 $this->resetting = true;
520 * Is the table marked for reset preferences?
522 * @return bool True if the table is marked to reset, false otherwise.
524 protected function is_resetting_preferences(): bool {
525 if ($this->resetting === null) {
526 $this->resetting = optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL);
529 return $this->resetting;
533 * Must be called after table is defined. Use methods above first. Cannot
534 * use functions below till after calling this method.
535 * @return type?
537 function setup() {
539 if (empty($this->columns) || empty($this->uniqueid)) {
540 return false;
543 $this->initialise_table_preferences();
545 if (empty($this->baseurl)) {
546 debugging('You should set baseurl when using flexible_table.');
547 global $PAGE;
548 $this->baseurl = $PAGE->url;
551 if ($this->currpage == null) {
552 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
555 $this->setup = true;
557 // Always introduce the "flexible" class for the table if not specified
558 if (empty($this->attributes)) {
559 $this->attributes['class'] = 'flexible table table-striped table-hover';
560 } else if (!isset($this->attributes['class'])) {
561 $this->attributes['class'] = 'flexible table table-striped table-hover';
562 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
563 $this->attributes['class'] = trim('flexible table table-striped table-hover ' . $this->attributes['class']);
568 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
569 * @param string $uniqueid the identifier for a table.
570 * @return SQL fragment that can be used in an ORDER BY clause.
572 public static function get_sort_for_table($uniqueid) {
573 global $SESSION;
574 if (isset($SESSION->flextable[$uniqueid])) {
575 $prefs = $SESSION->flextable[$uniqueid];
576 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
577 return '';
580 if (empty($prefs['sortby'])) {
581 return '';
583 if (empty($prefs['textsort'])) {
584 $prefs['textsort'] = array();
587 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
591 * Prepare an an order by clause from the list of columns to be sorted.
592 * @param array $cols column name => SORT_ASC or SORT_DESC
593 * @return SQL fragment that can be used in an ORDER BY clause.
595 public static function construct_order_by($cols, $textsortcols=array()) {
596 global $DB;
597 $bits = array();
599 foreach ($cols as $column => $order) {
600 if (in_array($column, $textsortcols)) {
601 $column = $DB->sql_order_by_text($column);
603 if ($order == SORT_ASC) {
604 $bits[] = $column . ' ASC';
605 } else {
606 $bits[] = $column . ' DESC';
610 return implode(', ', $bits);
614 * @return SQL fragment that can be used in an ORDER BY clause.
616 public function get_sql_sort() {
617 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
621 * Whether the current table contains any fullname columns
623 * @return bool
625 private function contains_fullname_columns(): bool {
626 $fullnamecolumns = array_intersect_key($this->columns, array_flip($this->userfullnamecolumns));
628 return !empty($fullnamecolumns);
632 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
633 * @return array column name => SORT_... constant.
635 public function get_sort_columns() {
636 if (!$this->setup) {
637 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
640 if (empty($this->prefs['sortby'])) {
641 return array();
643 foreach ($this->prefs['sortby'] as $column => $notused) {
644 if (isset($this->columns[$column])) {
645 continue; // This column is OK.
647 if (in_array($column, \core_user\fields::get_name_fields()) && $this->contains_fullname_columns()) {
648 continue; // This column is OK.
650 // This column is not OK.
651 unset($this->prefs['sortby'][$column]);
654 return $this->prefs['sortby'];
658 * @return int the offset for LIMIT clause of SQL
660 function get_page_start() {
661 if (!$this->use_pages) {
662 return '';
664 return $this->currpage * $this->pagesize;
668 * @return int the pagesize for LIMIT clause of SQL
670 function get_page_size() {
671 if (!$this->use_pages) {
672 return '';
674 return $this->pagesize;
678 * @return string sql to add to where statement.
680 function get_sql_where() {
681 global $DB;
683 $conditions = array();
684 $params = array();
686 if ($this->contains_fullname_columns()) {
687 static $i = 0;
688 $i++;
690 if (!empty($this->prefs['i_first'])) {
691 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
692 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
694 if (!empty($this->prefs['i_last'])) {
695 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
696 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
700 return array(implode(" AND ", $conditions), $params);
704 * Add a row of data to the table. This function takes an array or object with
705 * column names as keys or property names.
707 * It ignores any elements with keys that are not defined as columns. It
708 * puts in empty strings into the row when there is no element in the passed
709 * array corresponding to a column in the table. It puts the row elements in
710 * the proper order (internally row table data is stored by in arrays with
711 * a numerical index corresponding to the column number).
713 * @param object|array $rowwithkeys array keys or object property names are column names,
714 * as defined in call to define_columns.
715 * @param string $classname CSS class name to add to this row's tr tag.
717 function add_data_keyed($rowwithkeys, $classname = '') {
718 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
722 * Add a number of rows to the table at once. And optionally finish output after they have been added.
724 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
725 * object or array is added to table. We expect properties for the row array as would be
726 * passed to add_data_keyed.
727 * @param bool $finish
729 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
730 foreach ($rowstoadd as $row) {
731 if (is_null($row)) {
732 $this->add_separator();
733 } else {
734 $this->add_data_keyed($this->format_row($row));
737 if ($finish) {
738 $this->finish_output(!$this->is_downloading());
743 * Add a seperator line to table.
745 function add_separator() {
746 if (!$this->setup) {
747 return false;
749 $this->add_data(NULL);
753 * This method actually directly echoes the row passed to it now or adds it
754 * to the download. If this is the first row and start_output has not
755 * already been called this method also calls start_output to open the table
756 * or send headers for the downloaded.
757 * Can be used as before. print_html now calls finish_html to close table.
759 * @param array $row a numerically keyed row of data to add to the table.
760 * @param string $classname CSS class name to add to this row's tr tag.
761 * @return bool success.
763 function add_data($row, $classname = '') {
764 if (!$this->setup) {
765 return false;
767 if (!$this->started_output) {
768 $this->start_output();
770 if ($this->exportclass!==null) {
771 if ($row === null) {
772 $this->exportclass->add_seperator();
773 } else {
774 $this->exportclass->add_data($row);
776 } else {
777 $this->print_row($row, $classname);
779 return true;
783 * You should call this to finish outputting the table data after adding
784 * data to the table with add_data or add_data_keyed.
787 function finish_output($closeexportclassdoc = true) {
788 if ($this->exportclass!==null) {
789 $this->exportclass->finish_table();
790 if ($closeexportclassdoc) {
791 $this->exportclass->finish_document();
793 } else {
794 $this->finish_html();
799 * Hook that can be overridden in child classes to wrap a table in a form
800 * for example. Called only when there is data to display and not
801 * downloading.
803 function wrap_html_start() {
807 * Hook that can be overridden in child classes to wrap a table in a form
808 * for example. Called only when there is data to display and not
809 * downloading.
811 function wrap_html_finish() {
815 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
816 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
817 * displaying table as html, adding a div wrap, etc.
819 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
821 * @param array|object $row row of data from db used to make one row of the table.
822 * @return array one row for the table, added using add_data_keyed method.
824 function format_row($row) {
825 if (is_array($row)) {
826 $row = (object)$row;
828 $formattedrow = array();
829 foreach (array_keys($this->columns) as $column) {
830 $colmethodname = 'col_'.$column;
831 if (method_exists($this, $colmethodname)) {
832 $formattedcolumn = $this->$colmethodname($row);
833 } else {
834 $formattedcolumn = $this->other_cols($column, $row);
835 if ($formattedcolumn===NULL) {
836 $formattedcolumn = $row->$column;
839 $formattedrow[$column] = $formattedcolumn;
841 return $formattedrow;
845 * Fullname is treated as a special columname in tablelib and should always
846 * be treated the same as the fullname of a user.
847 * @uses $this->useridfield if the userid field is not expected to be id
848 * then you need to override $this->useridfield to point at the correct
849 * field for the user id.
851 * @param object $row the data from the db containing all fields from the
852 * users table necessary to construct the full name of the user in
853 * current language.
854 * @return string contents of cell in column 'fullname', for this row.
856 function col_fullname($row) {
857 global $COURSE;
859 $name = fullname($row, has_capability('moodle/site:viewfullnames', $this->get_context()));
860 if ($this->download) {
861 return $name;
864 $userid = $row->{$this->useridfield};
865 if ($COURSE->id == SITEID) {
866 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
867 } else {
868 $profileurl = new moodle_url('/user/view.php',
869 array('id' => $userid, 'course' => $COURSE->id));
871 return html_writer::link($profileurl, $name);
875 * You can override this method in a child class. See the description of
876 * build_table which calls this method.
878 function other_cols($column, $row) {
879 if (isset($row->$column) && ($column === 'email' || $column === 'idnumber') &&
880 (!$this->is_downloading() || $this->export_class_instance()->supports_html())) {
881 // Columns email and idnumber may potentially contain malicious characters, escape them by default.
882 // This function will not be executed if the child class implements col_email() or col_idnumber().
883 return s($row->$column);
885 return NULL;
889 * Used from col_* functions when text is to be displayed. Does the
890 * right thing - either converts text to html or strips any html tags
891 * depending on if we are downloading and what is the download type. Params
892 * are the same as format_text function in weblib.php but some default
893 * options are changed.
895 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
896 if (!$this->is_downloading()) {
897 if (is_null($options)) {
898 $options = new stdClass;
900 //some sensible defaults
901 if (!isset($options->para)) {
902 $options->para = false;
904 if (!isset($options->newlines)) {
905 $options->newlines = false;
907 if (!isset($options->smiley)) {
908 $options->smiley = false;
910 if (!isset($options->filter)) {
911 $options->filter = false;
913 return format_text($text, $format, $options);
914 } else {
915 $eci = $this->export_class_instance();
916 return $eci->format_text($text, $format, $options, $courseid);
920 * This method is deprecated although the old api is still supported.
921 * @deprecated 1.9.2 - Jun 2, 2008
923 function print_html() {
924 if (!$this->setup) {
925 return false;
927 $this->finish_html();
931 * This function is not part of the public api.
932 * @return string initial of first name we are currently filtering by
934 function get_initial_first() {
935 if (!$this->use_initials) {
936 return NULL;
939 return $this->prefs['i_first'];
943 * This function is not part of the public api.
944 * @return string initial of last name we are currently filtering by
946 function get_initial_last() {
947 if (!$this->use_initials) {
948 return NULL;
951 return $this->prefs['i_last'];
955 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
956 * @param array $alpha of letters in the alphabet.
957 * @param string $current the currently selected letter.
958 * @param string $class class name to add to this initial bar.
959 * @param string $title the name to put in front of this initial bar.
960 * @param string $urlvar URL parameter name for this initial.
962 * @deprecated since Moodle 3.3
964 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
966 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
967 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
969 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
970 $title . ' : ';
971 if ($current) {
972 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
973 } else {
974 echo html_writer::tag('strong', get_string('all'));
977 foreach ($alpha as $letter) {
978 if ($letter === $current) {
979 echo html_writer::tag('strong', $letter);
980 } else {
981 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
985 echo html_writer::end_tag('div');
989 * This function is not part of the public api.
991 function print_initials_bar() {
992 global $OUTPUT;
994 $ifirst = $this->get_initial_first();
995 $ilast = $this->get_initial_last();
996 if (is_null($ifirst)) {
997 $ifirst = '';
999 if (is_null($ilast)) {
1000 $ilast = '';
1003 if ((!empty($ifirst) || !empty($ilast) || $this->use_initials) && $this->contains_fullname_columns()) {
1004 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
1005 $prefixlast = $this->request[TABLE_VAR_ILAST];
1006 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
1007 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
1013 * This function is not part of the public api.
1015 function print_nothing_to_display() {
1016 global $OUTPUT;
1018 // Render the dynamic table header.
1019 echo $this->get_dynamic_table_html_start();
1021 // Render button to allow user to reset table preferences.
1022 echo $this->render_reset_button();
1024 $this->print_initials_bar();
1026 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1028 // Render the dynamic table footer.
1029 echo $this->get_dynamic_table_html_end();
1033 * This function is not part of the public api.
1035 function get_row_from_keyed($rowwithkeys) {
1036 if (is_object($rowwithkeys)) {
1037 $rowwithkeys = (array)$rowwithkeys;
1039 $row = array();
1040 foreach (array_keys($this->columns) as $column) {
1041 if (isset($rowwithkeys[$column])) {
1042 $row [] = $rowwithkeys[$column];
1043 } else {
1044 $row[] ='';
1047 return $row;
1051 * Get the html for the download buttons
1053 * Usually only use internally
1055 public function download_buttons() {
1056 global $OUTPUT;
1058 if ($this->is_downloadable() && !$this->is_downloading()) {
1059 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1060 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1061 } else {
1062 return '';
1067 * This function is not part of the public api.
1068 * You don't normally need to call this. It is called automatically when
1069 * needed when you start adding data to the table.
1072 function start_output() {
1073 $this->started_output = true;
1074 if ($this->exportclass!==null) {
1075 $this->exportclass->start_table($this->sheettitle);
1076 $this->exportclass->output_headers($this->headers);
1077 } else {
1078 $this->start_html();
1079 $this->print_headers();
1080 echo html_writer::start_tag('tbody');
1085 * This function is not part of the public api.
1087 function print_row($row, $classname = '') {
1088 echo $this->get_row_html($row, $classname);
1092 * Generate html code for the passed row.
1094 * @param array $row Row data.
1095 * @param string $classname classes to add.
1097 * @return string $html html code for the row passed.
1099 public function get_row_html($row, $classname = '') {
1100 static $suppress_lastrow = NULL;
1101 $rowclasses = array();
1103 if ($classname) {
1104 $rowclasses[] = $classname;
1107 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1108 $html = '';
1110 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1112 // If we have a separator, print it
1113 if ($row === NULL) {
1114 $colcount = count($this->columns);
1115 $html .= html_writer::tag('td', html_writer::tag('div', '',
1116 array('class' => 'tabledivider')), array('colspan' => $colcount));
1118 } else {
1119 $html .= $this->get_row_cells_html($rowid, $row, $suppress_lastrow);
1122 $html .= html_writer::end_tag('tr');
1124 $suppress_enabled = array_sum($this->column_suppress);
1125 if ($suppress_enabled) {
1126 $suppress_lastrow = $row;
1128 $this->currentrow++;
1129 return $html;
1133 * Generate html code for the row cells.
1135 * @param string $rowid
1136 * @param array $row
1137 * @param array|null $suppresslastrow
1138 * @return string
1140 public function get_row_cells_html(string $rowid, array $row, ?array $suppresslastrow): string {
1141 $html = '';
1142 $colbyindex = array_flip($this->columns);
1143 foreach ($row as $index => $data) {
1144 $column = $colbyindex[$index];
1146 $attributes = [
1147 'class' => "cell c{$index}" . $this->column_class[$column],
1148 'id' => "{$rowid}_c{$index}",
1149 'style' => $this->make_styles_string($this->column_style[$column]),
1152 $celltype = 'td';
1153 if ($this->headercolumn && $column == $this->headercolumn) {
1154 $celltype = 'th';
1155 $attributes['scope'] = 'row';
1158 $attributes += $this->columnsattributes[$column] ?? [];
1160 if (empty($this->prefs['collapse'][$column])) {
1161 if ($this->column_suppress[$column] && $suppresslastrow !== null && $suppresslastrow[$index] === $data) {
1162 $content = '&nbsp;';
1163 } else {
1164 $content = $data;
1166 } else {
1167 $content = '&nbsp;';
1170 $html .= html_writer::tag($celltype, $content, $attributes);
1172 return $html;
1176 * This function is not part of the public api.
1178 function finish_html() {
1179 global $OUTPUT, $PAGE;
1181 if (!$this->started_output) {
1182 //no data has been added to the table.
1183 $this->print_nothing_to_display();
1185 } else {
1186 // Print empty rows to fill the table to the current pagesize.
1187 // This is done so the header aria-controls attributes do not point to
1188 // non existant elements.
1189 $emptyrow = array_fill(0, count($this->columns), '');
1190 while ($this->currentrow < $this->pagesize) {
1191 $this->print_row($emptyrow, 'emptyrow');
1194 echo html_writer::end_tag('tbody');
1195 echo html_writer::end_tag('table');
1196 echo html_writer::end_tag('div');
1197 $this->wrap_html_finish();
1199 // Paging bar
1200 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1201 echo $this->download_buttons();
1204 if($this->use_pages) {
1205 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1206 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1207 echo $OUTPUT->render($pagingbar);
1210 // Render the dynamic table footer.
1211 echo $this->get_dynamic_table_html_end();
1216 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1217 * used by {@link print_headers()}.
1218 * @param string $column the column name, index into various names.
1219 * @param int $index numerical index of the column.
1220 * @return string HTML fragment.
1222 protected function show_hide_link($column, $index) {
1223 global $OUTPUT;
1224 // Some headers contain <br /> tags, do not include in title, hence the
1225 // strip tags.
1227 $ariacontrols = '';
1228 for ($i = 0; $i < $this->pagesize; $i++) {
1229 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1232 $ariacontrols = trim($ariacontrols);
1234 if (!empty($this->prefs['collapse'][$column])) {
1235 $linkattributes = [
1236 'title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1237 'aria-expanded' => 'false',
1238 'aria-controls' => $ariacontrols,
1239 'data-action' => 'show',
1240 'data-column' => $column,
1241 'role' => 'button',
1243 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1244 $OUTPUT->pix_icon('t/switch_plus', null), $linkattributes);
1246 } else if ($this->headers[$index] !== NULL) {
1247 $linkattributes = [
1248 'title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1249 'aria-expanded' => 'true',
1250 'aria-controls' => $ariacontrols,
1251 'data-action' => 'hide',
1252 'data-column' => $column,
1253 'role' => 'button',
1255 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1256 $OUTPUT->pix_icon('t/switch_minus', null), $linkattributes);
1261 * This function is not part of the public api.
1263 function print_headers() {
1264 global $CFG, $OUTPUT;
1266 // Set the primary sort column/order where possible, so that sort links/icons are correct.
1268 'sortby' => $primarysortcolumn,
1269 'sortorder' => $primarysortorder,
1270 ] = $this->get_primary_sort_order();
1272 echo html_writer::start_tag('thead');
1273 echo html_writer::start_tag('tr');
1274 foreach ($this->columns as $column => $index) {
1276 $icon_hide = '';
1277 if ($this->is_collapsible) {
1278 $icon_hide = $this->show_hide_link($column, $index);
1280 switch ($column) {
1282 case 'userpic':
1283 // do nothing, do not display sortable links
1284 break;
1286 default:
1288 if (array_search($column, $this->userfullnamecolumns) !== false) {
1289 // Check the full name display for sortable fields.
1290 if (has_capability('moodle/site:viewfullnames', $this->get_context())) {
1291 $nameformat = $CFG->alternativefullnameformat;
1292 } else {
1293 $nameformat = $CFG->fullnamedisplay;
1296 if ($nameformat == 'language') {
1297 $nameformat = get_string('fullnamedisplay');
1300 $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat);
1302 if (!empty($requirednames)) {
1303 if ($this->is_sortable($column)) {
1304 // Done this way for the possibility of more than two sortable full name display fields.
1305 $this->headers[$index] = '';
1306 foreach ($requirednames as $name) {
1307 $sortname = $this->sort_link(get_string($name),
1308 $name, $primarysortcolumn === $name, $primarysortorder);
1309 $this->headers[$index] .= $sortname . ' / ';
1311 $helpicon = '';
1312 if (isset($this->helpforheaders[$index])) {
1313 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1315 $this->headers[$index] = substr($this->headers[$index], 0, -3) . $helpicon;
1318 } else if ($this->is_sortable($column)) {
1319 $helpicon = '';
1320 if (isset($this->helpforheaders[$index])) {
1321 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1323 $this->headers[$index] = $this->sort_link($this->headers[$index],
1324 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1328 $attributes = array(
1329 'class' => 'header c' . $index . $this->column_class[$column],
1330 'scope' => 'col',
1332 if ($this->headers[$index] === NULL) {
1333 $content = '&nbsp;';
1334 } else if (!empty($this->prefs['collapse'][$column])) {
1335 $content = $icon_hide;
1336 } else {
1337 if (is_array($this->column_style[$column])) {
1338 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1340 $helpicon = '';
1341 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1342 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1344 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1345 $icon_hide, array('class' => 'commands'));
1347 echo html_writer::tag('th', $content, $attributes);
1350 echo html_writer::end_tag('tr');
1351 echo html_writer::end_tag('thead');
1355 * Calculate the preferences for sort order based on user-supplied values and get params.
1357 protected function set_sorting_preferences(): void {
1358 $sortdata = $this->sortdata;
1360 if ($sortdata === null) {
1361 $sortdata = $this->prefs['sortby'];
1363 $sortorder = optional_param($this->request[TABLE_VAR_DIR], $this->sort_default_order, PARAM_INT);
1364 $sortby = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT);
1366 if (array_key_exists($sortby, $sortdata)) {
1367 // This key already exists somewhere. Change its sortorder and bring it to the top.
1368 unset($sortdata[$sortby]);
1370 $sortdata = array_merge([$sortby => $sortorder], $sortdata);
1373 $usernamefields = \core_user\fields::get_name_fields();
1374 $sortdata = array_filter($sortdata, function($sortby) use ($usernamefields) {
1375 $isvalidsort = $sortby && $this->is_sortable($sortby);
1376 $isvalidsort = $isvalidsort && empty($this->prefs['collapse'][$sortby]);
1377 $isrealcolumn = isset($this->columns[$sortby]);
1378 $isfullnamefield = $this->contains_fullname_columns() && in_array($sortby, $usernamefields);
1380 return $isvalidsort && ($isrealcolumn || $isfullnamefield);
1381 }, ARRAY_FILTER_USE_KEY);
1383 // Finally, make sure that no more than $this->maxsortkeys are present into the array.
1384 $sortdata = array_slice($sortdata, 0, $this->maxsortkeys);
1386 // If a default order is defined and it is not in the current list of order by columns, add it at the end.
1387 // This prevents results from being returned in a random order if the only order by column contains equal values.
1388 if (!empty($this->sort_default_column) && !array_key_exists($this->sort_default_column, $sortdata)) {
1389 $sortdata = array_merge($sortdata, [$this->sort_default_column => $this->sort_default_order]);
1392 // Apply the sortdata to the preference.
1393 $this->prefs['sortby'] = $sortdata;
1397 * Fill in the preferences for the initials bar.
1399 protected function set_initials_preferences(): void {
1400 $ifirst = $this->ifirst;
1401 $ilast = $this->ilast;
1403 if ($ifirst === null) {
1404 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
1407 if ($ilast === null) {
1408 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
1411 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
1412 $this->prefs['i_first'] = $ifirst;
1415 if (!is_null($ilast) && ($ilast === '' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
1416 $this->prefs['i_last'] = $ilast;
1422 * Set hide and show preferences.
1424 protected function set_hide_show_preferences(): void {
1426 if ($this->hiddencolumns !== null) {
1427 $this->prefs['collapse'] = array_fill_keys(array_filter($this->hiddencolumns, function($column) {
1428 return array_key_exists($column, $this->columns);
1429 }), true);
1430 } else {
1431 if ($column = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) {
1432 if (isset($this->columns[$column])) {
1433 $this->prefs['collapse'][$column] = true;
1438 if ($column = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) {
1439 unset($this->prefs['collapse'][$column]);
1442 foreach (array_keys($this->prefs['collapse']) as $column) {
1443 if (array_key_exists($column, $this->prefs['sortby'])) {
1444 unset($this->prefs['sortby'][$column]);
1450 * Set the list of hidden columns.
1452 * @param array $columns The list of hidden columns.
1454 public function set_hidden_columns(array $columns): void {
1455 $this->hiddencolumns = $columns;
1459 * Initialise table preferences.
1461 protected function initialise_table_preferences(): void {
1462 global $SESSION;
1464 // Load any existing user preferences.
1465 if ($this->persistent) {
1466 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
1467 $oldprefs = $this->prefs;
1468 } else if (isset($SESSION->flextable[$this->uniqueid])) {
1469 $this->prefs = $SESSION->flextable[$this->uniqueid];
1470 $oldprefs = $this->prefs;
1473 // Set up default preferences if needed.
1474 if (!$this->prefs || $this->is_resetting_preferences()) {
1475 $this->prefs = [
1476 'collapse' => [],
1477 'sortby' => [],
1478 'i_first' => '',
1479 'i_last' => '',
1480 'textsort' => $this->column_textsort,
1484 if (!isset($oldprefs)) {
1485 $oldprefs = $this->prefs;
1488 // Save user preferences if they have changed.
1489 if ($this->is_resetting_preferences()) {
1490 $this->sortdata = null;
1491 $this->ifirst = null;
1492 $this->ilast = null;
1495 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
1496 isset($this->columns[$showcol])) {
1497 $this->prefs['collapse'][$showcol] = false;
1498 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
1499 isset($this->columns[$hidecol])) {
1500 $this->prefs['collapse'][$hidecol] = true;
1501 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
1502 unset($this->prefs['sortby'][$hidecol]);
1506 $this->set_hide_show_preferences();
1507 $this->set_sorting_preferences();
1508 $this->set_initials_preferences();
1510 // Now, reduce the width of collapsed columns and remove the width from columns that should be expanded.
1511 foreach (array_keys($this->columns) as $column) {
1512 if (!empty($this->prefs['collapse'][$column])) {
1513 $this->column_style[$column]['width'] = '10px';
1514 } else {
1515 unset($this->column_style[$column]['width']);
1519 if (empty($this->baseurl)) {
1520 debugging('You should set baseurl when using flexible_table.');
1521 global $PAGE;
1522 $this->baseurl = $PAGE->url;
1525 if ($this->currpage == null) {
1526 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
1529 $this->save_preferences($oldprefs);
1533 * Save preferences.
1535 * @param array $oldprefs Old preferences to compare against.
1537 protected function save_preferences($oldprefs): void {
1538 global $SESSION;
1540 if ($this->prefs != $oldprefs) {
1541 if ($this->persistent) {
1542 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
1543 } else {
1544 $SESSION->flextable[$this->uniqueid] = $this->prefs;
1547 unset($oldprefs);
1551 * Set the preferred table sorting attributes.
1553 * @param string $sortby The field to sort by.
1554 * @param int $sortorder The sort order.
1556 public function set_sortdata(array $sortdata): void {
1557 $this->sortdata = [];
1558 foreach ($sortdata as $sortitem) {
1559 if (!array_key_exists($sortitem['sortby'], $this->sortdata)) {
1560 $this->sortdata[$sortitem['sortby']] = (int) $sortitem['sortorder'];
1566 * Get the default per page.
1568 * @return int
1570 public function get_default_per_page(): int {
1571 return $this->defaultperpage;
1575 * Set the default per page.
1577 * @param int $defaultperpage
1579 public function set_default_per_page(int $defaultperpage): void {
1580 $this->defaultperpage = $defaultperpage;
1584 * Set the preferred first name initial in an initials bar.
1586 * @param string $initial The character to set
1588 public function set_first_initial(string $initial): void {
1589 $this->ifirst = $initial;
1593 * Set the preferred last name initial in an initials bar.
1595 * @param string $initial The character to set
1597 public function set_last_initial(string $initial): void {
1598 $this->ilast = $initial;
1602 * Set the page number.
1604 * @param int $pagenumber The page number.
1606 public function set_page_number(int $pagenumber): void {
1607 $this->currpage = $pagenumber - 1;
1611 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1612 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1613 * @param int $order SORT_ASC or SORT_DESC
1614 * @return string HTML fragment.
1616 protected function sort_icon($isprimary, $order) {
1617 global $OUTPUT;
1619 if (!$isprimary) {
1620 return '';
1623 if ($order == SORT_ASC) {
1624 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1625 } else {
1626 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1631 * Generate the correct tool tip for changing the sort order. This is a
1632 * helper method used by {@link sort_link()}.
1633 * @param bool $isprimary whether the is column is the current primary sort column.
1634 * @param int $order SORT_ASC or SORT_DESC
1635 * @return string the correct title.
1637 protected function sort_order_name($isprimary, $order) {
1638 if ($isprimary && $order != SORT_ASC) {
1639 return get_string('desc');
1640 } else {
1641 return get_string('asc');
1646 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1647 * @param string $text the text for the link.
1648 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1649 * @param bool $isprimary whether the is column is the current primary sort column.
1650 * @param int $order SORT_ASC or SORT_DESC
1651 * @return string HTML fragment.
1653 protected function sort_link($text, $column, $isprimary, $order) {
1654 // If we are already sorting by this column, switch direction.
1655 if (array_key_exists($column, $this->prefs['sortby'])) {
1656 $sortorder = $this->prefs['sortby'][$column] == SORT_ASC ? SORT_DESC : SORT_ASC;
1657 } else {
1658 $sortorder = $order;
1661 $params = [
1662 $this->request[TABLE_VAR_SORT] => $column,
1663 $this->request[TABLE_VAR_DIR] => $sortorder,
1666 return html_writer::link($this->baseurl->out(false, $params),
1667 $text . get_accesshide(get_string('sortby') . ' ' .
1668 $text . ' ' . $this->sort_order_name($isprimary, $order)),
1670 'data-sortable' => $this->is_sortable($column),
1671 'data-sortby' => $column,
1672 'data-sortorder' => $sortorder,
1673 'role' => 'button',
1674 ]) . ' ' . $this->sort_icon($isprimary, $order);
1678 * Return primary sorting column/order, either the first preferred "sortby" value or defaults defined for the table
1680 * @return array
1682 protected function get_primary_sort_order(): array {
1683 if (reset($this->prefs['sortby'])) {
1684 return $this->get_sort_order();
1687 return [
1688 'sortby' => $this->sort_default_column,
1689 'sortorder' => $this->sort_default_order,
1694 * Return sorting attributes values.
1696 * @return array
1698 protected function get_sort_order(): array {
1699 $sortbys = $this->prefs['sortby'];
1700 $sortby = key($sortbys);
1702 return [
1703 'sortby' => $sortby,
1704 'sortorder' => $sortbys[$sortby],
1709 * Get dynamic class component.
1711 * @return string
1713 protected function get_component() {
1714 $tableclass = explode("\\", get_class($this));
1715 return reset($tableclass);
1719 * Get dynamic class handler.
1721 * @return string
1723 protected function get_handler() {
1724 $tableclass = explode("\\", get_class($this));
1725 return end($tableclass);
1729 * Get the dynamic table start wrapper.
1730 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1732 * @return string
1734 protected function get_dynamic_table_html_start(): string {
1735 if (is_a($this, \core_table\dynamic::class)) {
1736 $sortdata = array_map(function($sortby, $sortorder) {
1737 return [
1738 'sortby' => $sortby,
1739 'sortorder' => $sortorder,
1741 }, array_keys($this->prefs['sortby']), array_values($this->prefs['sortby']));;
1743 return html_writer::start_tag('div', [
1744 'class' => 'table-dynamic position-relative',
1745 'data-region' => 'core_table/dynamic',
1746 'data-table-handler' => $this->get_handler(),
1747 'data-table-component' => $this->get_component(),
1748 'data-table-uniqueid' => $this->uniqueid,
1749 'data-table-filters' => json_encode($this->get_filterset()),
1750 'data-table-sort-data' => json_encode($sortdata),
1751 'data-table-first-initial' => $this->prefs['i_first'],
1752 'data-table-last-initial' => $this->prefs['i_last'],
1753 'data-table-page-number' => $this->currpage + 1,
1754 'data-table-page-size' => $this->pagesize,
1755 'data-table-default-per-page' => $this->get_default_per_page(),
1756 'data-table-hidden-columns' => json_encode(array_keys($this->prefs['collapse'])),
1757 'data-table-total-rows' => $this->totalrows,
1761 return '';
1765 * Get the dynamic table end wrapper.
1766 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1768 * @return string
1770 protected function get_dynamic_table_html_end(): string {
1771 global $PAGE;
1773 if (is_a($this, \core_table\dynamic::class)) {
1774 $output = '';
1776 $perpageurl = new moodle_url($PAGE->url);
1778 // Generate "Show all/Show per page" link.
1779 if ($this->pagesize == TABLE_SHOW_ALL_PAGE_SIZE && $this->totalrows > $this->get_default_per_page()) {
1780 $perpagesize = $this->get_default_per_page();
1781 $perpagestring = get_string('showperpage', '', $this->get_default_per_page());
1782 } else if ($this->pagesize < $this->totalrows) {
1783 $perpagesize = TABLE_SHOW_ALL_PAGE_SIZE;
1784 $perpagestring = get_string('showall', '', $this->totalrows);
1786 if (isset($perpagesize) && isset($perpagestring)) {
1787 $perpageurl->param('perpage', $perpagesize);
1788 $output .= html_writer::link(
1789 $perpageurl,
1790 $perpagestring,
1792 'data-action' => 'showcount',
1793 'data-target-page-size' => $perpagesize,
1798 $PAGE->requires->js_call_amd('core_table/dynamic', 'init');
1799 $output .= html_writer::end_tag('div');
1800 return $output;
1803 return '';
1807 * This function is not part of the public api.
1809 function start_html() {
1810 global $OUTPUT;
1812 // Render the dynamic table header.
1813 echo $this->get_dynamic_table_html_start();
1815 // Render button to allow user to reset table preferences.
1816 echo $this->render_reset_button();
1818 // Do we need to print initial bars?
1819 $this->print_initials_bar();
1821 // Paging bar
1822 if ($this->use_pages) {
1823 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1824 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1825 echo $OUTPUT->render($pagingbar);
1828 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1829 echo $this->download_buttons();
1832 $this->wrap_html_start();
1833 // Start of main data table
1835 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1836 echo html_writer::start_tag('table', $this->attributes);
1841 * This function is not part of the public api.
1842 * @param array $styles CSS-property => value
1843 * @return string values suitably to go in a style="" attribute in HTML.
1845 function make_styles_string($styles) {
1846 if (empty($styles)) {
1847 return null;
1850 $string = '';
1851 foreach($styles as $property => $value) {
1852 $string .= $property . ':' . $value . ';';
1854 return $string;
1858 * Generate the HTML for the table preferences reset button.
1860 * @return string HTML fragment, empty string if no need to reset
1862 protected function render_reset_button() {
1864 if (!$this->can_be_reset()) {
1865 return '';
1868 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1870 $html = html_writer::start_div('resettable mdl-right');
1871 $html .= html_writer::link($url, get_string('resettable'), ['role' => 'button']);
1872 $html .= html_writer::end_div();
1874 return $html;
1878 * Are there some table preferences that can be reset?
1880 * If true, then the "reset table preferences" widget should be displayed.
1882 * @return bool
1884 protected function can_be_reset() {
1885 // Loop through preferences and make sure they are empty or set to the default value.
1886 foreach ($this->prefs as $prefname => $prefval) {
1887 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1888 // Check if the actual sorting differs from the default one.
1889 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1890 return true;
1893 } else if ($prefname === 'collapse' and !empty($prefval)) {
1894 // Check if there are some collapsed columns (all are expanded by default).
1895 foreach ($prefval as $columnname => $iscollapsed) {
1896 if ($iscollapsed) {
1897 return true;
1901 } else if (!empty($prefval)) {
1902 // For all other cases, we just check if some preference is set.
1903 return true;
1907 return false;
1911 * Get the context for the table.
1913 * Note: This function _must_ be overridden by dynamic tables to ensure that the context is correctly determined
1914 * from the filterset parameters.
1916 * @return context
1918 public function get_context(): context {
1919 global $PAGE;
1921 if (is_a($this, \core_table\dynamic::class)) {
1922 throw new coding_exception('The get_context function must be defined for a dynamic table');
1925 return $PAGE->context;
1929 * Set the filterset in the table class.
1931 * The use of filtersets is a requirement for dynamic tables, but can be used by other tables too if desired.
1933 * @param filterset $filterset The filterset object to get filters and table parameters from
1935 public function set_filterset(filterset $filterset): void {
1936 $this->filterset = $filterset;
1938 $this->guess_base_url();
1942 * Get the currently defined filterset.
1944 * @return filterset
1946 public function get_filterset(): ?filterset {
1947 return $this->filterset;
1951 * Attempt to guess the base URL.
1953 public function guess_base_url(): void {
1954 if (is_a($this, \core_table\dynamic::class)) {
1955 throw new coding_exception('The guess_base_url function must be defined for a dynamic table');
1962 * @package moodlecore
1963 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1964 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1966 class table_sql extends flexible_table {
1968 public $countsql = NULL;
1969 public $countparams = NULL;
1971 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1973 public $sql = NULL;
1975 * @var array|\Traversable Data fetched from the db.
1977 public $rawdata = NULL;
1980 * @var bool Overriding default for this.
1982 public $is_sortable = true;
1984 * @var bool Overriding default for this.
1986 public $is_collapsible = true;
1989 * @param string $uniqueid a string identifying this table.Used as a key in
1990 * session vars.
1992 function __construct($uniqueid) {
1993 parent::__construct($uniqueid);
1994 // some sensible defaults
1995 $this->set_attribute('class', 'generaltable generalbox');
1999 * Take the data returned from the db_query and go through all the rows
2000 * processing each col using either col_{columnname} method or other_cols
2001 * method or if other_cols returns NULL then put the data straight into the
2002 * table.
2004 * After calling this function, don't forget to call close_recordset.
2006 public function build_table() {
2008 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
2009 return;
2011 if (!$this->rawdata) {
2012 return;
2015 foreach ($this->rawdata as $row) {
2016 $formattedrow = $this->format_row($row);
2017 $this->add_data_keyed($formattedrow,
2018 $this->get_row_class($row));
2023 * Closes recordset (for use after building the table).
2025 public function close_recordset() {
2026 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
2027 $this->rawdata instanceof moodle_recordset)) {
2028 $this->rawdata->close();
2029 $this->rawdata = null;
2034 * Get any extra classes names to add to this row in the HTML.
2035 * @param $row array the data for this row.
2036 * @return string added to the class="" attribute of the tr.
2038 function get_row_class($row) {
2039 return '';
2043 * This is only needed if you want to use different sql to count rows.
2044 * Used for example when perhaps all db JOINS are not needed when counting
2045 * records. You don't need to call this function the count_sql
2046 * will be generated automatically.
2048 * We need to count rows returned by the db seperately to the query itself
2049 * as we need to know how many pages of data we have to display.
2051 function set_count_sql($sql, array $params = NULL) {
2052 $this->countsql = $sql;
2053 $this->countparams = $params;
2057 * Set the sql to query the db. Query will be :
2058 * SELECT $fields FROM $from WHERE $where
2059 * Of course you can use sub-queries, JOINS etc. by putting them in the
2060 * appropriate clause of the query.
2062 function set_sql($fields, $from, $where, array $params = array()) {
2063 $this->sql = new stdClass();
2064 $this->sql->fields = $fields;
2065 $this->sql->from = $from;
2066 $this->sql->where = $where;
2067 $this->sql->params = $params;
2071 * Query the db. Store results in the table object for use by build_table.
2073 * @param int $pagesize size of page for paginated displayed table.
2074 * @param bool $useinitialsbar do you want to use the initials bar. Bar
2075 * will only be used if there is a fullname column defined for the table.
2077 function query_db($pagesize, $useinitialsbar=true) {
2078 global $DB;
2079 if (!$this->is_downloading()) {
2080 if ($this->countsql === NULL) {
2081 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
2082 $this->countparams = $this->sql->params;
2084 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
2085 if ($useinitialsbar && !$this->is_downloading()) {
2086 $this->initialbars(true);
2089 list($wsql, $wparams) = $this->get_sql_where();
2090 if ($wsql) {
2091 $this->countsql .= ' AND '.$wsql;
2092 $this->countparams = array_merge($this->countparams, $wparams);
2094 $this->sql->where .= ' AND '.$wsql;
2095 $this->sql->params = array_merge($this->sql->params, $wparams);
2097 $total = $DB->count_records_sql($this->countsql, $this->countparams);
2098 } else {
2099 $total = $grandtotal;
2102 $this->pagesize($pagesize, $total);
2105 // Fetch the attempts
2106 $sort = $this->get_sql_sort();
2107 if ($sort) {
2108 $sort = "ORDER BY $sort";
2110 $sql = "SELECT
2111 {$this->sql->fields}
2112 FROM {$this->sql->from}
2113 WHERE {$this->sql->where}
2114 {$sort}";
2116 if (!$this->is_downloading()) {
2117 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
2118 } else {
2119 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
2124 * Convenience method to call a number of methods for you to display the
2125 * table.
2127 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
2128 global $DB;
2129 if (!$this->columns) {
2130 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
2131 $this->sql->params, IGNORE_MULTIPLE);
2132 //if columns is not set then define columns as the keys of the rows returned
2133 //from the db.
2134 $this->define_columns(array_keys((array)$onerow));
2135 $this->define_headers(array_keys((array)$onerow));
2137 $this->pagesize = $pagesize;
2138 $this->setup();
2139 $this->query_db($pagesize, $useinitialsbar);
2140 $this->build_table();
2141 $this->close_recordset();
2142 $this->finish_output();
2148 * @package moodlecore
2149 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2150 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2152 class table_default_export_format_parent {
2154 * @var flexible_table or child class reference pointing to table class
2155 * object from which to export data.
2157 var $table;
2160 * @var bool output started. Keeps track of whether any output has been
2161 * started yet.
2163 var $documentstarted = false;
2166 * Constructor
2168 * @param flexible_table $table
2170 public function __construct(&$table) {
2171 $this->table =& $table;
2175 * Old syntax of class constructor. Deprecated in PHP7.
2177 * @deprecated since Moodle 3.1
2179 public function table_default_export_format_parent(&$table) {
2180 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2181 self::__construct($table);
2184 function set_table(&$table) {
2185 $this->table =& $table;
2188 function add_data($row) {
2189 return false;
2192 function add_seperator() {
2193 return false;
2196 function document_started() {
2197 return $this->documentstarted;
2200 * Given text in a variety of format codings, this function returns
2201 * the text as safe HTML or as plain text dependent on what is appropriate
2202 * for the download format. The default removes all tags.
2204 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
2205 //use some whitespace to indicate where there was some line spacing.
2206 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
2207 return html_entity_decode(strip_tags($text));
2211 * Format a row of data, removing HTML tags and entities from each of the cells
2213 * @param array $row
2214 * @return array
2216 public function format_data(array $row): array {
2217 return array_map([$this, 'format_text'], $row);
2222 * Dataformat exporter
2224 * @package core
2225 * @subpackage tablelib
2226 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
2227 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2229 class table_dataformat_export_format extends table_default_export_format_parent {
2231 /** @var \core\dataformat\base $dataformat */
2232 protected $dataformat;
2234 /** @var $rownum */
2235 protected $rownum = 0;
2237 /** @var $columns */
2238 protected $columns;
2241 * Constructor
2243 * @param string $table An sql table
2244 * @param string $dataformat type of dataformat for export
2246 public function __construct(&$table, $dataformat) {
2247 parent::__construct($table);
2249 if (ob_get_length()) {
2250 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
2253 $classname = 'dataformat_' . $dataformat . '\writer';
2254 if (!class_exists($classname)) {
2255 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
2257 $this->dataformat = new $classname;
2259 // The dataformat export time to first byte could take a while to generate...
2260 set_time_limit(0);
2262 // Close the session so that the users other tabs in the same session are not blocked.
2263 \core\session\manager::write_close();
2267 * Whether the current dataformat supports export of HTML
2269 * @return bool
2271 public function supports_html(): bool {
2272 return $this->dataformat->supports_html();
2276 * Start document
2278 * @param string $filename
2279 * @param string $sheettitle
2281 public function start_document($filename, $sheettitle) {
2282 $this->documentstarted = true;
2283 $this->dataformat->set_filename($filename);
2284 $this->dataformat->send_http_headers();
2285 $this->dataformat->set_sheettitle($sheettitle);
2286 $this->dataformat->start_output();
2290 * Start export
2292 * @param string $sheettitle optional spreadsheet worksheet title
2294 public function start_table($sheettitle) {
2295 $this->dataformat->set_sheettitle($sheettitle);
2299 * Output headers
2301 * @param array $headers
2303 public function output_headers($headers) {
2304 $this->columns = $this->format_data($headers);
2305 if (method_exists($this->dataformat, 'write_header')) {
2306 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
2307 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
2308 $this->dataformat->write_header($this->columns);
2309 } else {
2310 $this->dataformat->start_sheet($this->columns);
2315 * Add a row of data
2317 * @param array $row One record of data
2319 public function add_data($row) {
2320 if (!$this->supports_html()) {
2321 $row = $this->format_data($row);
2324 $this->dataformat->write_record($row, $this->rownum++);
2325 return true;
2329 * Finish export
2331 public function finish_table() {
2332 if (method_exists($this->dataformat, 'write_footer')) {
2333 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
2334 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
2335 $this->dataformat->write_footer($this->columns);
2336 } else {
2337 $this->dataformat->close_sheet($this->columns);
2342 * Finish download
2344 public function finish_document() {
2345 $this->dataformat->close_output();
2346 exit();