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) {
844 if (isset($row->$column) && ($column === 'email' ||
$column === 'idnumber') &&
845 (!$this->is_downloading() ||
$this->export_class_instance()->supports_html())) {
846 // Columns email and idnumber may potentially contain malicious characters, escape them by default.
847 // This function will not be executed if the child class implements col_email() or col_idnumber().
848 return s($row->$column);
854 * Used from col_* functions when text is to be displayed. Does the
855 * right thing - either converts text to html or strips any html tags
856 * depending on if we are downloading and what is the download type. Params
857 * are the same as format_text function in weblib.php but some default
858 * options are changed.
860 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
861 if (!$this->is_downloading()) {
862 if (is_null($options)) {
863 $options = new stdClass
;
865 //some sensible defaults
866 if (!isset($options->para
)) {
867 $options->para
= false;
869 if (!isset($options->newlines
)) {
870 $options->newlines
= false;
872 if (!isset($options->smiley
)) {
873 $options->smiley
= false;
875 if (!isset($options->filter
)) {
876 $options->filter
= false;
878 return format_text($text, $format, $options);
880 $eci = $this->export_class_instance();
881 return $eci->format_text($text, $format, $options, $courseid);
885 * This method is deprecated although the old api is still supported.
886 * @deprecated 1.9.2 - Jun 2, 2008
888 function print_html() {
892 $this->finish_html();
896 * This function is not part of the public api.
897 * @return string initial of first name we are currently filtering by
899 function get_initial_first() {
900 if (!$this->use_initials
) {
904 return $this->prefs
['i_first'];
908 * This function is not part of the public api.
909 * @return string initial of last name we are currently filtering by
911 function get_initial_last() {
912 if (!$this->use_initials
) {
916 return $this->prefs
['i_last'];
920 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
921 * @param array $alpha of letters in the alphabet.
922 * @param string $current the currently selected letter.
923 * @param string $class class name to add to this initial bar.
924 * @param string $title the name to put in front of this initial bar.
925 * @param string $urlvar URL parameter name for this initial.
927 * @deprecated since Moodle 3.3
929 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
931 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
932 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER
);
934 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
937 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
939 echo html_writer
::tag('strong', get_string('all'));
942 foreach ($alpha as $letter) {
943 if ($letter === $current) {
944 echo html_writer
::tag('strong', $letter);
946 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
950 echo html_writer
::end_tag('div');
954 * This function is not part of the public api.
956 function print_initials_bar() {
959 $ifirst = $this->get_initial_first();
960 $ilast = $this->get_initial_last();
961 if (is_null($ifirst)) {
964 if (is_null($ilast)) {
968 if ((!empty($ifirst) ||
!empty($ilast) ||
$this->use_initials
)
969 && isset($this->columns
['fullname'])) {
970 $prefixfirst = $this->request
[TABLE_VAR_IFIRST
];
971 $prefixlast = $this->request
[TABLE_VAR_ILAST
];
972 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl
);
973 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl
);
979 * This function is not part of the public api.
981 function print_nothing_to_display() {
984 // Render the dynamic table header.
985 echo $this->get_dynamic_table_html_start();
987 // Render button to allow user to reset table preferences.
988 echo $this->render_reset_button();
990 $this->print_initials_bar();
992 echo $OUTPUT->heading(get_string('nothingtodisplay'));
994 // Render the dynamic table footer.
995 echo $this->get_dynamic_table_html_end();
999 * This function is not part of the public api.
1001 function get_row_from_keyed($rowwithkeys) {
1002 if (is_object($rowwithkeys)) {
1003 $rowwithkeys = (array)$rowwithkeys;
1006 foreach (array_keys($this->columns
) as $column) {
1007 if (isset($rowwithkeys[$column])) {
1008 $row [] = $rowwithkeys[$column];
1017 * Get the html for the download buttons
1019 * Usually only use internally
1021 public function download_buttons() {
1024 if ($this->is_downloadable() && !$this->is_downloading()) {
1025 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1026 $this->baseurl
->out_omit_querystring(), 'download', $this->baseurl
->params());
1033 * This function is not part of the public api.
1034 * You don't normally need to call this. It is called automatically when
1035 * needed when you start adding data to the table.
1038 function start_output() {
1039 $this->started_output
= true;
1040 if ($this->exportclass
!==null) {
1041 $this->exportclass
->start_table($this->sheettitle
);
1042 $this->exportclass
->output_headers($this->headers
);
1044 $this->start_html();
1045 $this->print_headers();
1046 echo html_writer
::start_tag('tbody');
1051 * This function is not part of the public api.
1053 function print_row($row, $classname = '') {
1054 echo $this->get_row_html($row, $classname);
1058 * Generate html code for the passed row.
1060 * @param array $row Row data.
1061 * @param string $classname classes to add.
1063 * @return string $html html code for the row passed.
1065 public function get_row_html($row, $classname = '') {
1066 static $suppress_lastrow = NULL;
1067 $rowclasses = array();
1070 $rowclasses[] = $classname;
1073 $rowid = $this->uniqueid
. '_r' . $this->currentrow
;
1076 $html .= html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1078 // If we have a separator, print it
1079 if ($row === NULL) {
1080 $colcount = count($this->columns
);
1081 $html .= html_writer
::tag('td', html_writer
::tag('div', '',
1082 array('class' => 'tabledivider')), array('colspan' => $colcount));
1085 $colbyindex = array_flip($this->columns
);
1086 foreach ($row as $index => $data) {
1087 $column = $colbyindex[$index];
1090 'class' => "cell c{$index}" . $this->column_class
[$column],
1091 'id' => "{$rowid}_c{$index}",
1092 'style' => $this->make_styles_string($this->column_style
[$column]),
1096 if ($this->headercolumn
&& $column == $this->headercolumn
) {
1098 $attributes['scope'] = 'row';
1101 if (empty($this->prefs
['collapse'][$column])) {
1102 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1103 $content = ' ';
1108 $content = ' ';
1111 $html .= html_writer
::tag($celltype, $content, $attributes);
1115 $html .= html_writer
::end_tag('tr');
1117 $suppress_enabled = array_sum($this->column_suppress
);
1118 if ($suppress_enabled) {
1119 $suppress_lastrow = $row;
1121 $this->currentrow++
;
1126 * This function is not part of the public api.
1128 function finish_html() {
1129 global $OUTPUT, $PAGE;
1131 if (!$this->started_output
) {
1132 //no data has been added to the table.
1133 $this->print_nothing_to_display();
1136 // Print empty rows to fill the table to the current pagesize.
1137 // This is done so the header aria-controls attributes do not point to
1138 // non existant elements.
1139 $emptyrow = array_fill(0, count($this->columns
), '');
1140 while ($this->currentrow
< $this->pagesize
) {
1141 $this->print_row($emptyrow, 'emptyrow');
1144 echo html_writer
::end_tag('tbody');
1145 echo html_writer
::end_tag('table');
1146 echo html_writer
::end_tag('div');
1147 $this->wrap_html_finish();
1150 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1151 echo $this->download_buttons();
1154 if($this->use_pages
) {
1155 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1156 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1157 echo $OUTPUT->render($pagingbar);
1160 // Render the dynamic table footer.
1161 echo $this->get_dynamic_table_html_end();
1166 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1167 * used by {@link print_headers()}.
1168 * @param string $column the column name, index into various names.
1169 * @param int $index numerical index of the column.
1170 * @return string HTML fragment.
1172 protected function show_hide_link($column, $index) {
1174 // Some headers contain <br /> tags, do not include in title, hence the
1178 for ($i = 0; $i < $this->pagesize
; $i++
) {
1179 $ariacontrols .= $this->uniqueid
. '_r' . $i . '_c' . $index . ' ';
1182 $ariacontrols = trim($ariacontrols);
1184 if (!empty($this->prefs
['collapse'][$column])) {
1185 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index]),
1186 'aria-expanded' => 'false',
1187 'aria-controls' => $ariacontrols,
1188 'data-action' => 'show',
1189 'data-column' => $column);
1190 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1191 $OUTPUT->pix_icon('t/switch_plus', null), $linkattributes);
1193 } else if ($this->headers
[$index] !== NULL) {
1194 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index]),
1195 'aria-expanded' => 'true',
1196 'aria-controls' => $ariacontrols,
1197 'data-action' => 'hide',
1198 'data-column' => $column);
1199 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1200 $OUTPUT->pix_icon('t/switch_minus', null), $linkattributes);
1205 * This function is not part of the public api.
1207 function print_headers() {
1208 global $CFG, $OUTPUT;
1210 // Set the primary sort column/order where possible, so that sort links/icons are correct.
1212 'sortby' => $primarysortcolumn,
1213 'sortorder' => $primarysortorder,
1214 ] = $this->get_primary_sort_order();
1216 echo html_writer
::start_tag('thead');
1217 echo html_writer
::start_tag('tr');
1218 foreach ($this->columns
as $column => $index) {
1221 if ($this->is_collapsible
) {
1222 $icon_hide = $this->show_hide_link($column, $index);
1227 // Check the full name display for sortable fields.
1228 if (has_capability('moodle/site:viewfullnames', $this->get_context())) {
1229 $nameformat = $CFG->alternativefullnameformat
;
1231 $nameformat = $CFG->fullnamedisplay
;
1234 if ($nameformat == 'language') {
1235 $nameformat = get_string('fullnamedisplay');
1238 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1240 if (!empty($requirednames)) {
1241 if ($this->is_sortable($column)) {
1242 // Done this way for the possibility of more than two sortable full name display fields.
1243 $this->headers
[$index] = '';
1244 foreach ($requirednames as $name) {
1245 $sortname = $this->sort_link(get_string($name),
1246 $name, $primarysortcolumn === $name, $primarysortorder);
1247 $this->headers
[$index] .= $sortname . ' / ';
1250 if (isset($this->helpforheaders
[$index])) {
1251 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1253 $this->headers
[$index] = substr($this->headers
[$index], 0, -3). $helpicon;
1259 // do nothing, do not display sortable links
1263 if ($this->is_sortable($column)) {
1265 if (isset($this->helpforheaders
[$index])) {
1266 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1268 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1269 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1273 $attributes = array(
1274 'class' => 'header c' . $index . $this->column_class
[$column],
1277 if ($this->headers
[$index] === NULL) {
1278 $content = ' ';
1279 } else if (!empty($this->prefs
['collapse'][$column])) {
1280 $content = $icon_hide;
1282 if (is_array($this->column_style
[$column])) {
1283 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1286 if (isset($this->helpforheaders
[$index]) && !$this->is_sortable($column)) {
1287 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1289 $content = $this->headers
[$index] . $helpicon . html_writer
::tag('div',
1290 $icon_hide, array('class' => 'commands'));
1292 echo html_writer
::tag('th', $content, $attributes);
1295 echo html_writer
::end_tag('tr');
1296 echo html_writer
::end_tag('thead');
1300 * Calculate the preferences for sort order based on user-supplied values and get params.
1302 protected function set_sorting_preferences(): void
{
1303 $sortdata = $this->sortdata
;
1305 if ($sortdata === null) {
1306 $sortdata = $this->prefs
['sortby'];
1308 $sortorder = optional_param($this->request
[TABLE_VAR_DIR
], $this->sort_default_order
, PARAM_INT
);
1309 $sortby = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
);
1311 if (array_key_exists($sortby, $sortdata)) {
1312 // This key already exists somewhere. Change its sortorder and bring it to the top.
1313 unset($sortdata[$sortby]);
1315 $sortdata = array_merge([$sortby => $sortorder], $sortdata);
1318 $usernamefields = get_all_user_name_fields();
1319 $sortdata = array_filter($sortdata, function($sortby) use ($usernamefields) {
1320 $isvalidsort = $sortby && $this->is_sortable($sortby);
1321 $isvalidsort = $isvalidsort && empty($this->prefs
['collapse'][$sortby]);
1322 $isrealcolumn = isset($this->columns
[$sortby]);
1323 $isfullnamefield = isset($this->columns
['fullname']) && in_array($sortby, $usernamefields);
1325 return $isvalidsort && ($isrealcolumn ||
$isfullnamefield);
1326 }, ARRAY_FILTER_USE_KEY
);
1328 // Finally, make sure that no more than $this->maxsortkeys are present into the array.
1329 $sortdata = array_slice($sortdata, 0, $this->maxsortkeys
);
1331 // If a default order is defined and it is not in the current list of order by columns, add it at the end.
1332 // This prevents results from being returned in a random order if the only order by column contains equal values.
1333 if (!empty($this->sort_default_column
) && !array_key_exists($this->sort_default_column
, $sortdata)) {
1334 $sortdata = array_merge($sortdata, [$this->sort_default_column
=> $this->sort_default_order
]);
1337 // Apply the sortdata to the preference.
1338 $this->prefs
['sortby'] = $sortdata;
1342 * Fill in the preferences for the initials bar.
1344 protected function set_initials_preferences(): void
{
1345 $ifirst = $this->ifirst
;
1346 $ilast = $this->ilast
;
1348 if ($ifirst === null) {
1349 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
1352 if ($ilast === null) {
1353 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
1356 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
1357 $this->prefs
['i_first'] = $ifirst;
1360 if (!is_null($ilast) && ($ilast === '' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
1361 $this->prefs
['i_last'] = $ilast;
1367 * Set hide and show preferences.
1369 protected function set_hide_show_preferences(): void
{
1371 if ($this->hiddencolumns
!== null) {
1372 $this->prefs
['collapse'] = array_fill_keys(array_filter($this->hiddencolumns
, function($column) {
1373 return array_key_exists($column, $this->columns
);
1376 if ($column = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) {
1377 if (isset($this->columns
[$column])) {
1378 $this->prefs
['collapse'][$column] = true;
1383 if ($column = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) {
1384 unset($this->prefs
['collapse'][$column]);
1387 foreach (array_keys($this->prefs
['collapse']) as $column) {
1388 if (array_key_exists($column, $this->prefs
['sortby'])) {
1389 unset($this->prefs
['sortby'][$column]);
1395 * Set the list of hidden columns.
1397 * @param array $columns The list of hidden columns.
1399 public function set_hidden_columns(array $columns): void
{
1400 $this->hiddencolumns
= $columns;
1404 * Initialise table preferences.
1406 protected function initialise_table_preferences(): void
{
1409 // Load any existing user preferences.
1410 if ($this->persistent
) {
1411 $this->prefs
= json_decode(get_user_preferences('flextable_' . $this->uniqueid
), true);
1412 $oldprefs = $this->prefs
;
1413 } else if (isset($SESSION->flextable
[$this->uniqueid
])) {
1414 $this->prefs
= $SESSION->flextable
[$this->uniqueid
];
1415 $oldprefs = $this->prefs
;
1418 // Set up default preferences if needed.
1419 if (!$this->prefs ||
$this->is_resetting_preferences()) {
1425 'textsort' => $this->column_textsort
,
1429 if (!isset($oldprefs)) {
1430 $oldprefs = $this->prefs
;
1433 // Save user preferences if they have changed.
1434 if ($this->is_resetting_preferences()) {
1435 $this->sortdata
= null;
1436 $this->ifirst
= null;
1437 $this->ilast
= null;
1440 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
1441 isset($this->columns
[$showcol])) {
1442 $this->prefs
['collapse'][$showcol] = false;
1443 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
1444 isset($this->columns
[$hidecol])) {
1445 $this->prefs
['collapse'][$hidecol] = true;
1446 if (array_key_exists($hidecol, $this->prefs
['sortby'])) {
1447 unset($this->prefs
['sortby'][$hidecol]);
1451 $this->set_hide_show_preferences();
1452 $this->set_sorting_preferences();
1453 $this->set_initials_preferences();
1455 // Now, reduce the width of collapsed columns and remove the width from columns that should be expanded.
1456 foreach (array_keys($this->columns
) as $column) {
1457 if (!empty($this->prefs
['collapse'][$column])) {
1458 $this->column_style
[$column]['width'] = '10px';
1460 unset($this->column_style
[$column]['width']);
1464 if (empty($this->baseurl
)) {
1465 debugging('You should set baseurl when using flexible_table.');
1467 $this->baseurl
= $PAGE->url
;
1470 if ($this->currpage
== null) {
1471 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
1474 $this->save_preferences($oldprefs);
1480 * @param array $oldprefs Old preferences to compare against.
1482 protected function save_preferences($oldprefs): void
{
1485 if ($this->prefs
!= $oldprefs) {
1486 if ($this->persistent
) {
1487 set_user_preference('flextable_' . $this->uniqueid
, json_encode($this->prefs
));
1489 $SESSION->flextable
[$this->uniqueid
] = $this->prefs
;
1496 * Set the preferred table sorting attributes.
1498 * @param string $sortby The field to sort by.
1499 * @param int $sortorder The sort order.
1501 public function set_sortdata(array $sortdata): void
{
1502 $this->sortdata
= [];
1503 foreach ($sortdata as $sortitem) {
1504 if (!array_key_exists($sortitem['sortby'], $this->sortdata
)) {
1505 $this->sortdata
[$sortitem['sortby']] = (int) $sortitem['sortorder'];
1511 * Set the preferred first name initial in an initials bar.
1513 * @param string $initial The character to set
1515 public function set_first_initial(string $initial): void
{
1516 $this->ifirst
= $initial;
1520 * Set the preferred last name initial in an initials bar.
1522 * @param string $initial The character to set
1524 public function set_last_initial(string $initial): void
{
1525 $this->ilast
= $initial;
1529 * Set the page number.
1531 * @param int $pagenumber The page number.
1533 public function set_page_number(int $pagenumber): void
{
1534 $this->currpage
= $pagenumber - 1;
1538 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1539 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1540 * @param int $order SORT_ASC or SORT_DESC
1541 * @return string HTML fragment.
1543 protected function sort_icon($isprimary, $order) {
1550 if ($order == SORT_ASC
) {
1551 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1553 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1558 * Generate the correct tool tip for changing the sort order. This is a
1559 * helper method used by {@link sort_link()}.
1560 * @param bool $isprimary whether the is column is the current primary sort column.
1561 * @param int $order SORT_ASC or SORT_DESC
1562 * @return string the correct title.
1564 protected function sort_order_name($isprimary, $order) {
1565 if ($isprimary && $order != SORT_ASC
) {
1566 return get_string('desc');
1568 return get_string('asc');
1573 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1574 * @param string $text the text for the link.
1575 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1576 * @param bool $isprimary whether the is column is the current primary sort column.
1577 * @param int $order SORT_ASC or SORT_DESC
1578 * @return string HTML fragment.
1580 protected function sort_link($text, $column, $isprimary, $order) {
1581 // If we are already sorting by this column, switch direction.
1582 if (array_key_exists($column, $this->prefs
['sortby'])) {
1583 $sortorder = $this->prefs
['sortby'][$column] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
1585 $sortorder = $order;
1589 $this->request
[TABLE_VAR_SORT
] => $column,
1590 $this->request
[TABLE_VAR_DIR
] => $sortorder,
1593 return html_writer
::link($this->baseurl
->out(false, $params),
1594 $text . get_accesshide(get_string('sortby') . ' ' .
1595 $text . ' ' . $this->sort_order_name($isprimary, $order)),
1597 'data-sortable' => $this->is_sortable($column),
1598 'data-sortby' => $column,
1599 'data-sortorder' => $sortorder,
1600 ]) . ' ' . $this->sort_icon($isprimary, $order);
1604 * Return primary sorting column/order, either the first preferred "sortby" value or defaults defined for the table
1608 protected function get_primary_sort_order(): array {
1609 if (reset($this->prefs
['sortby'])) {
1610 return $this->get_sort_order();
1614 'sortby' => $this->sort_default_column
,
1615 'sortorder' => $this->sort_default_order
,
1620 * Return sorting attributes values.
1624 protected function get_sort_order(): array {
1625 $sortbys = $this->prefs
['sortby'];
1626 $sortby = key($sortbys);
1629 'sortby' => $sortby,
1630 'sortorder' => $sortbys[$sortby],
1635 * Get dynamic class component.
1639 protected function get_component() {
1640 $tableclass = explode("\\", get_class($this));
1641 return reset($tableclass);
1645 * Get dynamic class handler.
1649 protected function get_handler() {
1650 $tableclass = explode("\\", get_class($this));
1651 return end($tableclass);
1655 * Get the dynamic table start wrapper.
1656 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1660 protected function get_dynamic_table_html_start(): string {
1661 if (is_a($this, \core_table\dynamic
::class)) {
1662 $sortdata = array_map(function($sortby, $sortorder) {
1664 'sortby' => $sortby,
1665 'sortorder' => $sortorder,
1667 }, array_keys($this->prefs
['sortby']), array_values($this->prefs
['sortby']));;
1669 return html_writer
::start_tag('div', [
1670 'class' => 'table-dynamic position-relative',
1671 'data-region' => 'core_table/dynamic',
1672 'data-table-handler' => $this->get_handler(),
1673 'data-table-component' => $this->get_component(),
1674 'data-table-uniqueid' => $this->uniqueid
,
1675 'data-table-filters' => json_encode($this->get_filterset()),
1676 'data-table-sort-data' => json_encode($sortdata),
1677 'data-table-first-initial' => $this->prefs
['i_first'],
1678 'data-table-last-initial' => $this->prefs
['i_last'],
1679 'data-table-page-number' => $this->currpage +
1,
1680 'data-table-page-size' => $this->pagesize
,
1681 'data-table-hidden-columns' => json_encode(array_keys($this->prefs
['collapse'])),
1682 'data-table-total-rows' => $this->totalrows
,
1690 * Get the dynamic table end wrapper.
1691 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1695 protected function get_dynamic_table_html_end(): string {
1698 if (is_a($this, \core_table\dynamic
::class)) {
1699 $PAGE->requires
->js_call_amd('core_table/dynamic', 'init');
1700 return html_writer
::end_tag('div');
1707 * This function is not part of the public api.
1709 function start_html() {
1712 // Render the dynamic table header.
1713 echo $this->get_dynamic_table_html_start();
1715 // Render button to allow user to reset table preferences.
1716 echo $this->render_reset_button();
1718 // Do we need to print initial bars?
1719 $this->print_initials_bar();
1722 if ($this->use_pages
) {
1723 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1724 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1725 echo $OUTPUT->render($pagingbar);
1728 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1729 echo $this->download_buttons();
1732 $this->wrap_html_start();
1733 // Start of main data table
1735 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1736 echo html_writer
::start_tag('table', $this->attributes
);
1741 * This function is not part of the public api.
1742 * @param array $styles CSS-property => value
1743 * @return string values suitably to go in a style="" attribute in HTML.
1745 function make_styles_string($styles) {
1746 if (empty($styles)) {
1751 foreach($styles as $property => $value) {
1752 $string .= $property . ':' . $value . ';';
1758 * Generate the HTML for the table preferences reset button.
1760 * @return string HTML fragment, empty string if no need to reset
1762 protected function render_reset_button() {
1764 if (!$this->can_be_reset()) {
1768 $url = $this->baseurl
->out(false, array($this->request
[TABLE_VAR_RESET
] => 1));
1770 $html = html_writer
::start_div('resettable mdl-right');
1771 $html .= html_writer
::link($url, get_string('resettable'));
1772 $html .= html_writer
::end_div();
1778 * Are there some table preferences that can be reset?
1780 * If true, then the "reset table preferences" widget should be displayed.
1784 protected function can_be_reset() {
1785 // Loop through preferences and make sure they are empty or set to the default value.
1786 foreach ($this->prefs
as $prefname => $prefval) {
1787 if ($prefname === 'sortby' and !empty($this->sort_default_column
)) {
1788 // Check if the actual sorting differs from the default one.
1789 if (empty($prefval) or $prefval !== array($this->sort_default_column
=> $this->sort_default_order
)) {
1793 } else if ($prefname === 'collapse' and !empty($prefval)) {
1794 // Check if there are some collapsed columns (all are expanded by default).
1795 foreach ($prefval as $columnname => $iscollapsed) {
1801 } else if (!empty($prefval)) {
1802 // For all other cases, we just check if some preference is set.
1811 * Get the context for the table.
1813 * Note: This function _must_ be overridden by dynamic tables to ensure that the context is correctly determined
1814 * from the filterset parameters.
1818 public function get_context(): context
{
1821 if (is_a($this, \core_table\dynamic
::class)) {
1822 throw new coding_exception('The get_context function must be defined for a dynamic table');
1825 return $PAGE->context
;
1829 * Set the filterset in the table class.
1831 * The use of filtersets is a requirement for dynamic tables, but can be used by other tables too if desired.
1833 * @param filterset $filterset The filterset object to get filters and table parameters from
1835 public function set_filterset(filterset
$filterset): void
{
1836 $this->filterset
= $filterset;
1838 $this->guess_base_url();
1842 * Get the currently defined filterset.
1846 public function get_filterset(): ?filterset
{
1847 return $this->filterset
;
1851 * Attempt to guess the base URL.
1853 public function guess_base_url(): void
{
1854 if (is_a($this, \core_table\dynamic
::class)) {
1855 throw new coding_exception('The guess_base_url function must be defined for a dynamic table');
1862 * @package moodlecore
1863 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1866 class table_sql
extends flexible_table
{
1868 public $countsql = NULL;
1869 public $countparams = NULL;
1871 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1875 * @var array|\Traversable Data fetched from the db.
1877 public $rawdata = NULL;
1880 * @var bool Overriding default for this.
1882 public $is_sortable = true;
1884 * @var bool Overriding default for this.
1886 public $is_collapsible = true;
1889 * @param string $uniqueid a string identifying this table.Used as a key in
1892 function __construct($uniqueid) {
1893 parent
::__construct($uniqueid);
1894 // some sensible defaults
1895 $this->set_attribute('class', 'generaltable generalbox');
1899 * Take the data returned from the db_query and go through all the rows
1900 * processing each col using either col_{columnname} method or other_cols
1901 * method or if other_cols returns NULL then put the data straight into the
1904 * After calling this function, don't forget to call close_recordset.
1906 public function build_table() {
1908 if ($this->rawdata
instanceof \Traversable
&& !$this->rawdata
->valid()) {
1911 if (!$this->rawdata
) {
1915 foreach ($this->rawdata
as $row) {
1916 $formattedrow = $this->format_row($row);
1917 $this->add_data_keyed($formattedrow,
1918 $this->get_row_class($row));
1923 * Closes recordset (for use after building the table).
1925 public function close_recordset() {
1926 if ($this->rawdata
&& ($this->rawdata
instanceof \core\dml\recordset_walk ||
1927 $this->rawdata
instanceof moodle_recordset
)) {
1928 $this->rawdata
->close();
1929 $this->rawdata
= null;
1934 * Get any extra classes names to add to this row in the HTML.
1935 * @param $row array the data for this row.
1936 * @return string added to the class="" attribute of the tr.
1938 function get_row_class($row) {
1943 * This is only needed if you want to use different sql to count rows.
1944 * Used for example when perhaps all db JOINS are not needed when counting
1945 * records. You don't need to call this function the count_sql
1946 * will be generated automatically.
1948 * We need to count rows returned by the db seperately to the query itself
1949 * as we need to know how many pages of data we have to display.
1951 function set_count_sql($sql, array $params = NULL) {
1952 $this->countsql
= $sql;
1953 $this->countparams
= $params;
1957 * Set the sql to query the db. Query will be :
1958 * SELECT $fields FROM $from WHERE $where
1959 * Of course you can use sub-queries, JOINS etc. by putting them in the
1960 * appropriate clause of the query.
1962 function set_sql($fields, $from, $where, array $params = array()) {
1963 $this->sql
= new stdClass();
1964 $this->sql
->fields
= $fields;
1965 $this->sql
->from
= $from;
1966 $this->sql
->where
= $where;
1967 $this->sql
->params
= $params;
1971 * Query the db. Store results in the table object for use by build_table.
1973 * @param int $pagesize size of page for paginated displayed table.
1974 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1975 * will only be used if there is a fullname column defined for the table.
1977 function query_db($pagesize, $useinitialsbar=true) {
1979 if (!$this->is_downloading()) {
1980 if ($this->countsql
=== NULL) {
1981 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1982 $this->countparams
= $this->sql
->params
;
1984 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1985 if ($useinitialsbar && !$this->is_downloading()) {
1986 $this->initialbars(true);
1989 list($wsql, $wparams) = $this->get_sql_where();
1991 $this->countsql
.= ' AND '.$wsql;
1992 $this->countparams
= array_merge($this->countparams
, $wparams);
1994 $this->sql
->where
.= ' AND '.$wsql;
1995 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1997 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1999 $total = $grandtotal;
2002 $this->pagesize($pagesize, $total);
2005 // Fetch the attempts
2006 $sort = $this->get_sql_sort();
2008 $sort = "ORDER BY $sort";
2011 {$this->sql->fields}
2012 FROM {$this->sql->from}
2013 WHERE {$this->sql->where}
2016 if (!$this->is_downloading()) {
2017 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
2019 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
2024 * Convenience method to call a number of methods for you to display the
2027 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
2029 if (!$this->columns
) {
2030 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
2031 $this->sql
->params
, IGNORE_MULTIPLE
);
2032 //if columns is not set then define columns as the keys of the rows returned
2034 $this->define_columns(array_keys((array)$onerow));
2035 $this->define_headers(array_keys((array)$onerow));
2037 $this->pagesize
= $pagesize;
2039 $this->query_db($pagesize, $useinitialsbar);
2040 $this->build_table();
2041 $this->close_recordset();
2042 $this->finish_output();
2048 * @package moodlecore
2049 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2052 class table_default_export_format_parent
{
2054 * @var flexible_table or child class reference pointing to table class
2055 * object from which to export data.
2060 * @var bool output started. Keeps track of whether any output has been
2063 var $documentstarted = false;
2068 * @param flexible_table $table
2070 public function __construct(&$table) {
2071 $this->table
=& $table;
2075 * Old syntax of class constructor. Deprecated in PHP7.
2077 * @deprecated since Moodle 3.1
2079 public function table_default_export_format_parent(&$table) {
2080 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2081 self
::__construct($table);
2084 function set_table(&$table) {
2085 $this->table
=& $table;
2088 function add_data($row) {
2092 function add_seperator() {
2096 function document_started() {
2097 return $this->documentstarted
;
2100 * Given text in a variety of format codings, this function returns
2101 * the text as safe HTML or as plain text dependent on what is appropriate
2102 * for the download format. The default removes all tags.
2104 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
2105 //use some whitespace to indicate where there was some line spacing.
2106 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
2107 return strip_tags($text);
2112 * Dataformat exporter
2115 * @subpackage tablelib
2116 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
2117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2119 class table_dataformat_export_format
extends table_default_export_format_parent
{
2121 /** @var \core\dataformat\base $dataformat */
2122 protected $dataformat;
2125 protected $rownum = 0;
2127 /** @var $columns */
2133 * @param string $table An sql table
2134 * @param string $dataformat type of dataformat for export
2136 public function __construct(&$table, $dataformat) {
2137 parent
::__construct($table);
2139 if (ob_get_length()) {
2140 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
2143 $classname = 'dataformat_' . $dataformat . '\writer';
2144 if (!class_exists($classname)) {
2145 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
2147 $this->dataformat
= new $classname;
2149 // The dataformat export time to first byte could take a while to generate...
2152 // Close the session so that the users other tabs in the same session are not blocked.
2153 \core\session\manager
::write_close();
2157 * Whether the current dataformat supports export of HTML
2161 public function supports_html(): bool {
2162 return $this->dataformat
->supports_html();
2168 * @param string $filename
2169 * @param string $sheettitle
2171 public function start_document($filename, $sheettitle) {
2172 $this->documentstarted
= true;
2173 $this->dataformat
->set_filename($filename);
2174 $this->dataformat
->send_http_headers();
2175 $this->dataformat
->set_sheettitle($sheettitle);
2176 $this->dataformat
->start_output();
2182 * @param string $sheettitle optional spreadsheet worksheet title
2184 public function start_table($sheettitle) {
2185 $this->dataformat
->set_sheettitle($sheettitle);
2191 * @param array $headers
2193 public function output_headers($headers) {
2194 $this->columns
= $headers;
2195 if (method_exists($this->dataformat
, 'write_header')) {
2196 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
2197 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
2198 $this->dataformat
->write_header($headers);
2200 $this->dataformat
->start_sheet($headers);
2207 * @param array $row One record of data
2209 public function add_data($row) {
2210 $this->dataformat
->write_record($row, $this->rownum++
);
2217 public function finish_table() {
2218 if (method_exists($this->dataformat
, 'write_footer')) {
2219 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
2220 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
2221 $this->dataformat
->write_footer($this->columns
);
2223 $this->dataformat
->close_sheet($this->columns
);
2230 public function finish_document() {
2231 $this->dataformat
->close_output();