3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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();
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);
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);
50 * Constant that defines the 'Show all' page size.
52 define('TABLE_SHOW_ALL_PAGE_SIZE', 5000);
54 use core_table\local\filter\filterset
;
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
{
64 var $attributes = array();
65 var $headers = array();
68 * @var string A column which should be considered as a header column.
70 protected $headercolumn = null;
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. */
85 var $request = array();
88 * @var bool Whether or not to store table properties in the user_preferences table.
90 private $persistent = false;
91 var $is_collapsible = false;
92 var $is_sortable = false;
95 * @var array The fields to sort.
99 /** @var string The manually set first name initial preference */
102 /** @var string The manually set last name initial preference */
105 var $use_pages = false;
106 var $use_initials = false;
108 var $maxsortkeys = 2;
113 var $sort_default_column = NULL;
114 var $sort_default_order = SORT_ASC
;
116 /** @var integer The defeult per page size for the table. */
117 private $defaultperpage = 30;
120 * Array of positions in which to display download controls.
122 var $showdownloadbuttonsat= array(TABLE_P_TOP
);
125 * @var string Key of field returned by db query that is the id field of the
126 * user table or equivalent.
128 public $useridfield = 'id';
131 * @var string which download plugin to use. Default '' means none - print
132 * html table with paging. Property set by is_downloading which typically
133 * passes in cleaned data from $
138 * @var bool whether data is downloadable from table. Determines whether
139 * to display download buttons. Set by method downloadable().
141 var $downloadable = false;
144 * @var bool Has start output been called yet?
146 var $started_output = false;
148 var $exportclass = null;
151 * @var array For storing user-customised table properties in the user_preferences db table.
153 private $prefs = array();
155 /** @var $sheettitle */
156 protected $sheettitle;
158 /** @var $filename */
161 /** @var array $hiddencolumns List of hidden columns. */
162 protected $hiddencolumns;
164 /** @var $resetting bool Whether the table preferences is resetting. */
165 protected $resetting;
168 * @var filterset The currently applied filerset
169 * This is required for dynamic tables, but can be used by other tables too if desired.
171 protected $filterset = null;
175 * @param string $uniqueid all tables have to have a unique id, this is used
176 * as a key when storing table properties like sort order in the session.
178 function __construct($uniqueid) {
179 $this->uniqueid
= $uniqueid;
180 $this->request
= array(
181 TABLE_VAR_SORT
=> 'tsort',
182 TABLE_VAR_HIDE
=> 'thide',
183 TABLE_VAR_SHOW
=> 'tshow',
184 TABLE_VAR_IFIRST
=> 'tifirst',
185 TABLE_VAR_ILAST
=> 'tilast',
186 TABLE_VAR_PAGE
=> 'page',
187 TABLE_VAR_RESET
=> 'treset',
188 TABLE_VAR_DIR
=> 'tdir',
193 * Call this to pass the download type. Use :
194 * $download = optional_param('download', '', PARAM_ALPHA);
195 * To get the download type. We assume that if you call this function with
196 * params that this table's data is downloadable, so we call is_downloadable
197 * for you (even if the param is '', which means no download this time.
198 * Also you can call this method with no params to get the current set
200 * @param string $download dataformat type. One of csv, xhtml, ods, etc
201 * @param string $filename filename for downloads without file extension.
202 * @param string $sheettitle title for downloaded data.
203 * @return string download dataformat type. One of csv, xhtml, ods, etc
205 function is_downloading($download = null, $filename='', $sheettitle='') {
206 if ($download!==null) {
207 $this->sheettitle
= $sheettitle;
208 $this->is_downloadable(true);
209 $this->download
= $download;
210 $this->filename
= clean_filename($filename);
211 $this->export_class_instance();
213 return $this->download
;
217 * Get, and optionally set, the export class.
218 * @param $exportclass (optional) if passed, set the table to use this export class.
219 * @return table_default_export_format_parent the export class in use (after any set).
221 function export_class_instance($exportclass = null) {
222 if (!is_null($exportclass)) {
223 $this->started_output
= true;
224 $this->exportclass
= $exportclass;
225 $this->exportclass
->table
= $this;
226 } else if (is_null($this->exportclass
) && !empty($this->download
)) {
227 $this->exportclass
= new table_dataformat_export_format($this, $this->download
);
228 if (!$this->exportclass
->document_started()) {
229 $this->exportclass
->start_document($this->filename
, $this->sheettitle
);
232 return $this->exportclass
;
236 * Probably don't need to call this directly. Calling is_downloading with a
237 * param automatically sets table as downloadable.
239 * @param bool $downloadable optional param to set whether data from
240 * table is downloadable. If ommitted this function can be used to get
241 * current state of table.
242 * @return bool whether table data is set to be downloadable.
244 function is_downloadable($downloadable = null) {
245 if ($downloadable !== null) {
246 $this->downloadable
= $downloadable;
248 return $this->downloadable
;
252 * Call with boolean true to store table layout changes in the user_preferences table.
253 * Note: user_preferences.value has a maximum length of 1333 characters.
254 * Call with no parameter to get current state of table persistence.
256 * @param bool $persistent Optional parameter to set table layout persistence.
257 * @return bool Whether or not the table layout preferences will persist.
259 public function is_persistent($persistent = null) {
260 if ($persistent == true) {
261 $this->persistent
= true;
263 return $this->persistent
;
267 * Where to show download buttons.
268 * @param array $showat array of postions in which to show download buttons.
269 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
271 function show_download_buttons_at($showat) {
272 $this->showdownloadbuttonsat
= $showat;
276 * Sets the is_sortable variable to the given boolean, sort_default_column to
277 * the given string, and the sort_default_order to the given integer.
279 * @param string $defaultcolumn
280 * @param int $defaultorder
283 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC
) {
284 $this->is_sortable
= $bool;
285 $this->sort_default_column
= $defaultcolumn;
286 $this->sort_default_order
= $defaultorder;
290 * Use text sorting functions for this column (required for text columns with Oracle).
291 * Be warned that you cannot use this with column aliases. You can only do this
292 * with real columns. See MDL-40481 for an example.
293 * @param string column name
295 function text_sorting($column) {
296 $this->column_textsort
[] = $column;
300 * Do not sort using this column
301 * @param string column name
303 function no_sorting($column) {
304 $this->column_nosort
[] = $column;
308 * Is the column sortable?
309 * @param string column name, null means table
312 function is_sortable($column = null) {
313 if (empty($column)) {
314 return $this->is_sortable
;
316 if (!$this->is_sortable
) {
319 return !in_array($column, $this->column_nosort
);
323 * Sets the is_collapsible variable to the given boolean.
327 function collapsible($bool) {
328 $this->is_collapsible
= $bool;
332 * Sets the use_pages variable to the given boolean.
336 function pageable($bool) {
337 $this->use_pages
= $bool;
341 * Sets the use_initials variable to the given boolean.
345 function initialbars($bool) {
346 $this->use_initials
= $bool;
350 * Sets the pagesize variable to the given integer, the totalrows variable
351 * to the given integer, and the use_pages variable to true.
352 * @param int $perpage
356 function pagesize($perpage, $total) {
357 $this->pagesize
= $perpage;
358 $this->totalrows
= $total;
359 $this->use_pages
= true;
363 * Assigns each given variable in the array to the corresponding index
364 * in the request class variable.
365 * @param array $variables
368 function set_control_variables($variables) {
369 foreach ($variables as $what => $variable) {
370 if (isset($this->request
[$what])) {
371 $this->request
[$what] = $variable;
377 * Gives the given $value to the $attribute index of $this->attributes.
378 * @param string $attribute
379 * @param mixed $value
382 function set_attribute($attribute, $value) {
383 $this->attributes
[$attribute] = $value;
387 * What this method does is set the column so that if the same data appears in
388 * consecutive rows, then it is not repeated.
390 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
391 * that when one student has made multiple attempts, their name is only printed in the row
392 * for their first attempt.
393 * @param int $column the index of a column.
395 function column_suppress($column) {
396 if (isset($this->column_suppress
[$column])) {
397 $this->column_suppress
[$column] = true;
402 * Sets the given $column index to the given $classname in $this->column_class.
404 * @param string $classname
407 function column_class($column, $classname) {
408 if (isset($this->column_class
[$column])) {
409 $this->column_class
[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
414 * Sets the given $column index and $property index to the given $value in $this->column_style.
416 * @param string $property
417 * @param mixed $value
420 function column_style($column, $property, $value) {
421 if (isset($this->column_style
[$column])) {
422 $this->column_style
[$column][$property] = $value;
427 * Sets all columns' $propertys to the given $value in $this->column_style.
428 * @param int $property
429 * @param string $value
432 function column_style_all($property, $value) {
433 foreach (array_keys($this->columns
) as $column) {
434 $this->column_style
[$column][$property] = $value;
439 * Sets $this->baseurl.
440 * @param moodle_url|string $url the url with params needed to call up this page
442 function define_baseurl($url) {
443 $this->baseurl
= new moodle_url($url);
447 * @param array $columns an array of identifying names for columns. If
448 * columns are sorted then column names must correspond to a field in sql.
450 function define_columns($columns) {
451 $this->columns
= array();
452 $this->column_style
= array();
453 $this->column_class
= array();
456 foreach ($columns as $column) {
457 $this->columns
[$column] = $colnum++
;
458 $this->column_style
[$column] = array();
459 $this->column_class
[$column] = '';
460 $this->column_suppress
[$column] = false;
465 * @param array $headers numerical keyed array of displayed string titles
468 function define_headers($headers) {
469 $this->headers
= $headers;
473 * Mark a specific column as being a table header using the column name defined in define_columns.
475 * Note: Only one column can be a header, and it will be rendered using a th tag.
477 * @param string $column
479 public function define_header_column(string $column) {
480 $this->headercolumn
= $column;
484 * Defines a help icon for the header
486 * Always use this function if you need to create header with sorting and help icon.
488 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
490 public function define_help_for_headers($helpicons) {
491 $this->helpforheaders
= $helpicons;
495 * Mark the table preferences to be reset.
497 public function mark_table_to_reset(): void
{
498 $this->resetting
= true;
502 * Is the table marked for reset preferences?
504 * @return bool True if the table is marked to reset, false otherwise.
506 protected function is_resetting_preferences(): bool {
507 if ($this->resetting
=== null) {
508 $this->resetting
= optional_param($this->request
[TABLE_VAR_RESET
], false, PARAM_BOOL
);
511 return $this->resetting
;
515 * Must be called after table is defined. Use methods above first. Cannot
516 * use functions below till after calling this method.
521 if (empty($this->columns
) ||
empty($this->uniqueid
)) {
525 $this->initialise_table_preferences();
527 if (empty($this->baseurl
)) {
528 debugging('You should set baseurl when using flexible_table.');
530 $this->baseurl
= $PAGE->url
;
533 if ($this->currpage
== null) {
534 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
539 // Always introduce the "flexible" class for the table if not specified
540 if (empty($this->attributes
)) {
541 $this->attributes
['class'] = 'flexible table table-striped table-hover';
542 } else if (!isset($this->attributes
['class'])) {
543 $this->attributes
['class'] = 'flexible table table-striped table-hover';
544 } else if (!in_array('flexible', explode(' ', $this->attributes
['class']))) {
545 $this->attributes
['class'] = trim('flexible table table-striped table-hover ' . $this->attributes
['class']);
550 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
551 * @param string $uniqueid the identifier for a table.
552 * @return SQL fragment that can be used in an ORDER BY clause.
554 public static function get_sort_for_table($uniqueid) {
556 if (isset($SESSION->flextable
[$uniqueid])) {
557 $prefs = $SESSION->flextable
[$uniqueid];
558 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
562 if (empty($prefs['sortby'])) {
565 if (empty($prefs['textsort'])) {
566 $prefs['textsort'] = array();
569 return self
::construct_order_by($prefs['sortby'], $prefs['textsort']);
573 * Prepare an an order by clause from the list of columns to be sorted.
574 * @param array $cols column name => SORT_ASC or SORT_DESC
575 * @return SQL fragment that can be used in an ORDER BY clause.
577 public static function construct_order_by($cols, $textsortcols=array()) {
581 foreach ($cols as $column => $order) {
582 if (in_array($column, $textsortcols)) {
583 $column = $DB->sql_order_by_text($column);
585 if ($order == SORT_ASC
) {
586 $bits[] = $column . ' ASC';
588 $bits[] = $column . ' DESC';
592 return implode(', ', $bits);
596 * @return SQL fragment that can be used in an ORDER BY clause.
598 public function get_sql_sort() {
599 return self
::construct_order_by($this->get_sort_columns(), $this->column_textsort
);
603 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
604 * @return array column name => SORT_... constant.
606 public function get_sort_columns() {
608 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
611 if (empty($this->prefs
['sortby'])) {
615 foreach ($this->prefs
['sortby'] as $column => $notused) {
616 if (isset($this->columns
[$column])) {
617 continue; // This column is OK.
619 if (in_array($column, \core_user\fields
::get_name_fields()) &&
620 isset($this->columns
['fullname'])) {
621 continue; // This column is OK.
623 // This column is not OK.
624 unset($this->prefs
['sortby'][$column]);
627 return $this->prefs
['sortby'];
631 * @return int the offset for LIMIT clause of SQL
633 function get_page_start() {
634 if (!$this->use_pages
) {
637 return $this->currpage
* $this->pagesize
;
641 * @return int the pagesize for LIMIT clause of SQL
643 function get_page_size() {
644 if (!$this->use_pages
) {
647 return $this->pagesize
;
651 * @return string sql to add to where statement.
653 function get_sql_where() {
656 $conditions = array();
659 if (isset($this->columns
['fullname'])) {
663 if (!empty($this->prefs
['i_first'])) {
664 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
665 $params['ifirstc'.$i] = $this->prefs
['i_first'].'%';
667 if (!empty($this->prefs
['i_last'])) {
668 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
669 $params['ilastc'.$i] = $this->prefs
['i_last'].'%';
673 return array(implode(" AND ", $conditions), $params);
677 * Add a row of data to the table. This function takes an array or object with
678 * column names as keys or property names.
680 * It ignores any elements with keys that are not defined as columns. It
681 * puts in empty strings into the row when there is no element in the passed
682 * array corresponding to a column in the table. It puts the row elements in
683 * the proper order (internally row table data is stored by in arrays with
684 * a numerical index corresponding to the column number).
686 * @param object|array $rowwithkeys array keys or object property names are column names,
687 * as defined in call to define_columns.
688 * @param string $classname CSS class name to add to this row's tr tag.
690 function add_data_keyed($rowwithkeys, $classname = '') {
691 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
695 * Add a number of rows to the table at once. And optionally finish output after they have been added.
697 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
698 * object or array is added to table. We expect properties for the row array as would be
699 * passed to add_data_keyed.
700 * @param bool $finish
702 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
703 foreach ($rowstoadd as $row) {
705 $this->add_separator();
707 $this->add_data_keyed($this->format_row($row));
711 $this->finish_output(!$this->is_downloading());
716 * Add a seperator line to table.
718 function add_separator() {
722 $this->add_data(NULL);
726 * This method actually directly echoes the row passed to it now or adds it
727 * to the download. If this is the first row and start_output has not
728 * already been called this method also calls start_output to open the table
729 * or send headers for the downloaded.
730 * Can be used as before. print_html now calls finish_html to close table.
732 * @param array $row a numerically keyed row of data to add to the table.
733 * @param string $classname CSS class name to add to this row's tr tag.
734 * @return bool success.
736 function add_data($row, $classname = '') {
740 if (!$this->started_output
) {
741 $this->start_output();
743 if ($this->exportclass
!==null) {
745 $this->exportclass
->add_seperator();
747 $this->exportclass
->add_data($row);
750 $this->print_row($row, $classname);
756 * You should call this to finish outputting the table data after adding
757 * data to the table with add_data or add_data_keyed.
760 function finish_output($closeexportclassdoc = true) {
761 if ($this->exportclass
!==null) {
762 $this->exportclass
->finish_table();
763 if ($closeexportclassdoc) {
764 $this->exportclass
->finish_document();
767 $this->finish_html();
772 * Hook that can be overridden in child classes to wrap a table in a form
773 * for example. Called only when there is data to display and not
776 function wrap_html_start() {
780 * Hook that can be overridden in child classes to wrap a table in a form
781 * for example. Called only when there is data to display and not
784 function wrap_html_finish() {
788 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
789 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
790 * displaying table as html, adding a div wrap, etc.
792 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
794 * @param array|object $row row of data from db used to make one row of the table.
795 * @return array one row for the table, added using add_data_keyed method.
797 function format_row($row) {
798 if (is_array($row)) {
801 $formattedrow = array();
802 foreach (array_keys($this->columns
) as $column) {
803 $colmethodname = 'col_'.$column;
804 if (method_exists($this, $colmethodname)) {
805 $formattedcolumn = $this->$colmethodname($row);
807 $formattedcolumn = $this->other_cols($column, $row);
808 if ($formattedcolumn===NULL) {
809 $formattedcolumn = $row->$column;
812 $formattedrow[$column] = $formattedcolumn;
814 return $formattedrow;
818 * Fullname is treated as a special columname in tablelib and should always
819 * be treated the same as the fullname of a user.
820 * @uses $this->useridfield if the userid field is not expected to be id
821 * then you need to override $this->useridfield to point at the correct
822 * field for the user id.
824 * @param object $row the data from the db containing all fields from the
825 * users table necessary to construct the full name of the user in
827 * @return string contents of cell in column 'fullname', for this row.
829 function col_fullname($row) {
832 $name = fullname($row, has_capability('moodle/site:viewfullnames', $this->get_context()));
833 if ($this->download
) {
837 $userid = $row->{$this->useridfield
};
838 if ($COURSE->id
== SITEID
) {
839 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
841 $profileurl = new moodle_url('/user/view.php',
842 array('id' => $userid, 'course' => $COURSE->id
));
844 return html_writer
::link($profileurl, $name);
848 * You can override this method in a child class. See the description of
849 * build_table which calls this method.
851 function other_cols($column, $row) {
852 if (isset($row->$column) && ($column === 'email' ||
$column === 'idnumber') &&
853 (!$this->is_downloading() ||
$this->export_class_instance()->supports_html())) {
854 // Columns email and idnumber may potentially contain malicious characters, escape them by default.
855 // This function will not be executed if the child class implements col_email() or col_idnumber().
856 return s($row->$column);
862 * Used from col_* functions when text is to be displayed. Does the
863 * right thing - either converts text to html or strips any html tags
864 * depending on if we are downloading and what is the download type. Params
865 * are the same as format_text function in weblib.php but some default
866 * options are changed.
868 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
869 if (!$this->is_downloading()) {
870 if (is_null($options)) {
871 $options = new stdClass
;
873 //some sensible defaults
874 if (!isset($options->para
)) {
875 $options->para
= false;
877 if (!isset($options->newlines
)) {
878 $options->newlines
= false;
880 if (!isset($options->smiley
)) {
881 $options->smiley
= false;
883 if (!isset($options->filter
)) {
884 $options->filter
= false;
886 return format_text($text, $format, $options);
888 $eci = $this->export_class_instance();
889 return $eci->format_text($text, $format, $options, $courseid);
893 * This method is deprecated although the old api is still supported.
894 * @deprecated 1.9.2 - Jun 2, 2008
896 function print_html() {
900 $this->finish_html();
904 * This function is not part of the public api.
905 * @return string initial of first name we are currently filtering by
907 function get_initial_first() {
908 if (!$this->use_initials
) {
912 return $this->prefs
['i_first'];
916 * This function is not part of the public api.
917 * @return string initial of last name we are currently filtering by
919 function get_initial_last() {
920 if (!$this->use_initials
) {
924 return $this->prefs
['i_last'];
928 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
929 * @param array $alpha of letters in the alphabet.
930 * @param string $current the currently selected letter.
931 * @param string $class class name to add to this initial bar.
932 * @param string $title the name to put in front of this initial bar.
933 * @param string $urlvar URL parameter name for this initial.
935 * @deprecated since Moodle 3.3
937 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
939 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
940 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER
);
942 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
945 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
947 echo html_writer
::tag('strong', get_string('all'));
950 foreach ($alpha as $letter) {
951 if ($letter === $current) {
952 echo html_writer
::tag('strong', $letter);
954 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
958 echo html_writer
::end_tag('div');
962 * This function is not part of the public api.
964 function print_initials_bar() {
967 $ifirst = $this->get_initial_first();
968 $ilast = $this->get_initial_last();
969 if (is_null($ifirst)) {
972 if (is_null($ilast)) {
976 if ((!empty($ifirst) ||
!empty($ilast) ||
$this->use_initials
)
977 && isset($this->columns
['fullname'])) {
978 $prefixfirst = $this->request
[TABLE_VAR_IFIRST
];
979 $prefixlast = $this->request
[TABLE_VAR_ILAST
];
980 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl
);
981 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl
);
987 * This function is not part of the public api.
989 function print_nothing_to_display() {
992 // Render the dynamic table header.
993 echo $this->get_dynamic_table_html_start();
995 // Render button to allow user to reset table preferences.
996 echo $this->render_reset_button();
998 $this->print_initials_bar();
1000 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1002 // Render the dynamic table footer.
1003 echo $this->get_dynamic_table_html_end();
1007 * This function is not part of the public api.
1009 function get_row_from_keyed($rowwithkeys) {
1010 if (is_object($rowwithkeys)) {
1011 $rowwithkeys = (array)$rowwithkeys;
1014 foreach (array_keys($this->columns
) as $column) {
1015 if (isset($rowwithkeys[$column])) {
1016 $row [] = $rowwithkeys[$column];
1025 * Get the html for the download buttons
1027 * Usually only use internally
1029 public function download_buttons() {
1032 if ($this->is_downloadable() && !$this->is_downloading()) {
1033 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1034 $this->baseurl
->out_omit_querystring(), 'download', $this->baseurl
->params());
1041 * This function is not part of the public api.
1042 * You don't normally need to call this. It is called automatically when
1043 * needed when you start adding data to the table.
1046 function start_output() {
1047 $this->started_output
= true;
1048 if ($this->exportclass
!==null) {
1049 $this->exportclass
->start_table($this->sheettitle
);
1050 $this->exportclass
->output_headers($this->headers
);
1052 $this->start_html();
1053 $this->print_headers();
1054 echo html_writer
::start_tag('tbody');
1059 * This function is not part of the public api.
1061 function print_row($row, $classname = '') {
1062 echo $this->get_row_html($row, $classname);
1066 * Generate html code for the passed row.
1068 * @param array $row Row data.
1069 * @param string $classname classes to add.
1071 * @return string $html html code for the row passed.
1073 public function get_row_html($row, $classname = '') {
1074 static $suppress_lastrow = NULL;
1075 $rowclasses = array();
1078 $rowclasses[] = $classname;
1081 $rowid = $this->uniqueid
. '_r' . $this->currentrow
;
1084 $html .= html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1086 // If we have a separator, print it
1087 if ($row === NULL) {
1088 $colcount = count($this->columns
);
1089 $html .= html_writer
::tag('td', html_writer
::tag('div', '',
1090 array('class' => 'tabledivider')), array('colspan' => $colcount));
1093 $colbyindex = array_flip($this->columns
);
1094 foreach ($row as $index => $data) {
1095 $column = $colbyindex[$index];
1098 'class' => "cell c{$index}" . $this->column_class
[$column],
1099 'id' => "{$rowid}_c{$index}",
1100 'style' => $this->make_styles_string($this->column_style
[$column]),
1104 if ($this->headercolumn
&& $column == $this->headercolumn
) {
1106 $attributes['scope'] = 'row';
1109 if (empty($this->prefs
['collapse'][$column])) {
1110 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1111 $content = ' ';
1116 $content = ' ';
1119 $html .= html_writer
::tag($celltype, $content, $attributes);
1123 $html .= html_writer
::end_tag('tr');
1125 $suppress_enabled = array_sum($this->column_suppress
);
1126 if ($suppress_enabled) {
1127 $suppress_lastrow = $row;
1129 $this->currentrow++
;
1134 * This function is not part of the public api.
1136 function finish_html() {
1137 global $OUTPUT, $PAGE;
1139 if (!$this->started_output
) {
1140 //no data has been added to the table.
1141 $this->print_nothing_to_display();
1144 // Print empty rows to fill the table to the current pagesize.
1145 // This is done so the header aria-controls attributes do not point to
1146 // non existant elements.
1147 $emptyrow = array_fill(0, count($this->columns
), '');
1148 while ($this->currentrow
< $this->pagesize
) {
1149 $this->print_row($emptyrow, 'emptyrow');
1152 echo html_writer
::end_tag('tbody');
1153 echo html_writer
::end_tag('table');
1154 echo html_writer
::end_tag('div');
1155 $this->wrap_html_finish();
1158 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1159 echo $this->download_buttons();
1162 if($this->use_pages
) {
1163 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1164 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1165 echo $OUTPUT->render($pagingbar);
1168 // Render the dynamic table footer.
1169 echo $this->get_dynamic_table_html_end();
1174 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1175 * used by {@link print_headers()}.
1176 * @param string $column the column name, index into various names.
1177 * @param int $index numerical index of the column.
1178 * @return string HTML fragment.
1180 protected function show_hide_link($column, $index) {
1182 // Some headers contain <br /> tags, do not include in title, hence the
1186 for ($i = 0; $i < $this->pagesize
; $i++
) {
1187 $ariacontrols .= $this->uniqueid
. '_r' . $i . '_c' . $index . ' ';
1190 $ariacontrols = trim($ariacontrols);
1192 if (!empty($this->prefs
['collapse'][$column])) {
1193 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index]),
1194 'aria-expanded' => 'false',
1195 'aria-controls' => $ariacontrols,
1196 'data-action' => 'show',
1197 'data-column' => $column);
1198 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1199 $OUTPUT->pix_icon('t/switch_plus', null), $linkattributes);
1201 } else if ($this->headers
[$index] !== NULL) {
1202 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index]),
1203 'aria-expanded' => 'true',
1204 'aria-controls' => $ariacontrols,
1205 'data-action' => 'hide',
1206 'data-column' => $column);
1207 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1208 $OUTPUT->pix_icon('t/switch_minus', null), $linkattributes);
1213 * This function is not part of the public api.
1215 function print_headers() {
1216 global $CFG, $OUTPUT;
1218 // Set the primary sort column/order where possible, so that sort links/icons are correct.
1220 'sortby' => $primarysortcolumn,
1221 'sortorder' => $primarysortorder,
1222 ] = $this->get_primary_sort_order();
1224 echo html_writer
::start_tag('thead');
1225 echo html_writer
::start_tag('tr');
1226 foreach ($this->columns
as $column => $index) {
1229 if ($this->is_collapsible
) {
1230 $icon_hide = $this->show_hide_link($column, $index);
1235 // Check the full name display for sortable fields.
1236 if (has_capability('moodle/site:viewfullnames', $this->get_context())) {
1237 $nameformat = $CFG->alternativefullnameformat
;
1239 $nameformat = $CFG->fullnamedisplay
;
1242 if ($nameformat == 'language') {
1243 $nameformat = get_string('fullnamedisplay');
1246 $requirednames = order_in_string(\core_user\fields
::get_name_fields(), $nameformat);
1248 if (!empty($requirednames)) {
1249 if ($this->is_sortable($column)) {
1250 // Done this way for the possibility of more than two sortable full name display fields.
1251 $this->headers
[$index] = '';
1252 foreach ($requirednames as $name) {
1253 $sortname = $this->sort_link(get_string($name),
1254 $name, $primarysortcolumn === $name, $primarysortorder);
1255 $this->headers
[$index] .= $sortname . ' / ';
1258 if (isset($this->helpforheaders
[$index])) {
1259 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1261 $this->headers
[$index] = substr($this->headers
[$index], 0, -3). $helpicon;
1267 // do nothing, do not display sortable links
1271 if ($this->is_sortable($column)) {
1273 if (isset($this->helpforheaders
[$index])) {
1274 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1276 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1277 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1281 $attributes = array(
1282 'class' => 'header c' . $index . $this->column_class
[$column],
1285 if ($this->headers
[$index] === NULL) {
1286 $content = ' ';
1287 } else if (!empty($this->prefs
['collapse'][$column])) {
1288 $content = $icon_hide;
1290 if (is_array($this->column_style
[$column])) {
1291 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1294 if (isset($this->helpforheaders
[$index]) && !$this->is_sortable($column)) {
1295 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1297 $content = $this->headers
[$index] . $helpicon . html_writer
::tag('div',
1298 $icon_hide, array('class' => 'commands'));
1300 echo html_writer
::tag('th', $content, $attributes);
1303 echo html_writer
::end_tag('tr');
1304 echo html_writer
::end_tag('thead');
1308 * Calculate the preferences for sort order based on user-supplied values and get params.
1310 protected function set_sorting_preferences(): void
{
1311 $sortdata = $this->sortdata
;
1313 if ($sortdata === null) {
1314 $sortdata = $this->prefs
['sortby'];
1316 $sortorder = optional_param($this->request
[TABLE_VAR_DIR
], $this->sort_default_order
, PARAM_INT
);
1317 $sortby = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
);
1319 if (array_key_exists($sortby, $sortdata)) {
1320 // This key already exists somewhere. Change its sortorder and bring it to the top.
1321 unset($sortdata[$sortby]);
1323 $sortdata = array_merge([$sortby => $sortorder], $sortdata);
1326 $usernamefields = \core_user\fields
::get_name_fields();
1327 $sortdata = array_filter($sortdata, function($sortby) use ($usernamefields) {
1328 $isvalidsort = $sortby && $this->is_sortable($sortby);
1329 $isvalidsort = $isvalidsort && empty($this->prefs
['collapse'][$sortby]);
1330 $isrealcolumn = isset($this->columns
[$sortby]);
1331 $isfullnamefield = isset($this->columns
['fullname']) && in_array($sortby, $usernamefields);
1333 return $isvalidsort && ($isrealcolumn ||
$isfullnamefield);
1334 }, ARRAY_FILTER_USE_KEY
);
1336 // Finally, make sure that no more than $this->maxsortkeys are present into the array.
1337 $sortdata = array_slice($sortdata, 0, $this->maxsortkeys
);
1339 // If a default order is defined and it is not in the current list of order by columns, add it at the end.
1340 // This prevents results from being returned in a random order if the only order by column contains equal values.
1341 if (!empty($this->sort_default_column
) && !array_key_exists($this->sort_default_column
, $sortdata)) {
1342 $sortdata = array_merge($sortdata, [$this->sort_default_column
=> $this->sort_default_order
]);
1345 // Apply the sortdata to the preference.
1346 $this->prefs
['sortby'] = $sortdata;
1350 * Fill in the preferences for the initials bar.
1352 protected function set_initials_preferences(): void
{
1353 $ifirst = $this->ifirst
;
1354 $ilast = $this->ilast
;
1356 if ($ifirst === null) {
1357 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
1360 if ($ilast === null) {
1361 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
1364 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
1365 $this->prefs
['i_first'] = $ifirst;
1368 if (!is_null($ilast) && ($ilast === '' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
1369 $this->prefs
['i_last'] = $ilast;
1375 * Set hide and show preferences.
1377 protected function set_hide_show_preferences(): void
{
1379 if ($this->hiddencolumns
!== null) {
1380 $this->prefs
['collapse'] = array_fill_keys(array_filter($this->hiddencolumns
, function($column) {
1381 return array_key_exists($column, $this->columns
);
1384 if ($column = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) {
1385 if (isset($this->columns
[$column])) {
1386 $this->prefs
['collapse'][$column] = true;
1391 if ($column = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) {
1392 unset($this->prefs
['collapse'][$column]);
1395 foreach (array_keys($this->prefs
['collapse']) as $column) {
1396 if (array_key_exists($column, $this->prefs
['sortby'])) {
1397 unset($this->prefs
['sortby'][$column]);
1403 * Set the list of hidden columns.
1405 * @param array $columns The list of hidden columns.
1407 public function set_hidden_columns(array $columns): void
{
1408 $this->hiddencolumns
= $columns;
1412 * Initialise table preferences.
1414 protected function initialise_table_preferences(): void
{
1417 // Load any existing user preferences.
1418 if ($this->persistent
) {
1419 $this->prefs
= json_decode(get_user_preferences('flextable_' . $this->uniqueid
), true);
1420 $oldprefs = $this->prefs
;
1421 } else if (isset($SESSION->flextable
[$this->uniqueid
])) {
1422 $this->prefs
= $SESSION->flextable
[$this->uniqueid
];
1423 $oldprefs = $this->prefs
;
1426 // Set up default preferences if needed.
1427 if (!$this->prefs ||
$this->is_resetting_preferences()) {
1433 'textsort' => $this->column_textsort
,
1437 if (!isset($oldprefs)) {
1438 $oldprefs = $this->prefs
;
1441 // Save user preferences if they have changed.
1442 if ($this->is_resetting_preferences()) {
1443 $this->sortdata
= null;
1444 $this->ifirst
= null;
1445 $this->ilast
= null;
1448 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
1449 isset($this->columns
[$showcol])) {
1450 $this->prefs
['collapse'][$showcol] = false;
1451 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
1452 isset($this->columns
[$hidecol])) {
1453 $this->prefs
['collapse'][$hidecol] = true;
1454 if (array_key_exists($hidecol, $this->prefs
['sortby'])) {
1455 unset($this->prefs
['sortby'][$hidecol]);
1459 $this->set_hide_show_preferences();
1460 $this->set_sorting_preferences();
1461 $this->set_initials_preferences();
1463 // Now, reduce the width of collapsed columns and remove the width from columns that should be expanded.
1464 foreach (array_keys($this->columns
) as $column) {
1465 if (!empty($this->prefs
['collapse'][$column])) {
1466 $this->column_style
[$column]['width'] = '10px';
1468 unset($this->column_style
[$column]['width']);
1472 if (empty($this->baseurl
)) {
1473 debugging('You should set baseurl when using flexible_table.');
1475 $this->baseurl
= $PAGE->url
;
1478 if ($this->currpage
== null) {
1479 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
1482 $this->save_preferences($oldprefs);
1488 * @param array $oldprefs Old preferences to compare against.
1490 protected function save_preferences($oldprefs): void
{
1493 if ($this->prefs
!= $oldprefs) {
1494 if ($this->persistent
) {
1495 set_user_preference('flextable_' . $this->uniqueid
, json_encode($this->prefs
));
1497 $SESSION->flextable
[$this->uniqueid
] = $this->prefs
;
1504 * Set the preferred table sorting attributes.
1506 * @param string $sortby The field to sort by.
1507 * @param int $sortorder The sort order.
1509 public function set_sortdata(array $sortdata): void
{
1510 $this->sortdata
= [];
1511 foreach ($sortdata as $sortitem) {
1512 if (!array_key_exists($sortitem['sortby'], $this->sortdata
)) {
1513 $this->sortdata
[$sortitem['sortby']] = (int) $sortitem['sortorder'];
1519 * Get the default per page.
1523 public function get_default_per_page(): int {
1524 return $this->defaultperpage
;
1528 * Set the default per page.
1530 * @param int $defaultperpage
1532 public function set_default_per_page(int $defaultperpage): void
{
1533 $this->defaultperpage
= $defaultperpage;
1537 * Set the preferred first name initial in an initials bar.
1539 * @param string $initial The character to set
1541 public function set_first_initial(string $initial): void
{
1542 $this->ifirst
= $initial;
1546 * Set the preferred last name initial in an initials bar.
1548 * @param string $initial The character to set
1550 public function set_last_initial(string $initial): void
{
1551 $this->ilast
= $initial;
1555 * Set the page number.
1557 * @param int $pagenumber The page number.
1559 public function set_page_number(int $pagenumber): void
{
1560 $this->currpage
= $pagenumber - 1;
1564 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1565 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1566 * @param int $order SORT_ASC or SORT_DESC
1567 * @return string HTML fragment.
1569 protected function sort_icon($isprimary, $order) {
1576 if ($order == SORT_ASC
) {
1577 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1579 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1584 * Generate the correct tool tip for changing the sort order. This is a
1585 * helper method used by {@link sort_link()}.
1586 * @param bool $isprimary whether the is column is the current primary sort column.
1587 * @param int $order SORT_ASC or SORT_DESC
1588 * @return string the correct title.
1590 protected function sort_order_name($isprimary, $order) {
1591 if ($isprimary && $order != SORT_ASC
) {
1592 return get_string('desc');
1594 return get_string('asc');
1599 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1600 * @param string $text the text for the link.
1601 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1602 * @param bool $isprimary whether the is column is the current primary sort column.
1603 * @param int $order SORT_ASC or SORT_DESC
1604 * @return string HTML fragment.
1606 protected function sort_link($text, $column, $isprimary, $order) {
1607 // If we are already sorting by this column, switch direction.
1608 if (array_key_exists($column, $this->prefs
['sortby'])) {
1609 $sortorder = $this->prefs
['sortby'][$column] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
1611 $sortorder = $order;
1615 $this->request
[TABLE_VAR_SORT
] => $column,
1616 $this->request
[TABLE_VAR_DIR
] => $sortorder,
1619 return html_writer
::link($this->baseurl
->out(false, $params),
1620 $text . get_accesshide(get_string('sortby') . ' ' .
1621 $text . ' ' . $this->sort_order_name($isprimary, $order)),
1623 'data-sortable' => $this->is_sortable($column),
1624 'data-sortby' => $column,
1625 'data-sortorder' => $sortorder,
1626 ]) . ' ' . $this->sort_icon($isprimary, $order);
1630 * Return primary sorting column/order, either the first preferred "sortby" value or defaults defined for the table
1634 protected function get_primary_sort_order(): array {
1635 if (reset($this->prefs
['sortby'])) {
1636 return $this->get_sort_order();
1640 'sortby' => $this->sort_default_column
,
1641 'sortorder' => $this->sort_default_order
,
1646 * Return sorting attributes values.
1650 protected function get_sort_order(): array {
1651 $sortbys = $this->prefs
['sortby'];
1652 $sortby = key($sortbys);
1655 'sortby' => $sortby,
1656 'sortorder' => $sortbys[$sortby],
1661 * Get dynamic class component.
1665 protected function get_component() {
1666 $tableclass = explode("\\", get_class($this));
1667 return reset($tableclass);
1671 * Get dynamic class handler.
1675 protected function get_handler() {
1676 $tableclass = explode("\\", get_class($this));
1677 return end($tableclass);
1681 * Get the dynamic table start wrapper.
1682 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1686 protected function get_dynamic_table_html_start(): string {
1687 if (is_a($this, \core_table\dynamic
::class)) {
1688 $sortdata = array_map(function($sortby, $sortorder) {
1690 'sortby' => $sortby,
1691 'sortorder' => $sortorder,
1693 }, array_keys($this->prefs
['sortby']), array_values($this->prefs
['sortby']));;
1695 return html_writer
::start_tag('div', [
1696 'class' => 'table-dynamic position-relative',
1697 'data-region' => 'core_table/dynamic',
1698 'data-table-handler' => $this->get_handler(),
1699 'data-table-component' => $this->get_component(),
1700 'data-table-uniqueid' => $this->uniqueid
,
1701 'data-table-filters' => json_encode($this->get_filterset()),
1702 'data-table-sort-data' => json_encode($sortdata),
1703 'data-table-first-initial' => $this->prefs
['i_first'],
1704 'data-table-last-initial' => $this->prefs
['i_last'],
1705 'data-table-page-number' => $this->currpage +
1,
1706 'data-table-page-size' => $this->pagesize
,
1707 'data-table-default-per-page' => $this->get_default_per_page(),
1708 'data-table-hidden-columns' => json_encode(array_keys($this->prefs
['collapse'])),
1709 'data-table-total-rows' => $this->totalrows
,
1717 * Get the dynamic table end wrapper.
1718 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1722 protected function get_dynamic_table_html_end(): string {
1725 if (is_a($this, \core_table\dynamic
::class)) {
1728 $perpageurl = new moodle_url($PAGE->url
);
1730 // Generate "Show all/Show per page" link.
1731 if ($this->pagesize
== TABLE_SHOW_ALL_PAGE_SIZE
&& $this->totalrows
> $this->get_default_per_page()) {
1732 $perpagesize = $this->get_default_per_page();
1733 $perpagestring = get_string('showperpage', '', $this->get_default_per_page());
1734 } else if ($this->pagesize
< $this->totalrows
) {
1735 $perpagesize = TABLE_SHOW_ALL_PAGE_SIZE
;
1736 $perpagestring = get_string('showall', '', $this->totalrows
);
1738 if (isset($perpagesize) && isset($perpagestring)) {
1739 $perpageurl->param('perpage', $perpagesize);
1740 $output .= html_writer
::link(
1744 'data-action' => 'showcount',
1745 'data-target-page-size' => $perpagesize,
1750 $PAGE->requires
->js_call_amd('core_table/dynamic', 'init');
1751 $output .= html_writer
::end_tag('div');
1759 * This function is not part of the public api.
1761 function start_html() {
1764 // Render the dynamic table header.
1765 echo $this->get_dynamic_table_html_start();
1767 // Render button to allow user to reset table preferences.
1768 echo $this->render_reset_button();
1770 // Do we need to print initial bars?
1771 $this->print_initials_bar();
1774 if ($this->use_pages
) {
1775 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1776 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1777 echo $OUTPUT->render($pagingbar);
1780 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1781 echo $this->download_buttons();
1784 $this->wrap_html_start();
1785 // Start of main data table
1787 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1788 echo html_writer
::start_tag('table', $this->attributes
);
1793 * This function is not part of the public api.
1794 * @param array $styles CSS-property => value
1795 * @return string values suitably to go in a style="" attribute in HTML.
1797 function make_styles_string($styles) {
1798 if (empty($styles)) {
1803 foreach($styles as $property => $value) {
1804 $string .= $property . ':' . $value . ';';
1810 * Generate the HTML for the table preferences reset button.
1812 * @return string HTML fragment, empty string if no need to reset
1814 protected function render_reset_button() {
1816 if (!$this->can_be_reset()) {
1820 $url = $this->baseurl
->out(false, array($this->request
[TABLE_VAR_RESET
] => 1));
1822 $html = html_writer
::start_div('resettable mdl-right');
1823 $html .= html_writer
::link($url, get_string('resettable'));
1824 $html .= html_writer
::end_div();
1830 * Are there some table preferences that can be reset?
1832 * If true, then the "reset table preferences" widget should be displayed.
1836 protected function can_be_reset() {
1837 // Loop through preferences and make sure they are empty or set to the default value.
1838 foreach ($this->prefs
as $prefname => $prefval) {
1839 if ($prefname === 'sortby' and !empty($this->sort_default_column
)) {
1840 // Check if the actual sorting differs from the default one.
1841 if (empty($prefval) or $prefval !== array($this->sort_default_column
=> $this->sort_default_order
)) {
1845 } else if ($prefname === 'collapse' and !empty($prefval)) {
1846 // Check if there are some collapsed columns (all are expanded by default).
1847 foreach ($prefval as $columnname => $iscollapsed) {
1853 } else if (!empty($prefval)) {
1854 // For all other cases, we just check if some preference is set.
1863 * Get the context for the table.
1865 * Note: This function _must_ be overridden by dynamic tables to ensure that the context is correctly determined
1866 * from the filterset parameters.
1870 public function get_context(): context
{
1873 if (is_a($this, \core_table\dynamic
::class)) {
1874 throw new coding_exception('The get_context function must be defined for a dynamic table');
1877 return $PAGE->context
;
1881 * Set the filterset in the table class.
1883 * The use of filtersets is a requirement for dynamic tables, but can be used by other tables too if desired.
1885 * @param filterset $filterset The filterset object to get filters and table parameters from
1887 public function set_filterset(filterset
$filterset): void
{
1888 $this->filterset
= $filterset;
1890 $this->guess_base_url();
1894 * Get the currently defined filterset.
1898 public function get_filterset(): ?filterset
{
1899 return $this->filterset
;
1903 * Attempt to guess the base URL.
1905 public function guess_base_url(): void
{
1906 if (is_a($this, \core_table\dynamic
::class)) {
1907 throw new coding_exception('The guess_base_url function must be defined for a dynamic table');
1914 * @package moodlecore
1915 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1916 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1918 class table_sql
extends flexible_table
{
1920 public $countsql = NULL;
1921 public $countparams = NULL;
1923 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1927 * @var array|\Traversable Data fetched from the db.
1929 public $rawdata = NULL;
1932 * @var bool Overriding default for this.
1934 public $is_sortable = true;
1936 * @var bool Overriding default for this.
1938 public $is_collapsible = true;
1941 * @param string $uniqueid a string identifying this table.Used as a key in
1944 function __construct($uniqueid) {
1945 parent
::__construct($uniqueid);
1946 // some sensible defaults
1947 $this->set_attribute('class', 'generaltable generalbox');
1951 * Take the data returned from the db_query and go through all the rows
1952 * processing each col using either col_{columnname} method or other_cols
1953 * method or if other_cols returns NULL then put the data straight into the
1956 * After calling this function, don't forget to call close_recordset.
1958 public function build_table() {
1960 if ($this->rawdata
instanceof \Traversable
&& !$this->rawdata
->valid()) {
1963 if (!$this->rawdata
) {
1967 foreach ($this->rawdata
as $row) {
1968 $formattedrow = $this->format_row($row);
1969 $this->add_data_keyed($formattedrow,
1970 $this->get_row_class($row));
1975 * Closes recordset (for use after building the table).
1977 public function close_recordset() {
1978 if ($this->rawdata
&& ($this->rawdata
instanceof \core\dml\recordset_walk ||
1979 $this->rawdata
instanceof moodle_recordset
)) {
1980 $this->rawdata
->close();
1981 $this->rawdata
= null;
1986 * Get any extra classes names to add to this row in the HTML.
1987 * @param $row array the data for this row.
1988 * @return string added to the class="" attribute of the tr.
1990 function get_row_class($row) {
1995 * This is only needed if you want to use different sql to count rows.
1996 * Used for example when perhaps all db JOINS are not needed when counting
1997 * records. You don't need to call this function the count_sql
1998 * will be generated automatically.
2000 * We need to count rows returned by the db seperately to the query itself
2001 * as we need to know how many pages of data we have to display.
2003 function set_count_sql($sql, array $params = NULL) {
2004 $this->countsql
= $sql;
2005 $this->countparams
= $params;
2009 * Set the sql to query the db. Query will be :
2010 * SELECT $fields FROM $from WHERE $where
2011 * Of course you can use sub-queries, JOINS etc. by putting them in the
2012 * appropriate clause of the query.
2014 function set_sql($fields, $from, $where, array $params = array()) {
2015 $this->sql
= new stdClass();
2016 $this->sql
->fields
= $fields;
2017 $this->sql
->from
= $from;
2018 $this->sql
->where
= $where;
2019 $this->sql
->params
= $params;
2023 * Query the db. Store results in the table object for use by build_table.
2025 * @param int $pagesize size of page for paginated displayed table.
2026 * @param bool $useinitialsbar do you want to use the initials bar. Bar
2027 * will only be used if there is a fullname column defined for the table.
2029 function query_db($pagesize, $useinitialsbar=true) {
2031 if (!$this->is_downloading()) {
2032 if ($this->countsql
=== NULL) {
2033 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
2034 $this->countparams
= $this->sql
->params
;
2036 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
2037 if ($useinitialsbar && !$this->is_downloading()) {
2038 $this->initialbars(true);
2041 list($wsql, $wparams) = $this->get_sql_where();
2043 $this->countsql
.= ' AND '.$wsql;
2044 $this->countparams
= array_merge($this->countparams
, $wparams);
2046 $this->sql
->where
.= ' AND '.$wsql;
2047 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
2049 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
2051 $total = $grandtotal;
2054 $this->pagesize($pagesize, $total);
2057 // Fetch the attempts
2058 $sort = $this->get_sql_sort();
2060 $sort = "ORDER BY $sort";
2063 {$this->sql->fields}
2064 FROM {$this->sql->from}
2065 WHERE {$this->sql->where}
2068 if (!$this->is_downloading()) {
2069 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
2071 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
2076 * Convenience method to call a number of methods for you to display the
2079 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
2081 if (!$this->columns
) {
2082 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
2083 $this->sql
->params
, IGNORE_MULTIPLE
);
2084 //if columns is not set then define columns as the keys of the rows returned
2086 $this->define_columns(array_keys((array)$onerow));
2087 $this->define_headers(array_keys((array)$onerow));
2089 $this->pagesize
= $pagesize;
2091 $this->query_db($pagesize, $useinitialsbar);
2092 $this->build_table();
2093 $this->close_recordset();
2094 $this->finish_output();
2100 * @package moodlecore
2101 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2104 class table_default_export_format_parent
{
2106 * @var flexible_table or child class reference pointing to table class
2107 * object from which to export data.
2112 * @var bool output started. Keeps track of whether any output has been
2115 var $documentstarted = false;
2120 * @param flexible_table $table
2122 public function __construct(&$table) {
2123 $this->table
=& $table;
2127 * Old syntax of class constructor. Deprecated in PHP7.
2129 * @deprecated since Moodle 3.1
2131 public function table_default_export_format_parent(&$table) {
2132 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2133 self
::__construct($table);
2136 function set_table(&$table) {
2137 $this->table
=& $table;
2140 function add_data($row) {
2144 function add_seperator() {
2148 function document_started() {
2149 return $this->documentstarted
;
2152 * Given text in a variety of format codings, this function returns
2153 * the text as safe HTML or as plain text dependent on what is appropriate
2154 * for the download format. The default removes all tags.
2156 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
2157 //use some whitespace to indicate where there was some line spacing.
2158 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
2159 return strip_tags($text);
2164 * Dataformat exporter
2167 * @subpackage tablelib
2168 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
2169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2171 class table_dataformat_export_format
extends table_default_export_format_parent
{
2173 /** @var \core\dataformat\base $dataformat */
2174 protected $dataformat;
2177 protected $rownum = 0;
2179 /** @var $columns */
2185 * @param string $table An sql table
2186 * @param string $dataformat type of dataformat for export
2188 public function __construct(&$table, $dataformat) {
2189 parent
::__construct($table);
2191 if (ob_get_length()) {
2192 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
2195 $classname = 'dataformat_' . $dataformat . '\writer';
2196 if (!class_exists($classname)) {
2197 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
2199 $this->dataformat
= new $classname;
2201 // The dataformat export time to first byte could take a while to generate...
2204 // Close the session so that the users other tabs in the same session are not blocked.
2205 \core\session\manager
::write_close();
2209 * Whether the current dataformat supports export of HTML
2213 public function supports_html(): bool {
2214 return $this->dataformat
->supports_html();
2220 * @param string $filename
2221 * @param string $sheettitle
2223 public function start_document($filename, $sheettitle) {
2224 $this->documentstarted
= true;
2225 $this->dataformat
->set_filename($filename);
2226 $this->dataformat
->send_http_headers();
2227 $this->dataformat
->set_sheettitle($sheettitle);
2228 $this->dataformat
->start_output();
2234 * @param string $sheettitle optional spreadsheet worksheet title
2236 public function start_table($sheettitle) {
2237 $this->dataformat
->set_sheettitle($sheettitle);
2243 * @param array $headers
2245 public function output_headers($headers) {
2246 $this->columns
= $headers;
2247 if (method_exists($this->dataformat
, 'write_header')) {
2248 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
2249 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
2250 $this->dataformat
->write_header($headers);
2252 $this->dataformat
->start_sheet($headers);
2259 * @param array $row One record of data
2261 public function add_data($row) {
2262 $this->dataformat
->write_record($row, $this->rownum++
);
2269 public function finish_table() {
2270 if (method_exists($this->dataformat
, 'write_footer')) {
2271 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
2272 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
2273 $this->dataformat
->write_footer($this->columns
);
2275 $this->dataformat
->close_sheet($this->columns
);
2282 public function finish_document() {
2283 $this->dataformat
->close_output();