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);
49 use core_table\local\filter\filterset
;
53 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 class flexible_table
{
59 var $attributes = array();
60 var $headers = array();
63 * @var string A column which should be considered as a header column.
65 protected $headercolumn = null;
68 * @var string For create header with help icon.
70 private $helpforheaders = array();
71 var $columns = array();
72 var $column_style = array();
73 var $column_class = array();
74 var $column_suppress = array();
75 var $column_nosort = array('userpic');
76 private $column_textsort = array();
77 /** @var boolean Stores if setup has already been called on this flixible table. */
80 var $request = array();
83 * @var bool Whether or not to store table properties in the user_preferences table.
85 private $persistent = false;
86 var $is_collapsible = false;
87 var $is_sortable = false;
90 * @var array The fields to sort.
94 /** @var string The manually set first name initial preference */
97 /** @var string The manually set last name initial preference */
100 var $use_pages = false;
101 var $use_initials = false;
103 var $maxsortkeys = 2;
108 var $sort_default_column = NULL;
109 var $sort_default_order = SORT_ASC
;
112 * Array of positions in which to display download controls.
114 var $showdownloadbuttonsat= array(TABLE_P_TOP
);
117 * @var string Key of field returned by db query that is the id field of the
118 * user table or equivalent.
120 public $useridfield = 'id';
123 * @var string which download plugin to use. Default '' means none - print
124 * html table with paging. Property set by is_downloading which typically
125 * passes in cleaned data from $
130 * @var bool whether data is downloadable from table. Determines whether
131 * to display download buttons. Set by method downloadable().
133 var $downloadable = false;
136 * @var bool Has start output been called yet?
138 var $started_output = false;
140 var $exportclass = null;
143 * @var array For storing user-customised table properties in the user_preferences db table.
145 private $prefs = array();
147 /** @var $sheettitle */
148 protected $sheettitle;
150 /** @var $filename */
153 /** @var array $hiddencolumns List of hidden columns. */
154 protected $hiddencolumns;
156 /** @var $resetting bool Whether the table preferences is resetting. */
157 protected $resetting;
160 * @var filterset The currently applied filerset
161 * This is required for dynamic tables, but can be used by other tables too if desired.
163 protected $filterset = null;
167 * @param string $uniqueid all tables have to have a unique id, this is used
168 * as a key when storing table properties like sort order in the session.
170 function __construct($uniqueid) {
171 $this->uniqueid
= $uniqueid;
172 $this->request
= array(
173 TABLE_VAR_SORT
=> 'tsort',
174 TABLE_VAR_HIDE
=> 'thide',
175 TABLE_VAR_SHOW
=> 'tshow',
176 TABLE_VAR_IFIRST
=> 'tifirst',
177 TABLE_VAR_ILAST
=> 'tilast',
178 TABLE_VAR_PAGE
=> 'page',
179 TABLE_VAR_RESET
=> 'treset',
180 TABLE_VAR_DIR
=> 'tdir',
185 * Call this to pass the download type. Use :
186 * $download = optional_param('download', '', PARAM_ALPHA);
187 * To get the download type. We assume that if you call this function with
188 * params that this table's data is downloadable, so we call is_downloadable
189 * for you (even if the param is '', which means no download this time.
190 * Also you can call this method with no params to get the current set
192 * @param string $download dataformat type. One of csv, xhtml, ods, etc
193 * @param string $filename filename for downloads without file extension.
194 * @param string $sheettitle title for downloaded data.
195 * @return string download dataformat type. One of csv, xhtml, ods, etc
197 function is_downloading($download = null, $filename='', $sheettitle='') {
198 if ($download!==null) {
199 $this->sheettitle
= $sheettitle;
200 $this->is_downloadable(true);
201 $this->download
= $download;
202 $this->filename
= clean_filename($filename);
203 $this->export_class_instance();
205 return $this->download
;
209 * Get, and optionally set, the export class.
210 * @param $exportclass (optional) if passed, set the table to use this export class.
211 * @return table_default_export_format_parent the export class in use (after any set).
213 function export_class_instance($exportclass = null) {
214 if (!is_null($exportclass)) {
215 $this->started_output
= true;
216 $this->exportclass
= $exportclass;
217 $this->exportclass
->table
= $this;
218 } else if (is_null($this->exportclass
) && !empty($this->download
)) {
219 $this->exportclass
= new table_dataformat_export_format($this, $this->download
);
220 if (!$this->exportclass
->document_started()) {
221 $this->exportclass
->start_document($this->filename
, $this->sheettitle
);
224 return $this->exportclass
;
228 * Probably don't need to call this directly. Calling is_downloading with a
229 * param automatically sets table as downloadable.
231 * @param bool $downloadable optional param to set whether data from
232 * table is downloadable. If ommitted this function can be used to get
233 * current state of table.
234 * @return bool whether table data is set to be downloadable.
236 function is_downloadable($downloadable = null) {
237 if ($downloadable !== null) {
238 $this->downloadable
= $downloadable;
240 return $this->downloadable
;
244 * Call with boolean true to store table layout changes in the user_preferences table.
245 * Note: user_preferences.value has a maximum length of 1333 characters.
246 * Call with no parameter to get current state of table persistence.
248 * @param bool $persistent Optional parameter to set table layout persistence.
249 * @return bool Whether or not the table layout preferences will persist.
251 public function is_persistent($persistent = null) {
252 if ($persistent == true) {
253 $this->persistent
= true;
255 return $this->persistent
;
259 * Where to show download buttons.
260 * @param array $showat array of postions in which to show download buttons.
261 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
263 function show_download_buttons_at($showat) {
264 $this->showdownloadbuttonsat
= $showat;
268 * Sets the is_sortable variable to the given boolean, sort_default_column to
269 * the given string, and the sort_default_order to the given integer.
271 * @param string $defaultcolumn
272 * @param int $defaultorder
275 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC
) {
276 $this->is_sortable
= $bool;
277 $this->sort_default_column
= $defaultcolumn;
278 $this->sort_default_order
= $defaultorder;
282 * Use text sorting functions for this column (required for text columns with Oracle).
283 * Be warned that you cannot use this with column aliases. You can only do this
284 * with real columns. See MDL-40481 for an example.
285 * @param string column name
287 function text_sorting($column) {
288 $this->column_textsort
[] = $column;
292 * Do not sort using this column
293 * @param string column name
295 function no_sorting($column) {
296 $this->column_nosort
[] = $column;
300 * Is the column sortable?
301 * @param string column name, null means table
304 function is_sortable($column = null) {
305 if (empty($column)) {
306 return $this->is_sortable
;
308 if (!$this->is_sortable
) {
311 return !in_array($column, $this->column_nosort
);
315 * Sets the is_collapsible variable to the given boolean.
319 function collapsible($bool) {
320 $this->is_collapsible
= $bool;
324 * Sets the use_pages variable to the given boolean.
328 function pageable($bool) {
329 $this->use_pages
= $bool;
333 * Sets the use_initials variable to the given boolean.
337 function initialbars($bool) {
338 $this->use_initials
= $bool;
342 * Sets the pagesize variable to the given integer, the totalrows variable
343 * to the given integer, and the use_pages variable to true.
344 * @param int $perpage
348 function pagesize($perpage, $total) {
349 $this->pagesize
= $perpage;
350 $this->totalrows
= $total;
351 $this->use_pages
= true;
355 * Assigns each given variable in the array to the corresponding index
356 * in the request class variable.
357 * @param array $variables
360 function set_control_variables($variables) {
361 foreach ($variables as $what => $variable) {
362 if (isset($this->request
[$what])) {
363 $this->request
[$what] = $variable;
369 * Gives the given $value to the $attribute index of $this->attributes.
370 * @param string $attribute
371 * @param mixed $value
374 function set_attribute($attribute, $value) {
375 $this->attributes
[$attribute] = $value;
379 * What this method does is set the column so that if the same data appears in
380 * consecutive rows, then it is not repeated.
382 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
383 * that when one student has made multiple attempts, their name is only printed in the row
384 * for their first attempt.
385 * @param int $column the index of a column.
387 function column_suppress($column) {
388 if (isset($this->column_suppress
[$column])) {
389 $this->column_suppress
[$column] = true;
394 * Sets the given $column index to the given $classname in $this->column_class.
396 * @param string $classname
399 function column_class($column, $classname) {
400 if (isset($this->column_class
[$column])) {
401 $this->column_class
[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
406 * Sets the given $column index and $property index to the given $value in $this->column_style.
408 * @param string $property
409 * @param mixed $value
412 function column_style($column, $property, $value) {
413 if (isset($this->column_style
[$column])) {
414 $this->column_style
[$column][$property] = $value;
419 * Sets all columns' $propertys to the given $value in $this->column_style.
420 * @param int $property
421 * @param string $value
424 function column_style_all($property, $value) {
425 foreach (array_keys($this->columns
) as $column) {
426 $this->column_style
[$column][$property] = $value;
431 * Sets $this->baseurl.
432 * @param moodle_url|string $url the url with params needed to call up this page
434 function define_baseurl($url) {
435 $this->baseurl
= new moodle_url($url);
439 * @param array $columns an array of identifying names for columns. If
440 * columns are sorted then column names must correspond to a field in sql.
442 function define_columns($columns) {
443 $this->columns
= array();
444 $this->column_style
= array();
445 $this->column_class
= array();
448 foreach ($columns as $column) {
449 $this->columns
[$column] = $colnum++
;
450 $this->column_style
[$column] = array();
451 $this->column_class
[$column] = '';
452 $this->column_suppress
[$column] = false;
457 * @param array $headers numerical keyed array of displayed string titles
460 function define_headers($headers) {
461 $this->headers
= $headers;
465 * Mark a specific column as being a table header using the column name defined in define_columns.
467 * Note: Only one column can be a header, and it will be rendered using a th tag.
469 * @param string $column
471 public function define_header_column(string $column) {
472 $this->headercolumn
= $column;
476 * Defines a help icon for the header
478 * Always use this function if you need to create header with sorting and help icon.
480 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
482 public function define_help_for_headers($helpicons) {
483 $this->helpforheaders
= $helpicons;
487 * Mark the table preferences to be reset.
489 public function mark_table_to_reset(): void
{
490 $this->resetting
= true;
494 * Is the table marked for reset preferences?
496 * @return bool True if the table is marked to reset, false otherwise.
498 protected function is_resetting_preferences(): bool {
499 if ($this->resetting
=== null) {
500 $this->resetting
= optional_param($this->request
[TABLE_VAR_RESET
], false, PARAM_BOOL
);
503 return $this->resetting
;
507 * Must be called after table is defined. Use methods above first. Cannot
508 * use functions below till after calling this method.
513 if (empty($this->columns
) ||
empty($this->uniqueid
)) {
517 $this->initialise_table_preferences();
519 if (empty($this->baseurl
)) {
520 debugging('You should set baseurl when using flexible_table.');
522 $this->baseurl
= $PAGE->url
;
525 if ($this->currpage
== null) {
526 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
531 // Always introduce the "flexible" class for the table if not specified
532 if (empty($this->attributes
)) {
533 $this->attributes
['class'] = 'flexible table table-striped table-hover';
534 } else if (!isset($this->attributes
['class'])) {
535 $this->attributes
['class'] = 'flexible table table-striped table-hover';
536 } else if (!in_array('flexible', explode(' ', $this->attributes
['class']))) {
537 $this->attributes
['class'] = trim('flexible table table-striped table-hover ' . $this->attributes
['class']);
542 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
543 * @param string $uniqueid the identifier for a table.
544 * @return SQL fragment that can be used in an ORDER BY clause.
546 public static function get_sort_for_table($uniqueid) {
548 if (isset($SESSION->flextable
[$uniqueid])) {
549 $prefs = $SESSION->flextable
[$uniqueid];
550 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
554 if (empty($prefs['sortby'])) {
557 if (empty($prefs['textsort'])) {
558 $prefs['textsort'] = array();
561 return self
::construct_order_by($prefs['sortby'], $prefs['textsort']);
565 * Prepare an an order by clause from the list of columns to be sorted.
566 * @param array $cols column name => SORT_ASC or SORT_DESC
567 * @return SQL fragment that can be used in an ORDER BY clause.
569 public static function construct_order_by($cols, $textsortcols=array()) {
573 foreach ($cols as $column => $order) {
574 if (in_array($column, $textsortcols)) {
575 $column = $DB->sql_order_by_text($column);
577 if ($order == SORT_ASC
) {
578 $bits[] = $column . ' ASC';
580 $bits[] = $column . ' DESC';
584 return implode(', ', $bits);
588 * @return SQL fragment that can be used in an ORDER BY clause.
590 public function get_sql_sort() {
591 return self
::construct_order_by($this->get_sort_columns(), $this->column_textsort
);
595 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
596 * @return array column name => SORT_... constant.
598 public function get_sort_columns() {
600 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
603 if (empty($this->prefs
['sortby'])) {
607 foreach ($this->prefs
['sortby'] as $column => $notused) {
608 if (isset($this->columns
[$column])) {
609 continue; // This column is OK.
611 if (in_array($column, get_all_user_name_fields()) &&
612 isset($this->columns
['fullname'])) {
613 continue; // This column is OK.
615 // This column is not OK.
616 unset($this->prefs
['sortby'][$column]);
619 return $this->prefs
['sortby'];
623 * @return int the offset for LIMIT clause of SQL
625 function get_page_start() {
626 if (!$this->use_pages
) {
629 return $this->currpage
* $this->pagesize
;
633 * @return int the pagesize for LIMIT clause of SQL
635 function get_page_size() {
636 if (!$this->use_pages
) {
639 return $this->pagesize
;
643 * @return string sql to add to where statement.
645 function get_sql_where() {
648 $conditions = array();
651 if (isset($this->columns
['fullname'])) {
655 if (!empty($this->prefs
['i_first'])) {
656 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
657 $params['ifirstc'.$i] = $this->prefs
['i_first'].'%';
659 if (!empty($this->prefs
['i_last'])) {
660 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
661 $params['ilastc'.$i] = $this->prefs
['i_last'].'%';
665 return array(implode(" AND ", $conditions), $params);
669 * Add a row of data to the table. This function takes an array or object with
670 * column names as keys or property names.
672 * It ignores any elements with keys that are not defined as columns. It
673 * puts in empty strings into the row when there is no element in the passed
674 * array corresponding to a column in the table. It puts the row elements in
675 * the proper order (internally row table data is stored by in arrays with
676 * a numerical index corresponding to the column number).
678 * @param object|array $rowwithkeys array keys or object property names are column names,
679 * as defined in call to define_columns.
680 * @param string $classname CSS class name to add to this row's tr tag.
682 function add_data_keyed($rowwithkeys, $classname = '') {
683 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
687 * Add a number of rows to the table at once. And optionally finish output after they have been added.
689 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
690 * object or array is added to table. We expect properties for the row array as would be
691 * passed to add_data_keyed.
692 * @param bool $finish
694 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
695 foreach ($rowstoadd as $row) {
697 $this->add_separator();
699 $this->add_data_keyed($this->format_row($row));
703 $this->finish_output(!$this->is_downloading());
708 * Add a seperator line to table.
710 function add_separator() {
714 $this->add_data(NULL);
718 * This method actually directly echoes the row passed to it now or adds it
719 * to the download. If this is the first row and start_output has not
720 * already been called this method also calls start_output to open the table
721 * or send headers for the downloaded.
722 * Can be used as before. print_html now calls finish_html to close table.
724 * @param array $row a numerically keyed row of data to add to the table.
725 * @param string $classname CSS class name to add to this row's tr tag.
726 * @return bool success.
728 function add_data($row, $classname = '') {
732 if (!$this->started_output
) {
733 $this->start_output();
735 if ($this->exportclass
!==null) {
737 $this->exportclass
->add_seperator();
739 $this->exportclass
->add_data($row);
742 $this->print_row($row, $classname);
748 * You should call this to finish outputting the table data after adding
749 * data to the table with add_data or add_data_keyed.
752 function finish_output($closeexportclassdoc = true) {
753 if ($this->exportclass
!==null) {
754 $this->exportclass
->finish_table();
755 if ($closeexportclassdoc) {
756 $this->exportclass
->finish_document();
759 $this->finish_html();
764 * Hook that can be overridden in child classes to wrap a table in a form
765 * for example. Called only when there is data to display and not
768 function wrap_html_start() {
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_finish() {
780 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
781 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
782 * displaying table as html, adding a div wrap, etc.
784 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
786 * @param array|object $row row of data from db used to make one row of the table.
787 * @return array one row for the table, added using add_data_keyed method.
789 function format_row($row) {
790 if (is_array($row)) {
793 $formattedrow = array();
794 foreach (array_keys($this->columns
) as $column) {
795 $colmethodname = 'col_'.$column;
796 if (method_exists($this, $colmethodname)) {
797 $formattedcolumn = $this->$colmethodname($row);
799 $formattedcolumn = $this->other_cols($column, $row);
800 if ($formattedcolumn===NULL) {
801 $formattedcolumn = $row->$column;
804 $formattedrow[$column] = $formattedcolumn;
806 return $formattedrow;
810 * Fullname is treated as a special columname in tablelib and should always
811 * be treated the same as the fullname of a user.
812 * @uses $this->useridfield if the userid field is not expected to be id
813 * then you need to override $this->useridfield to point at the correct
814 * field for the user id.
816 * @param object $row the data from the db containing all fields from the
817 * users table necessary to construct the full name of the user in
819 * @return string contents of cell in column 'fullname', for this row.
821 function col_fullname($row) {
824 $name = fullname($row, has_capability('moodle/site:viewfullnames', $this->get_context()));
825 if ($this->download
) {
829 $userid = $row->{$this->useridfield
};
830 if ($COURSE->id
== SITEID
) {
831 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
833 $profileurl = new moodle_url('/user/view.php',
834 array('id' => $userid, 'course' => $COURSE->id
));
836 return html_writer
::link($profileurl, $name);
840 * You can override this method in a child class. See the description of
841 * build_table which calls this method.
843 function other_cols($column, $row) {
848 * Used from col_* functions when text is to be displayed. Does the
849 * right thing - either converts text to html or strips any html tags
850 * depending on if we are downloading and what is the download type. Params
851 * are the same as format_text function in weblib.php but some default
852 * options are changed.
854 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
855 if (!$this->is_downloading()) {
856 if (is_null($options)) {
857 $options = new stdClass
;
859 //some sensible defaults
860 if (!isset($options->para
)) {
861 $options->para
= false;
863 if (!isset($options->newlines
)) {
864 $options->newlines
= false;
866 if (!isset($options->smiley
)) {
867 $options->smiley
= false;
869 if (!isset($options->filter
)) {
870 $options->filter
= false;
872 return format_text($text, $format, $options);
874 $eci = $this->export_class_instance();
875 return $eci->format_text($text, $format, $options, $courseid);
879 * This method is deprecated although the old api is still supported.
880 * @deprecated 1.9.2 - Jun 2, 2008
882 function print_html() {
886 $this->finish_html();
890 * This function is not part of the public api.
891 * @return string initial of first name we are currently filtering by
893 function get_initial_first() {
894 if (!$this->use_initials
) {
898 return $this->prefs
['i_first'];
902 * This function is not part of the public api.
903 * @return string initial of last name we are currently filtering by
905 function get_initial_last() {
906 if (!$this->use_initials
) {
910 return $this->prefs
['i_last'];
914 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
915 * @param array $alpha of letters in the alphabet.
916 * @param string $current the currently selected letter.
917 * @param string $class class name to add to this initial bar.
918 * @param string $title the name to put in front of this initial bar.
919 * @param string $urlvar URL parameter name for this initial.
921 * @deprecated since Moodle 3.3
923 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
925 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
926 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER
);
928 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
931 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
933 echo html_writer
::tag('strong', get_string('all'));
936 foreach ($alpha as $letter) {
937 if ($letter === $current) {
938 echo html_writer
::tag('strong', $letter);
940 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
944 echo html_writer
::end_tag('div');
948 * This function is not part of the public api.
950 function print_initials_bar() {
953 $ifirst = $this->get_initial_first();
954 $ilast = $this->get_initial_last();
955 if (is_null($ifirst)) {
958 if (is_null($ilast)) {
962 if ((!empty($ifirst) ||
!empty($ilast) ||
$this->use_initials
)
963 && isset($this->columns
['fullname'])) {
964 $prefixfirst = $this->request
[TABLE_VAR_IFIRST
];
965 $prefixlast = $this->request
[TABLE_VAR_ILAST
];
966 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl
);
967 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl
);
973 * This function is not part of the public api.
975 function print_nothing_to_display() {
978 // Render the dynamic table header.
979 echo $this->get_dynamic_table_html_start();
981 // Render button to allow user to reset table preferences.
982 echo $this->render_reset_button();
984 $this->print_initials_bar();
986 echo $OUTPUT->heading(get_string('nothingtodisplay'));
988 // Render the dynamic table footer.
989 echo $this->get_dynamic_table_html_end();
993 * This function is not part of the public api.
995 function get_row_from_keyed($rowwithkeys) {
996 if (is_object($rowwithkeys)) {
997 $rowwithkeys = (array)$rowwithkeys;
1000 foreach (array_keys($this->columns
) as $column) {
1001 if (isset($rowwithkeys[$column])) {
1002 $row [] = $rowwithkeys[$column];
1011 * Get the html for the download buttons
1013 * Usually only use internally
1015 public function download_buttons() {
1018 if ($this->is_downloadable() && !$this->is_downloading()) {
1019 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1020 $this->baseurl
->out_omit_querystring(), 'download', $this->baseurl
->params());
1027 * This function is not part of the public api.
1028 * You don't normally need to call this. It is called automatically when
1029 * needed when you start adding data to the table.
1032 function start_output() {
1033 $this->started_output
= true;
1034 if ($this->exportclass
!==null) {
1035 $this->exportclass
->start_table($this->sheettitle
);
1036 $this->exportclass
->output_headers($this->headers
);
1038 $this->start_html();
1039 $this->print_headers();
1040 echo html_writer
::start_tag('tbody');
1045 * This function is not part of the public api.
1047 function print_row($row, $classname = '') {
1048 echo $this->get_row_html($row, $classname);
1052 * Generate html code for the passed row.
1054 * @param array $row Row data.
1055 * @param string $classname classes to add.
1057 * @return string $html html code for the row passed.
1059 public function get_row_html($row, $classname = '') {
1060 static $suppress_lastrow = NULL;
1061 $rowclasses = array();
1064 $rowclasses[] = $classname;
1067 $rowid = $this->uniqueid
. '_r' . $this->currentrow
;
1070 $html .= html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1072 // If we have a separator, print it
1073 if ($row === NULL) {
1074 $colcount = count($this->columns
);
1075 $html .= html_writer
::tag('td', html_writer
::tag('div', '',
1076 array('class' => 'tabledivider')), array('colspan' => $colcount));
1079 $colbyindex = array_flip($this->columns
);
1080 foreach ($row as $index => $data) {
1081 $column = $colbyindex[$index];
1084 'class' => "cell c{$index}" . $this->column_class
[$column],
1085 'id' => "{$rowid}_c{$index}",
1086 'style' => $this->make_styles_string($this->column_style
[$column]),
1090 if ($this->headercolumn
&& $column == $this->headercolumn
) {
1092 $attributes['scope'] = 'row';
1095 if (empty($this->prefs
['collapse'][$column])) {
1096 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1097 $content = ' ';
1102 $content = ' ';
1105 $html .= html_writer
::tag($celltype, $content, $attributes);
1109 $html .= html_writer
::end_tag('tr');
1111 $suppress_enabled = array_sum($this->column_suppress
);
1112 if ($suppress_enabled) {
1113 $suppress_lastrow = $row;
1115 $this->currentrow++
;
1120 * This function is not part of the public api.
1122 function finish_html() {
1123 global $OUTPUT, $PAGE;
1125 if (!$this->started_output
) {
1126 //no data has been added to the table.
1127 $this->print_nothing_to_display();
1130 // Print empty rows to fill the table to the current pagesize.
1131 // This is done so the header aria-controls attributes do not point to
1132 // non existant elements.
1133 $emptyrow = array_fill(0, count($this->columns
), '');
1134 while ($this->currentrow
< $this->pagesize
) {
1135 $this->print_row($emptyrow, 'emptyrow');
1138 echo html_writer
::end_tag('tbody');
1139 echo html_writer
::end_tag('table');
1140 echo html_writer
::end_tag('div');
1141 $this->wrap_html_finish();
1144 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1145 echo $this->download_buttons();
1148 if($this->use_pages
) {
1149 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1150 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1151 echo $OUTPUT->render($pagingbar);
1154 // Render the dynamic table footer.
1155 echo $this->get_dynamic_table_html_end();
1160 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1161 * used by {@link print_headers()}.
1162 * @param string $column the column name, index into various names.
1163 * @param int $index numerical index of the column.
1164 * @return string HTML fragment.
1166 protected function show_hide_link($column, $index) {
1168 // Some headers contain <br /> tags, do not include in title, hence the
1172 for ($i = 0; $i < $this->pagesize
; $i++
) {
1173 $ariacontrols .= $this->uniqueid
. '_r' . $i . '_c' . $index . ' ';
1176 $ariacontrols = trim($ariacontrols);
1178 if (!empty($this->prefs
['collapse'][$column])) {
1179 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index]),
1180 'aria-expanded' => 'false',
1181 'aria-controls' => $ariacontrols,
1182 'data-action' => 'show',
1183 'data-column' => $column);
1184 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1185 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1187 } else if ($this->headers
[$index] !== NULL) {
1188 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index]),
1189 'aria-expanded' => 'true',
1190 'aria-controls' => $ariacontrols,
1191 'data-action' => 'hide',
1192 'data-column' => $column);
1193 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1194 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1199 * This function is not part of the public api.
1201 function print_headers() {
1202 global $CFG, $OUTPUT;
1204 // Set the primary sort column/order where possible, so that sort links/icons are correct.
1206 'sortby' => $primarysortcolumn,
1207 'sortorder' => $primarysortorder,
1208 ] = $this->get_primary_sort_order();
1210 echo html_writer
::start_tag('thead');
1211 echo html_writer
::start_tag('tr');
1212 foreach ($this->columns
as $column => $index) {
1215 if ($this->is_collapsible
) {
1216 $icon_hide = $this->show_hide_link($column, $index);
1221 // Check the full name display for sortable fields.
1222 if (has_capability('moodle/site:viewfullnames', $this->get_context())) {
1223 $nameformat = $CFG->alternativefullnameformat
;
1225 $nameformat = $CFG->fullnamedisplay
;
1228 if ($nameformat == 'language') {
1229 $nameformat = get_string('fullnamedisplay');
1232 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1234 if (!empty($requirednames)) {
1235 if ($this->is_sortable($column)) {
1236 // Done this way for the possibility of more than two sortable full name display fields.
1237 $this->headers
[$index] = '';
1238 foreach ($requirednames as $name) {
1239 $sortname = $this->sort_link(get_string($name),
1240 $name, $primarysortcolumn === $name, $primarysortorder);
1241 $this->headers
[$index] .= $sortname . ' / ';
1244 if (isset($this->helpforheaders
[$index])) {
1245 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1247 $this->headers
[$index] = substr($this->headers
[$index], 0, -3). $helpicon;
1253 // do nothing, do not display sortable links
1257 if ($this->is_sortable($column)) {
1259 if (isset($this->helpforheaders
[$index])) {
1260 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1262 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1263 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1267 $attributes = array(
1268 'class' => 'header c' . $index . $this->column_class
[$column],
1271 if ($this->headers
[$index] === NULL) {
1272 $content = ' ';
1273 } else if (!empty($this->prefs
['collapse'][$column])) {
1274 $content = $icon_hide;
1276 if (is_array($this->column_style
[$column])) {
1277 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1280 if (isset($this->helpforheaders
[$index]) && !$this->is_sortable($column)) {
1281 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1283 $content = $this->headers
[$index] . $helpicon . html_writer
::tag('div',
1284 $icon_hide, array('class' => 'commands'));
1286 echo html_writer
::tag('th', $content, $attributes);
1289 echo html_writer
::end_tag('tr');
1290 echo html_writer
::end_tag('thead');
1294 * Calculate the preferences for sort order based on user-supplied values and get params.
1296 protected function set_sorting_preferences(): void
{
1297 $sortdata = $this->sortdata
;
1299 if ($sortdata === null) {
1300 $sortdata = $this->prefs
['sortby'];
1302 $sortorder = optional_param($this->request
[TABLE_VAR_DIR
], $this->sort_default_order
, PARAM_INT
);
1303 $sortby = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
);
1305 if (array_key_exists($sortby, $sortdata)) {
1306 // This key already exists somewhere. Change its sortorder and bring it to the top.
1307 unset($sortdata[$sortby]);
1309 $sortdata = array_merge([$sortby => $sortorder], $sortdata);
1312 $usernamefields = get_all_user_name_fields();
1313 $sortdata = array_filter($sortdata, function($sortby) use ($usernamefields) {
1314 $isvalidsort = $sortby && $this->is_sortable($sortby);
1315 $isvalidsort = $isvalidsort && empty($this->prefs
['collapse'][$sortby]);
1316 $isrealcolumn = isset($this->columns
[$sortby]);
1317 $isfullnamefield = isset($this->columns
['fullname']) && in_array($sortby, $usernamefields);
1319 return $isvalidsort && ($isrealcolumn ||
$isfullnamefield);
1320 }, ARRAY_FILTER_USE_KEY
);
1322 // Finally, make sure that no more than $this->maxsortkeys are present into the array.
1323 $sortdata = array_slice($sortdata, 0, $this->maxsortkeys
);
1325 // If a default order is defined and it is not in the current list of order by columns, add it at the end.
1326 // This prevents results from being returned in a random order if the only order by column contains equal values.
1327 if (!empty($this->sort_default_column
) && !array_key_exists($this->sort_default_column
, $sortdata)) {
1328 $sortdata = array_merge($sortdata, [$this->sort_default_column
=> $this->sort_default_order
]);
1331 // Apply the sortdata to the preference.
1332 $this->prefs
['sortby'] = $sortdata;
1336 * Fill in the preferences for the initials bar.
1338 protected function set_initials_preferences(): void
{
1339 $ifirst = $this->ifirst
;
1340 $ilast = $this->ilast
;
1342 if ($ifirst === null) {
1343 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
1346 if ($ilast === null) {
1347 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
1350 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
1351 $this->prefs
['i_first'] = $ifirst;
1354 if (!is_null($ilast) && ($ilast === '' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
1355 $this->prefs
['i_last'] = $ilast;
1361 * Set hide and show preferences.
1363 protected function set_hide_show_preferences(): void
{
1365 if ($this->hiddencolumns
!== null) {
1366 $this->prefs
['collapse'] = array_fill_keys(array_filter($this->hiddencolumns
, function($column) {
1367 return array_key_exists($column, $this->columns
);
1370 if ($column = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) {
1371 if (isset($this->columns
[$column])) {
1372 $this->prefs
['collapse'][$column] = true;
1377 if ($column = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) {
1378 unset($this->prefs
['collapse'][$column]);
1381 foreach (array_keys($this->prefs
['collapse']) as $column) {
1382 if (array_key_exists($column, $this->prefs
['sortby'])) {
1383 unset($this->prefs
['sortby'][$column]);
1389 * Set the list of hidden columns.
1391 * @param array $columns The list of hidden columns.
1393 public function set_hidden_columns(array $columns): void
{
1394 $this->hiddencolumns
= $columns;
1398 * Initialise table preferences.
1400 protected function initialise_table_preferences(): void
{
1403 // Load any existing user preferences.
1404 if ($this->persistent
) {
1405 $this->prefs
= json_decode(get_user_preferences('flextable_' . $this->uniqueid
), true);
1406 $oldprefs = $this->prefs
;
1407 } else if (isset($SESSION->flextable
[$this->uniqueid
])) {
1408 $this->prefs
= $SESSION->flextable
[$this->uniqueid
];
1409 $oldprefs = $this->prefs
;
1412 // Set up default preferences if needed.
1413 if (!$this->prefs ||
$this->is_resetting_preferences()) {
1419 'textsort' => $this->column_textsort
,
1423 if (!isset($oldprefs)) {
1424 $oldprefs = $this->prefs
;
1427 // Save user preferences if they have changed.
1428 if ($this->is_resetting_preferences()) {
1429 $this->sortdata
= null;
1430 $this->ifirst
= null;
1431 $this->ilast
= null;
1434 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
1435 isset($this->columns
[$showcol])) {
1436 $this->prefs
['collapse'][$showcol] = false;
1437 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
1438 isset($this->columns
[$hidecol])) {
1439 $this->prefs
['collapse'][$hidecol] = true;
1440 if (array_key_exists($hidecol, $this->prefs
['sortby'])) {
1441 unset($this->prefs
['sortby'][$hidecol]);
1445 $this->set_hide_show_preferences();
1446 $this->set_sorting_preferences();
1447 $this->set_initials_preferences();
1449 // Now, reduce the width of collapsed columns and remove the width from columns that should be expanded.
1450 foreach (array_keys($this->columns
) as $column) {
1451 if (!empty($this->prefs
['collapse'][$column])) {
1452 $this->column_style
[$column]['width'] = '10px';
1454 unset($this->column_style
[$column]['width']);
1458 if (empty($this->baseurl
)) {
1459 debugging('You should set baseurl when using flexible_table.');
1461 $this->baseurl
= $PAGE->url
;
1464 if ($this->currpage
== null) {
1465 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
1468 $this->save_preferences($oldprefs);
1474 * @param array $oldprefs Old preferences to compare against.
1476 protected function save_preferences($oldprefs): void
{
1479 if ($this->prefs
!= $oldprefs) {
1480 if ($this->persistent
) {
1481 set_user_preference('flextable_' . $this->uniqueid
, json_encode($this->prefs
));
1483 $SESSION->flextable
[$this->uniqueid
] = $this->prefs
;
1490 * Set the preferred table sorting attributes.
1492 * @param string $sortby The field to sort by.
1493 * @param int $sortorder The sort order.
1495 public function set_sortdata(array $sortdata): void
{
1496 $this->sortdata
= [];
1497 foreach ($sortdata as $sortitem) {
1498 if (!array_key_exists($sortitem['sortby'], $this->sortdata
)) {
1499 $this->sortdata
[$sortitem['sortby']] = (int) $sortitem['sortorder'];
1505 * Set the preferred first name initial in an initials bar.
1507 * @param string $initial The character to set
1509 public function set_first_initial(string $initial): void
{
1510 $this->ifirst
= $initial;
1514 * Set the preferred last name initial in an initials bar.
1516 * @param string $initial The character to set
1518 public function set_last_initial(string $initial): void
{
1519 $this->ilast
= $initial;
1523 * Set the page number.
1525 * @param int $pagenumber The page number.
1527 public function set_page_number(int $pagenumber): void
{
1528 $this->currpage
= $pagenumber - 1;
1532 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1533 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1534 * @param int $order SORT_ASC or SORT_DESC
1535 * @return string HTML fragment.
1537 protected function sort_icon($isprimary, $order) {
1544 if ($order == SORT_ASC
) {
1545 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1547 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1552 * Generate the correct tool tip for changing the sort order. This is a
1553 * helper method used by {@link sort_link()}.
1554 * @param bool $isprimary whether the is column is the current primary sort column.
1555 * @param int $order SORT_ASC or SORT_DESC
1556 * @return string the correct title.
1558 protected function sort_order_name($isprimary, $order) {
1559 if ($isprimary && $order != SORT_ASC
) {
1560 return get_string('desc');
1562 return get_string('asc');
1567 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1568 * @param string $text the text for the link.
1569 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1570 * @param bool $isprimary whether the is column is the current primary sort column.
1571 * @param int $order SORT_ASC or SORT_DESC
1572 * @return string HTML fragment.
1574 protected function sort_link($text, $column, $isprimary, $order) {
1575 // If we are already sorting by this column, switch direction.
1576 if (array_key_exists($column, $this->prefs
['sortby'])) {
1577 $sortorder = $this->prefs
['sortby'][$column] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
1579 $sortorder = $order;
1583 $this->request
[TABLE_VAR_SORT
] => $column,
1584 $this->request
[TABLE_VAR_DIR
] => $sortorder,
1587 return html_writer
::link($this->baseurl
->out(false, $params),
1588 $text . get_accesshide(get_string('sortby') . ' ' .
1589 $text . ' ' . $this->sort_order_name($isprimary, $order)),
1591 'data-sortable' => $this->is_sortable($column),
1592 'data-sortby' => $column,
1593 'data-sortorder' => $sortorder,
1594 ]) . ' ' . $this->sort_icon($isprimary, $order);
1598 * Return primary sorting column/order, either the first preferred "sortby" value or defaults defined for the table
1602 protected function get_primary_sort_order(): array {
1603 if (reset($this->prefs
['sortby'])) {
1604 return $this->get_sort_order();
1608 'sortby' => $this->sort_default_column
,
1609 'sortorder' => $this->sort_default_order
,
1614 * Return sorting attributes values.
1618 protected function get_sort_order(): array {
1619 $sortbys = $this->prefs
['sortby'];
1620 $sortby = key($sortbys);
1623 'sortby' => $sortby,
1624 'sortorder' => $sortbys[$sortby],
1629 * Get dynamic class component.
1633 protected function get_component() {
1634 $tableclass = explode("\\", get_class($this));
1635 return reset($tableclass);
1639 * Get dynamic class handler.
1643 protected function get_handler() {
1644 $tableclass = explode("\\", get_class($this));
1645 return end($tableclass);
1649 * Get the dynamic table start wrapper.
1650 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1654 protected function get_dynamic_table_html_start(): string {
1655 if (is_a($this, \core_table\dynamic
::class)) {
1656 $sortdata = array_map(function($sortby, $sortorder) {
1658 'sortby' => $sortby,
1659 'sortorder' => $sortorder,
1661 }, array_keys($this->prefs
['sortby']), array_values($this->prefs
['sortby']));;
1663 return html_writer
::start_tag('div', [
1664 'class' => 'table-dynamic position-relative',
1665 'data-region' => 'core_table/dynamic',
1666 'data-table-handler' => $this->get_handler(),
1667 'data-table-component' => $this->get_component(),
1668 'data-table-uniqueid' => $this->uniqueid
,
1669 'data-table-filters' => json_encode($this->get_filterset()),
1670 'data-table-sort-data' => json_encode($sortdata),
1671 'data-table-first-initial' => $this->prefs
['i_first'],
1672 'data-table-last-initial' => $this->prefs
['i_last'],
1673 'data-table-page-number' => $this->currpage +
1,
1674 'data-table-page-size' => $this->pagesize
,
1675 'data-table-hidden-columns' => json_encode(array_keys($this->prefs
['collapse'])),
1676 'data-table-total-rows' => $this->totalrows
,
1684 * Get the dynamic table end wrapper.
1685 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1689 protected function get_dynamic_table_html_end(): string {
1692 if (is_a($this, \core_table\dynamic
::class)) {
1693 $PAGE->requires
->js_call_amd('core_table/dynamic', 'init');
1694 return html_writer
::end_tag('div');
1701 * This function is not part of the public api.
1703 function start_html() {
1706 // Render the dynamic table header.
1707 echo $this->get_dynamic_table_html_start();
1709 // Render button to allow user to reset table preferences.
1710 echo $this->render_reset_button();
1712 // Do we need to print initial bars?
1713 $this->print_initials_bar();
1716 if ($this->use_pages
) {
1717 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1718 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1719 echo $OUTPUT->render($pagingbar);
1722 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1723 echo $this->download_buttons();
1726 $this->wrap_html_start();
1727 // Start of main data table
1729 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1730 echo html_writer
::start_tag('table', $this->attributes
);
1735 * This function is not part of the public api.
1736 * @param array $styles CSS-property => value
1737 * @return string values suitably to go in a style="" attribute in HTML.
1739 function make_styles_string($styles) {
1740 if (empty($styles)) {
1745 foreach($styles as $property => $value) {
1746 $string .= $property . ':' . $value . ';';
1752 * Generate the HTML for the table preferences reset button.
1754 * @return string HTML fragment, empty string if no need to reset
1756 protected function render_reset_button() {
1758 if (!$this->can_be_reset()) {
1762 $url = $this->baseurl
->out(false, array($this->request
[TABLE_VAR_RESET
] => 1));
1764 $html = html_writer
::start_div('resettable mdl-right');
1765 $html .= html_writer
::link($url, get_string('resettable'));
1766 $html .= html_writer
::end_div();
1772 * Are there some table preferences that can be reset?
1774 * If true, then the "reset table preferences" widget should be displayed.
1778 protected function can_be_reset() {
1779 // Loop through preferences and make sure they are empty or set to the default value.
1780 foreach ($this->prefs
as $prefname => $prefval) {
1781 if ($prefname === 'sortby' and !empty($this->sort_default_column
)) {
1782 // Check if the actual sorting differs from the default one.
1783 if (empty($prefval) or $prefval !== array($this->sort_default_column
=> $this->sort_default_order
)) {
1787 } else if ($prefname === 'collapse' and !empty($prefval)) {
1788 // Check if there are some collapsed columns (all are expanded by default).
1789 foreach ($prefval as $columnname => $iscollapsed) {
1795 } else if (!empty($prefval)) {
1796 // For all other cases, we just check if some preference is set.
1805 * Get the context for the table.
1807 * Note: This function _must_ be overridden by dynamic tables to ensure that the context is correctly determined
1808 * from the filterset parameters.
1812 public function get_context(): context
{
1815 if (is_a($this, \core_table\dynamic
::class)) {
1816 throw new coding_exception('The get_context function must be defined for a dynamic table');
1819 return $PAGE->context
;
1823 * Set the filterset in the table class.
1825 * The use of filtersets is a requirement for dynamic tables, but can be used by other tables too if desired.
1827 * @param filterset $filterset The filterset object to get filters and table parameters from
1829 public function set_filterset(filterset
$filterset): void
{
1830 $this->filterset
= $filterset;
1832 $this->guess_base_url();
1836 * Get the currently defined filterset.
1840 public function get_filterset(): ?filterset
{
1841 return $this->filterset
;
1845 * Attempt to guess the base URL.
1847 public function guess_base_url(): void
{
1848 if (is_a($this, \core_table\dynamic
::class)) {
1849 throw new coding_exception('The guess_base_url function must be defined for a dynamic table');
1856 * @package moodlecore
1857 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1860 class table_sql
extends flexible_table
{
1862 public $countsql = NULL;
1863 public $countparams = NULL;
1865 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1869 * @var array|\Traversable Data fetched from the db.
1871 public $rawdata = NULL;
1874 * @var bool Overriding default for this.
1876 public $is_sortable = true;
1878 * @var bool Overriding default for this.
1880 public $is_collapsible = true;
1883 * @param string $uniqueid a string identifying this table.Used as a key in
1886 function __construct($uniqueid) {
1887 parent
::__construct($uniqueid);
1888 // some sensible defaults
1889 $this->set_attribute('class', 'generaltable generalbox');
1893 * Take the data returned from the db_query and go through all the rows
1894 * processing each col using either col_{columnname} method or other_cols
1895 * method or if other_cols returns NULL then put the data straight into the
1898 * After calling this function, don't forget to call close_recordset.
1900 public function build_table() {
1902 if ($this->rawdata
instanceof \Traversable
&& !$this->rawdata
->valid()) {
1905 if (!$this->rawdata
) {
1909 foreach ($this->rawdata
as $row) {
1910 $formattedrow = $this->format_row($row);
1911 $this->add_data_keyed($formattedrow,
1912 $this->get_row_class($row));
1917 * Closes recordset (for use after building the table).
1919 public function close_recordset() {
1920 if ($this->rawdata
&& ($this->rawdata
instanceof \core\dml\recordset_walk ||
1921 $this->rawdata
instanceof moodle_recordset
)) {
1922 $this->rawdata
->close();
1923 $this->rawdata
= null;
1928 * Get any extra classes names to add to this row in the HTML.
1929 * @param $row array the data for this row.
1930 * @return string added to the class="" attribute of the tr.
1932 function get_row_class($row) {
1937 * This is only needed if you want to use different sql to count rows.
1938 * Used for example when perhaps all db JOINS are not needed when counting
1939 * records. You don't need to call this function the count_sql
1940 * will be generated automatically.
1942 * We need to count rows returned by the db seperately to the query itself
1943 * as we need to know how many pages of data we have to display.
1945 function set_count_sql($sql, array $params = NULL) {
1946 $this->countsql
= $sql;
1947 $this->countparams
= $params;
1951 * Set the sql to query the db. Query will be :
1952 * SELECT $fields FROM $from WHERE $where
1953 * Of course you can use sub-queries, JOINS etc. by putting them in the
1954 * appropriate clause of the query.
1956 function set_sql($fields, $from, $where, array $params = array()) {
1957 $this->sql
= new stdClass();
1958 $this->sql
->fields
= $fields;
1959 $this->sql
->from
= $from;
1960 $this->sql
->where
= $where;
1961 $this->sql
->params
= $params;
1965 * Query the db. Store results in the table object for use by build_table.
1967 * @param int $pagesize size of page for paginated displayed table.
1968 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1969 * will only be used if there is a fullname column defined for the table.
1971 function query_db($pagesize, $useinitialsbar=true) {
1973 if (!$this->is_downloading()) {
1974 if ($this->countsql
=== NULL) {
1975 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1976 $this->countparams
= $this->sql
->params
;
1978 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1979 if ($useinitialsbar && !$this->is_downloading()) {
1980 $this->initialbars(true);
1983 list($wsql, $wparams) = $this->get_sql_where();
1985 $this->countsql
.= ' AND '.$wsql;
1986 $this->countparams
= array_merge($this->countparams
, $wparams);
1988 $this->sql
->where
.= ' AND '.$wsql;
1989 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1991 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1993 $total = $grandtotal;
1996 $this->pagesize($pagesize, $total);
1999 // Fetch the attempts
2000 $sort = $this->get_sql_sort();
2002 $sort = "ORDER BY $sort";
2005 {$this->sql->fields}
2006 FROM {$this->sql->from}
2007 WHERE {$this->sql->where}
2010 if (!$this->is_downloading()) {
2011 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
2013 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
2018 * Convenience method to call a number of methods for you to display the
2021 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
2023 if (!$this->columns
) {
2024 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
2025 $this->sql
->params
, IGNORE_MULTIPLE
);
2026 //if columns is not set then define columns as the keys of the rows returned
2028 $this->define_columns(array_keys((array)$onerow));
2029 $this->define_headers(array_keys((array)$onerow));
2031 $this->pagesize
= $pagesize;
2033 $this->query_db($pagesize, $useinitialsbar);
2034 $this->build_table();
2035 $this->close_recordset();
2036 $this->finish_output();
2042 * @package moodlecore
2043 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2044 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2046 class table_default_export_format_parent
{
2048 * @var flexible_table or child class reference pointing to table class
2049 * object from which to export data.
2054 * @var bool output started. Keeps track of whether any output has been
2057 var $documentstarted = false;
2062 * @param flexible_table $table
2064 public function __construct(&$table) {
2065 $this->table
=& $table;
2069 * Old syntax of class constructor. Deprecated in PHP7.
2071 * @deprecated since Moodle 3.1
2073 public function table_default_export_format_parent(&$table) {
2074 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2075 self
::__construct($table);
2078 function set_table(&$table) {
2079 $this->table
=& $table;
2082 function add_data($row) {
2086 function add_seperator() {
2090 function document_started() {
2091 return $this->documentstarted
;
2094 * Given text in a variety of format codings, this function returns
2095 * the text as safe HTML or as plain text dependent on what is appropriate
2096 * for the download format. The default removes all tags.
2098 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
2099 //use some whitespace to indicate where there was some line spacing.
2100 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
2101 return strip_tags($text);
2106 * Dataformat exporter
2109 * @subpackage tablelib
2110 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
2111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2113 class table_dataformat_export_format
extends table_default_export_format_parent
{
2115 /** @var \core\dataformat\base $dataformat */
2116 protected $dataformat;
2119 protected $rownum = 0;
2121 /** @var $columns */
2127 * @param string $table An sql table
2128 * @param string $dataformat type of dataformat for export
2130 public function __construct(&$table, $dataformat) {
2131 parent
::__construct($table);
2133 if (ob_get_length()) {
2134 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
2137 $classname = 'dataformat_' . $dataformat . '\writer';
2138 if (!class_exists($classname)) {
2139 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
2141 $this->dataformat
= new $classname;
2143 // The dataformat export time to first byte could take a while to generate...
2146 // Close the session so that the users other tabs in the same session are not blocked.
2147 \core\session\manager
::write_close();
2151 * Whether the current dataformat supports export of HTML
2155 public function supports_html(): bool {
2156 return $this->dataformat
->supports_html();
2162 * @param string $filename
2163 * @param string $sheettitle
2165 public function start_document($filename, $sheettitle) {
2166 $this->documentstarted
= true;
2167 $this->dataformat
->set_filename($filename);
2168 $this->dataformat
->send_http_headers();
2169 $this->dataformat
->set_sheettitle($sheettitle);
2170 $this->dataformat
->start_output();
2176 * @param string $sheettitle optional spreadsheet worksheet title
2178 public function start_table($sheettitle) {
2179 $this->dataformat
->set_sheettitle($sheettitle);
2185 * @param array $headers
2187 public function output_headers($headers) {
2188 $this->columns
= $headers;
2189 if (method_exists($this->dataformat
, 'write_header')) {
2190 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
2191 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
2192 $this->dataformat
->write_header($headers);
2194 $this->dataformat
->start_sheet($headers);
2201 * @param array $row One record of data
2203 public function add_data($row) {
2204 $this->dataformat
->write_record($row, $this->rownum++
);
2211 public function finish_table() {
2212 if (method_exists($this->dataformat
, 'write_footer')) {
2213 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
2214 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
2215 $this->dataformat
->write_footer($this->columns
);
2217 $this->dataformat
->close_sheet($this->columns
);
2224 public function finish_document() {
2225 $this->dataformat
->close_output();