Moodle release 4.0
[moodle.git] / lib / tablelib.php
blob70138797506a3763416dbafd097b0fe0d5fe0562
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @package core
20 * @subpackage lib
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**#@+
29 * These constants relate to the table's handling of URL parameters.
31 define('TABLE_VAR_SORT', 1);
32 define('TABLE_VAR_HIDE', 2);
33 define('TABLE_VAR_SHOW', 3);
34 define('TABLE_VAR_IFIRST', 4);
35 define('TABLE_VAR_ILAST', 5);
36 define('TABLE_VAR_PAGE', 6);
37 define('TABLE_VAR_RESET', 7);
38 define('TABLE_VAR_DIR', 8);
39 /**#@-*/
41 /**#@+
42 * Constants that indicate whether the paging bar for the table
43 * appears above or below the table.
45 define('TABLE_P_TOP', 1);
46 define('TABLE_P_BOTTOM', 2);
47 /**#@-*/
49 /**
50 * Constant that defines the 'Show all' page size.
52 define('TABLE_SHOW_ALL_PAGE_SIZE', 5000);
54 use core_table\local\filter\filterset;
56 /**
57 * @package moodlecore
58 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
59 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 class flexible_table {
63 var $uniqueid = NULL;
64 var $attributes = array();
65 var $headers = array();
67 /**
68 * @var string A column which should be considered as a header column.
70 protected $headercolumn = null;
72 /**
73 * @var string For create header with help icon.
75 private $helpforheaders = array();
76 var $columns = array();
77 var $column_style = array();
78 var $column_class = array();
79 var $column_suppress = array();
80 var $column_nosort = array('userpic');
81 private $column_textsort = array();
82 /** @var boolean Stores if setup has already been called on this flixible table. */
83 var $setup = false;
84 var $baseurl = NULL;
85 var $request = array();
87 /** @var string[] Columns that are expected to contain a users fullname. */
88 protected $userfullnamecolumns = ['fullname'];
90 /** @var array[] Attributes for each column */
91 private $columnsattributes = [];
93 /**
94 * @var bool Whether or not to store table properties in the user_preferences table.
96 private $persistent = false;
97 var $is_collapsible = false;
98 var $is_sortable = false;
101 * @var array The fields to sort.
103 protected $sortdata;
105 /** @var string The manually set first name initial preference */
106 protected $ifirst;
108 /** @var string The manually set last name initial preference */
109 protected $ilast;
111 var $use_pages = false;
112 var $use_initials = false;
114 var $maxsortkeys = 2;
115 var $pagesize = 30;
116 var $currpage = 0;
117 var $totalrows = 0;
118 var $currentrow = 0;
119 var $sort_default_column = NULL;
120 var $sort_default_order = SORT_ASC;
122 /** @var integer The defeult per page size for the table. */
123 private $defaultperpage = 30;
126 * Array of positions in which to display download controls.
128 var $showdownloadbuttonsat= array(TABLE_P_TOP);
131 * @var string Key of field returned by db query that is the id field of the
132 * user table or equivalent.
134 public $useridfield = 'id';
137 * @var string which download plugin to use. Default '' means none - print
138 * html table with paging. Property set by is_downloading which typically
139 * passes in cleaned data from $
141 var $download = '';
144 * @var bool whether data is downloadable from table. Determines whether
145 * to display download buttons. Set by method downloadable().
147 var $downloadable = false;
150 * @var bool Has start output been called yet?
152 var $started_output = false;
154 var $exportclass = null;
157 * @var array For storing user-customised table properties in the user_preferences db table.
159 private $prefs = array();
161 /** @var $sheettitle */
162 protected $sheettitle;
164 /** @var $filename */
165 protected $filename;
167 /** @var array $hiddencolumns List of hidden columns. */
168 protected $hiddencolumns;
170 /** @var $resetting bool Whether the table preferences is resetting. */
171 protected $resetting;
174 * @var filterset The currently applied filerset
175 * This is required for dynamic tables, but can be used by other tables too if desired.
177 protected $filterset = null;
180 * Constructor
181 * @param string $uniqueid all tables have to have a unique id, this is used
182 * as a key when storing table properties like sort order in the session.
184 function __construct($uniqueid) {
185 $this->uniqueid = $uniqueid;
186 $this->request = array(
187 TABLE_VAR_SORT => 'tsort',
188 TABLE_VAR_HIDE => 'thide',
189 TABLE_VAR_SHOW => 'tshow',
190 TABLE_VAR_IFIRST => 'tifirst',
191 TABLE_VAR_ILAST => 'tilast',
192 TABLE_VAR_PAGE => 'page',
193 TABLE_VAR_RESET => 'treset',
194 TABLE_VAR_DIR => 'tdir',
199 * Call this to pass the download type. Use :
200 * $download = optional_param('download', '', PARAM_ALPHA);
201 * To get the download type. We assume that if you call this function with
202 * params that this table's data is downloadable, so we call is_downloadable
203 * for you (even if the param is '', which means no download this time.
204 * Also you can call this method with no params to get the current set
205 * download type.
206 * @param string $download dataformat type. One of csv, xhtml, ods, etc
207 * @param string $filename filename for downloads without file extension.
208 * @param string $sheettitle title for downloaded data.
209 * @return string download dataformat type. One of csv, xhtml, ods, etc
211 function is_downloading($download = null, $filename='', $sheettitle='') {
212 if ($download!==null) {
213 $this->sheettitle = $sheettitle;
214 $this->is_downloadable(true);
215 $this->download = $download;
216 $this->filename = clean_filename($filename);
217 $this->export_class_instance();
219 return $this->download;
223 * Get, and optionally set, the export class.
224 * @param $exportclass (optional) if passed, set the table to use this export class.
225 * @return table_default_export_format_parent the export class in use (after any set).
227 function export_class_instance($exportclass = null) {
228 if (!is_null($exportclass)) {
229 $this->started_output = true;
230 $this->exportclass = $exportclass;
231 $this->exportclass->table = $this;
232 } else if (is_null($this->exportclass) && !empty($this->download)) {
233 $this->exportclass = new table_dataformat_export_format($this, $this->download);
234 if (!$this->exportclass->document_started()) {
235 $this->exportclass->start_document($this->filename, $this->sheettitle);
238 return $this->exportclass;
242 * Probably don't need to call this directly. Calling is_downloading with a
243 * param automatically sets table as downloadable.
245 * @param bool $downloadable optional param to set whether data from
246 * table is downloadable. If ommitted this function can be used to get
247 * current state of table.
248 * @return bool whether table data is set to be downloadable.
250 function is_downloadable($downloadable = null) {
251 if ($downloadable !== null) {
252 $this->downloadable = $downloadable;
254 return $this->downloadable;
258 * Call with boolean true to store table layout changes in the user_preferences table.
259 * Note: user_preferences.value has a maximum length of 1333 characters.
260 * Call with no parameter to get current state of table persistence.
262 * @param bool $persistent Optional parameter to set table layout persistence.
263 * @return bool Whether or not the table layout preferences will persist.
265 public function is_persistent($persistent = null) {
266 if ($persistent == true) {
267 $this->persistent = true;
269 return $this->persistent;
273 * Where to show download buttons.
274 * @param array $showat array of postions in which to show download buttons.
275 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
277 function show_download_buttons_at($showat) {
278 $this->showdownloadbuttonsat = $showat;
282 * Sets the is_sortable variable to the given boolean, sort_default_column to
283 * the given string, and the sort_default_order to the given integer.
284 * @param bool $bool
285 * @param string $defaultcolumn
286 * @param int $defaultorder
287 * @return void
289 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
290 $this->is_sortable = $bool;
291 $this->sort_default_column = $defaultcolumn;
292 $this->sort_default_order = $defaultorder;
296 * Use text sorting functions for this column (required for text columns with Oracle).
297 * Be warned that you cannot use this with column aliases. You can only do this
298 * with real columns. See MDL-40481 for an example.
299 * @param string column name
301 function text_sorting($column) {
302 $this->column_textsort[] = $column;
306 * Do not sort using this column
307 * @param string column name
309 function no_sorting($column) {
310 $this->column_nosort[] = $column;
314 * Is the column sortable?
315 * @param string column name, null means table
316 * @return bool
318 function is_sortable($column = null) {
319 if (empty($column)) {
320 return $this->is_sortable;
322 if (!$this->is_sortable) {
323 return false;
325 return !in_array($column, $this->column_nosort);
329 * Sets the is_collapsible variable to the given boolean.
330 * @param bool $bool
331 * @return void
333 function collapsible($bool) {
334 $this->is_collapsible = $bool;
338 * Sets the use_pages variable to the given boolean.
339 * @param bool $bool
340 * @return void
342 function pageable($bool) {
343 $this->use_pages = $bool;
347 * Sets the use_initials variable to the given boolean.
348 * @param bool $bool
349 * @return void
351 function initialbars($bool) {
352 $this->use_initials = $bool;
356 * Sets the pagesize variable to the given integer, the totalrows variable
357 * to the given integer, and the use_pages variable to true.
358 * @param int $perpage
359 * @param int $total
360 * @return void
362 function pagesize($perpage, $total) {
363 $this->pagesize = $perpage;
364 $this->totalrows = $total;
365 $this->use_pages = true;
369 * Assigns each given variable in the array to the corresponding index
370 * in the request class variable.
371 * @param array $variables
372 * @return void
374 function set_control_variables($variables) {
375 foreach ($variables as $what => $variable) {
376 if (isset($this->request[$what])) {
377 $this->request[$what] = $variable;
383 * Gives the given $value to the $attribute index of $this->attributes.
384 * @param string $attribute
385 * @param mixed $value
386 * @return void
388 function set_attribute($attribute, $value) {
389 $this->attributes[$attribute] = $value;
393 * What this method does is set the column so that if the same data appears in
394 * consecutive rows, then it is not repeated.
396 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
397 * that when one student has made multiple attempts, their name is only printed in the row
398 * for their first attempt.
399 * @param int $column the index of a column.
401 function column_suppress($column) {
402 if (isset($this->column_suppress[$column])) {
403 $this->column_suppress[$column] = true;
408 * Sets the given $column index to the given $classname in $this->column_class.
409 * @param int $column
410 * @param string $classname
411 * @return void
413 function column_class($column, $classname) {
414 if (isset($this->column_class[$column])) {
415 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
420 * Sets the given $column index and $property index to the given $value in $this->column_style.
421 * @param int $column
422 * @param string $property
423 * @param mixed $value
424 * @return void
426 function column_style($column, $property, $value) {
427 if (isset($this->column_style[$column])) {
428 $this->column_style[$column][$property] = $value;
433 * Sets the given $attributes to $this->columnsattributes.
434 * Column attributes will be added to every cell in the column.
436 * @param array[] $attributes e.g. ['c0_firstname' => ['data-foo' => 'bar']]
438 public function set_columnsattributes(array $attributes): void {
439 $this->columnsattributes = $attributes;
443 * Sets all columns' $propertys to the given $value in $this->column_style.
444 * @param int $property
445 * @param string $value
446 * @return void
448 function column_style_all($property, $value) {
449 foreach (array_keys($this->columns) as $column) {
450 $this->column_style[$column][$property] = $value;
455 * Sets $this->baseurl.
456 * @param moodle_url|string $url the url with params needed to call up this page
458 function define_baseurl($url) {
459 $this->baseurl = new moodle_url($url);
463 * @param array $columns an array of identifying names for columns. If
464 * columns are sorted then column names must correspond to a field in sql.
466 function define_columns($columns) {
467 $this->columns = array();
468 $this->column_style = array();
469 $this->column_class = array();
470 $this->columnsattributes = [];
471 $colnum = 0;
473 foreach ($columns as $column) {
474 $this->columns[$column] = $colnum++;
475 $this->column_style[$column] = array();
476 $this->column_class[$column] = '';
477 $this->columnsattributes[$column] = [];
478 $this->column_suppress[$column] = false;
483 * @param array $headers numerical keyed array of displayed string titles
484 * for each column.
486 function define_headers($headers) {
487 $this->headers = $headers;
491 * Mark a specific column as being a table header using the column name defined in define_columns.
493 * Note: Only one column can be a header, and it will be rendered using a th tag.
495 * @param string $column
497 public function define_header_column(string $column) {
498 $this->headercolumn = $column;
502 * Defines a help icon for the header
504 * Always use this function if you need to create header with sorting and help icon.
506 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
508 public function define_help_for_headers($helpicons) {
509 $this->helpforheaders = $helpicons;
513 * Mark the table preferences to be reset.
515 public function mark_table_to_reset(): void {
516 $this->resetting = true;
520 * Is the table marked for reset preferences?
522 * @return bool True if the table is marked to reset, false otherwise.
524 protected function is_resetting_preferences(): bool {
525 if ($this->resetting === null) {
526 $this->resetting = optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL);
529 return $this->resetting;
533 * Must be called after table is defined. Use methods above first. Cannot
534 * use functions below till after calling this method.
535 * @return type?
537 function setup() {
539 if (empty($this->columns) || empty($this->uniqueid)) {
540 return false;
543 $this->initialise_table_preferences();
545 if (empty($this->baseurl)) {
546 debugging('You should set baseurl when using flexible_table.');
547 global $PAGE;
548 $this->baseurl = $PAGE->url;
551 if ($this->currpage == null) {
552 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
555 $this->setup = true;
557 // Always introduce the "flexible" class for the table if not specified
558 if (empty($this->attributes)) {
559 $this->attributes['class'] = 'flexible table table-striped table-hover';
560 } else if (!isset($this->attributes['class'])) {
561 $this->attributes['class'] = 'flexible table table-striped table-hover';
562 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
563 $this->attributes['class'] = trim('flexible table table-striped table-hover ' . $this->attributes['class']);
568 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
569 * @param string $uniqueid the identifier for a table.
570 * @return SQL fragment that can be used in an ORDER BY clause.
572 public static function get_sort_for_table($uniqueid) {
573 global $SESSION;
574 if (isset($SESSION->flextable[$uniqueid])) {
575 $prefs = $SESSION->flextable[$uniqueid];
576 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
577 return '';
580 if (empty($prefs['sortby'])) {
581 return '';
583 if (empty($prefs['textsort'])) {
584 $prefs['textsort'] = array();
587 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
591 * Prepare an an order by clause from the list of columns to be sorted.
592 * @param array $cols column name => SORT_ASC or SORT_DESC
593 * @return SQL fragment that can be used in an ORDER BY clause.
595 public static function construct_order_by($cols, $textsortcols=array()) {
596 global $DB;
597 $bits = array();
599 foreach ($cols as $column => $order) {
600 if (in_array($column, $textsortcols)) {
601 $column = $DB->sql_order_by_text($column);
603 if ($order == SORT_ASC) {
604 $bits[] = $column . ' ASC';
605 } else {
606 $bits[] = $column . ' DESC';
610 return implode(', ', $bits);
614 * @return SQL fragment that can be used in an ORDER BY clause.
616 public function get_sql_sort() {
617 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
621 * Whether the current table contains any fullname columns
623 * @return bool
625 private function contains_fullname_columns(): bool {
626 $fullnamecolumns = array_intersect_key($this->columns, array_flip($this->userfullnamecolumns));
628 return !empty($fullnamecolumns);
632 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
633 * @return array column name => SORT_... constant.
635 public function get_sort_columns() {
636 if (!$this->setup) {
637 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
640 if (empty($this->prefs['sortby'])) {
641 return array();
643 foreach ($this->prefs['sortby'] as $column => $notused) {
644 if (isset($this->columns[$column])) {
645 continue; // This column is OK.
647 if (in_array($column, \core_user\fields::get_name_fields()) && $this->contains_fullname_columns()) {
648 continue; // This column is OK.
650 // This column is not OK.
651 unset($this->prefs['sortby'][$column]);
654 return $this->prefs['sortby'];
658 * @return int the offset for LIMIT clause of SQL
660 function get_page_start() {
661 if (!$this->use_pages) {
662 return '';
664 return $this->currpage * $this->pagesize;
668 * @return int the pagesize for LIMIT clause of SQL
670 function get_page_size() {
671 if (!$this->use_pages) {
672 return '';
674 return $this->pagesize;
678 * @return string sql to add to where statement.
680 function get_sql_where() {
681 global $DB;
683 $conditions = array();
684 $params = array();
686 if ($this->contains_fullname_columns()) {
687 static $i = 0;
688 $i++;
690 if (!empty($this->prefs['i_first'])) {
691 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
692 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
694 if (!empty($this->prefs['i_last'])) {
695 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
696 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
700 return array(implode(" AND ", $conditions), $params);
704 * Add a row of data to the table. This function takes an array or object with
705 * column names as keys or property names.
707 * It ignores any elements with keys that are not defined as columns. It
708 * puts in empty strings into the row when there is no element in the passed
709 * array corresponding to a column in the table. It puts the row elements in
710 * the proper order (internally row table data is stored by in arrays with
711 * a numerical index corresponding to the column number).
713 * @param object|array $rowwithkeys array keys or object property names are column names,
714 * as defined in call to define_columns.
715 * @param string $classname CSS class name to add to this row's tr tag.
717 function add_data_keyed($rowwithkeys, $classname = '') {
718 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
722 * Add a number of rows to the table at once. And optionally finish output after they have been added.
724 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
725 * object or array is added to table. We expect properties for the row array as would be
726 * passed to add_data_keyed.
727 * @param bool $finish
729 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
730 foreach ($rowstoadd as $row) {
731 if (is_null($row)) {
732 $this->add_separator();
733 } else {
734 $this->add_data_keyed($this->format_row($row));
737 if ($finish) {
738 $this->finish_output(!$this->is_downloading());
743 * Add a seperator line to table.
745 function add_separator() {
746 if (!$this->setup) {
747 return false;
749 $this->add_data(NULL);
753 * This method actually directly echoes the row passed to it now or adds it
754 * to the download. If this is the first row and start_output has not
755 * already been called this method also calls start_output to open the table
756 * or send headers for the downloaded.
757 * Can be used as before. print_html now calls finish_html to close table.
759 * @param array $row a numerically keyed row of data to add to the table.
760 * @param string $classname CSS class name to add to this row's tr tag.
761 * @return bool success.
763 function add_data($row, $classname = '') {
764 if (!$this->setup) {
765 return false;
767 if (!$this->started_output) {
768 $this->start_output();
770 if ($this->exportclass!==null) {
771 if ($row === null) {
772 $this->exportclass->add_seperator();
773 } else {
774 $this->exportclass->add_data($row);
776 } else {
777 $this->print_row($row, $classname);
779 return true;
783 * You should call this to finish outputting the table data after adding
784 * data to the table with add_data or add_data_keyed.
787 function finish_output($closeexportclassdoc = true) {
788 if ($this->exportclass!==null) {
789 $this->exportclass->finish_table();
790 if ($closeexportclassdoc) {
791 $this->exportclass->finish_document();
793 } else {
794 $this->finish_html();
799 * Hook that can be overridden in child classes to wrap a table in a form
800 * for example. Called only when there is data to display and not
801 * downloading.
803 function wrap_html_start() {
807 * Hook that can be overridden in child classes to wrap a table in a form
808 * for example. Called only when there is data to display and not
809 * downloading.
811 function wrap_html_finish() {
815 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
816 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
817 * displaying table as html, adding a div wrap, etc.
819 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
821 * @param array|object $row row of data from db used to make one row of the table.
822 * @return array one row for the table, added using add_data_keyed method.
824 function format_row($row) {
825 if (is_array($row)) {
826 $row = (object)$row;
828 $formattedrow = array();
829 foreach (array_keys($this->columns) as $column) {
830 $colmethodname = 'col_'.$column;
831 if (method_exists($this, $colmethodname)) {
832 $formattedcolumn = $this->$colmethodname($row);
833 } else {
834 $formattedcolumn = $this->other_cols($column, $row);
835 if ($formattedcolumn===NULL) {
836 $formattedcolumn = $row->$column;
839 $formattedrow[$column] = $formattedcolumn;
841 return $formattedrow;
845 * Fullname is treated as a special columname in tablelib and should always
846 * be treated the same as the fullname of a user.
847 * @uses $this->useridfield if the userid field is not expected to be id
848 * then you need to override $this->useridfield to point at the correct
849 * field for the user id.
851 * @param object $row the data from the db containing all fields from the
852 * users table necessary to construct the full name of the user in
853 * current language.
854 * @return string contents of cell in column 'fullname', for this row.
856 function col_fullname($row) {
857 global $COURSE;
859 $name = fullname($row, has_capability('moodle/site:viewfullnames', $this->get_context()));
860 if ($this->download) {
861 return $name;
864 $userid = $row->{$this->useridfield};
865 if ($COURSE->id == SITEID) {
866 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
867 } else {
868 $profileurl = new moodle_url('/user/view.php',
869 array('id' => $userid, 'course' => $COURSE->id));
871 return html_writer::link($profileurl, $name);
875 * You can override this method in a child class. See the description of
876 * build_table which calls this method.
878 function other_cols($column, $row) {
879 if (isset($row->$column) && ($column === 'email' || $column === 'idnumber') &&
880 (!$this->is_downloading() || $this->export_class_instance()->supports_html())) {
881 // Columns email and idnumber may potentially contain malicious characters, escape them by default.
882 // This function will not be executed if the child class implements col_email() or col_idnumber().
883 return s($row->$column);
885 return NULL;
889 * Used from col_* functions when text is to be displayed. Does the
890 * right thing - either converts text to html or strips any html tags
891 * depending on if we are downloading and what is the download type. Params
892 * are the same as format_text function in weblib.php but some default
893 * options are changed.
895 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
896 if (!$this->is_downloading()) {
897 if (is_null($options)) {
898 $options = new stdClass;
900 //some sensible defaults
901 if (!isset($options->para)) {
902 $options->para = false;
904 if (!isset($options->newlines)) {
905 $options->newlines = false;
907 if (!isset($options->smiley)) {
908 $options->smiley = false;
910 if (!isset($options->filter)) {
911 $options->filter = false;
913 return format_text($text, $format, $options);
914 } else {
915 $eci = $this->export_class_instance();
916 return $eci->format_text($text, $format, $options, $courseid);
920 * This method is deprecated although the old api is still supported.
921 * @deprecated 1.9.2 - Jun 2, 2008
923 function print_html() {
924 if (!$this->setup) {
925 return false;
927 $this->finish_html();
931 * This function is not part of the public api.
932 * @return string initial of first name we are currently filtering by
934 function get_initial_first() {
935 if (!$this->use_initials) {
936 return NULL;
939 return $this->prefs['i_first'];
943 * This function is not part of the public api.
944 * @return string initial of last name we are currently filtering by
946 function get_initial_last() {
947 if (!$this->use_initials) {
948 return NULL;
951 return $this->prefs['i_last'];
955 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
956 * @param array $alpha of letters in the alphabet.
957 * @param string $current the currently selected letter.
958 * @param string $class class name to add to this initial bar.
959 * @param string $title the name to put in front of this initial bar.
960 * @param string $urlvar URL parameter name for this initial.
962 * @deprecated since Moodle 3.3
964 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
966 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
967 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
969 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
970 $title . ' : ';
971 if ($current) {
972 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
973 } else {
974 echo html_writer::tag('strong', get_string('all'));
977 foreach ($alpha as $letter) {
978 if ($letter === $current) {
979 echo html_writer::tag('strong', $letter);
980 } else {
981 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
985 echo html_writer::end_tag('div');
989 * This function is not part of the public api.
991 function print_initials_bar() {
992 global $OUTPUT;
994 $ifirst = $this->get_initial_first();
995 $ilast = $this->get_initial_last();
996 if (is_null($ifirst)) {
997 $ifirst = '';
999 if (is_null($ilast)) {
1000 $ilast = '';
1003 if ((!empty($ifirst) || !empty($ilast) || $this->use_initials) && $this->contains_fullname_columns()) {
1004 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
1005 $prefixlast = $this->request[TABLE_VAR_ILAST];
1006 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
1007 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
1013 * This function is not part of the public api.
1015 function print_nothing_to_display() {
1016 global $OUTPUT;
1018 // Render the dynamic table header.
1019 echo $this->get_dynamic_table_html_start();
1021 // Render button to allow user to reset table preferences.
1022 echo $this->render_reset_button();
1024 $this->print_initials_bar();
1026 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1028 // Render the dynamic table footer.
1029 echo $this->get_dynamic_table_html_end();
1033 * This function is not part of the public api.
1035 function get_row_from_keyed($rowwithkeys) {
1036 if (is_object($rowwithkeys)) {
1037 $rowwithkeys = (array)$rowwithkeys;
1039 $row = array();
1040 foreach (array_keys($this->columns) as $column) {
1041 if (isset($rowwithkeys[$column])) {
1042 $row [] = $rowwithkeys[$column];
1043 } else {
1044 $row[] ='';
1047 return $row;
1051 * Get the html for the download buttons
1053 * Usually only use internally
1055 public function download_buttons() {
1056 global $OUTPUT;
1058 if ($this->is_downloadable() && !$this->is_downloading()) {
1059 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1060 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1061 } else {
1062 return '';
1067 * This function is not part of the public api.
1068 * You don't normally need to call this. It is called automatically when
1069 * needed when you start adding data to the table.
1072 function start_output() {
1073 $this->started_output = true;
1074 if ($this->exportclass!==null) {
1075 $this->exportclass->start_table($this->sheettitle);
1076 $this->exportclass->output_headers($this->headers);
1077 } else {
1078 $this->start_html();
1079 $this->print_headers();
1080 echo html_writer::start_tag('tbody');
1085 * This function is not part of the public api.
1087 function print_row($row, $classname = '') {
1088 echo $this->get_row_html($row, $classname);
1092 * Generate html code for the passed row.
1094 * @param array $row Row data.
1095 * @param string $classname classes to add.
1097 * @return string $html html code for the row passed.
1099 public function get_row_html($row, $classname = '') {
1100 static $suppress_lastrow = NULL;
1101 $rowclasses = array();
1103 if ($classname) {
1104 $rowclasses[] = $classname;
1107 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1108 $html = '';
1110 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1112 // If we have a separator, print it
1113 if ($row === NULL) {
1114 $colcount = count($this->columns);
1115 $html .= html_writer::tag('td', html_writer::tag('div', '',
1116 array('class' => 'tabledivider')), array('colspan' => $colcount));
1118 } else {
1119 $html .= $this->get_row_cells_html($rowid, $row, $suppress_lastrow);
1122 $html .= html_writer::end_tag('tr');
1124 $suppress_enabled = array_sum($this->column_suppress);
1125 if ($suppress_enabled) {
1126 $suppress_lastrow = $row;
1128 $this->currentrow++;
1129 return $html;
1133 * Generate html code for the row cells.
1135 * @param string $rowid
1136 * @param array $row
1137 * @param array|null $suppresslastrow
1138 * @return string
1140 public function get_row_cells_html(string $rowid, array $row, ?array $suppresslastrow): string {
1141 $html = '';
1142 $colbyindex = array_flip($this->columns);
1143 foreach ($row as $index => $data) {
1144 $column = $colbyindex[$index];
1146 $attributes = [
1147 'class' => "cell c{$index}" . $this->column_class[$column],
1148 'id' => "{$rowid}_c{$index}",
1149 'style' => $this->make_styles_string($this->column_style[$column]),
1152 $celltype = 'td';
1153 if ($this->headercolumn && $column == $this->headercolumn) {
1154 $celltype = 'th';
1155 $attributes['scope'] = 'row';
1158 $attributes += $this->columnsattributes[$column] ?? [];
1160 if (empty($this->prefs['collapse'][$column])) {
1161 if ($this->column_suppress[$column] && $suppresslastrow !== null && $suppresslastrow[$index] === $data) {
1162 $content = '&nbsp;';
1163 } else {
1164 $content = $data;
1166 } else {
1167 $content = '&nbsp;';
1170 $html .= html_writer::tag($celltype, $content, $attributes);
1172 return $html;
1176 * This function is not part of the public api.
1178 function finish_html() {
1179 global $OUTPUT, $PAGE;
1181 if (!$this->started_output) {
1182 //no data has been added to the table.
1183 $this->print_nothing_to_display();
1185 } else {
1186 // Print empty rows to fill the table to the current pagesize.
1187 // This is done so the header aria-controls attributes do not point to
1188 // non existant elements.
1189 $emptyrow = array_fill(0, count($this->columns), '');
1190 while ($this->currentrow < $this->pagesize) {
1191 $this->print_row($emptyrow, 'emptyrow');
1194 echo html_writer::end_tag('tbody');
1195 echo html_writer::end_tag('table');
1196 echo html_writer::end_tag('div');
1197 $this->wrap_html_finish();
1199 // Paging bar
1200 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1201 echo $this->download_buttons();
1204 if($this->use_pages) {
1205 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1206 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1207 echo $OUTPUT->render($pagingbar);
1210 // Render the dynamic table footer.
1211 echo $this->get_dynamic_table_html_end();
1216 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1217 * used by {@link print_headers()}.
1218 * @param string $column the column name, index into various names.
1219 * @param int $index numerical index of the column.
1220 * @return string HTML fragment.
1222 protected function show_hide_link($column, $index) {
1223 global $OUTPUT;
1224 // Some headers contain <br /> tags, do not include in title, hence the
1225 // strip tags.
1227 $ariacontrols = '';
1228 for ($i = 0; $i < $this->pagesize; $i++) {
1229 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1232 $ariacontrols = trim($ariacontrols);
1234 if (!empty($this->prefs['collapse'][$column])) {
1235 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1236 'aria-expanded' => 'false',
1237 'aria-controls' => $ariacontrols,
1238 'data-action' => 'show',
1239 'data-column' => $column);
1240 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1241 $OUTPUT->pix_icon('t/switch_plus', null), $linkattributes);
1243 } else if ($this->headers[$index] !== NULL) {
1244 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1245 'aria-expanded' => 'true',
1246 'aria-controls' => $ariacontrols,
1247 'data-action' => 'hide',
1248 'data-column' => $column);
1249 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1250 $OUTPUT->pix_icon('t/switch_minus', null), $linkattributes);
1255 * This function is not part of the public api.
1257 function print_headers() {
1258 global $CFG, $OUTPUT;
1260 // Set the primary sort column/order where possible, so that sort links/icons are correct.
1262 'sortby' => $primarysortcolumn,
1263 'sortorder' => $primarysortorder,
1264 ] = $this->get_primary_sort_order();
1266 echo html_writer::start_tag('thead');
1267 echo html_writer::start_tag('tr');
1268 foreach ($this->columns as $column => $index) {
1270 $icon_hide = '';
1271 if ($this->is_collapsible) {
1272 $icon_hide = $this->show_hide_link($column, $index);
1274 switch ($column) {
1276 case 'userpic':
1277 // do nothing, do not display sortable links
1278 break;
1280 default:
1282 if (array_search($column, $this->userfullnamecolumns) !== false) {
1283 // Check the full name display for sortable fields.
1284 if (has_capability('moodle/site:viewfullnames', $this->get_context())) {
1285 $nameformat = $CFG->alternativefullnameformat;
1286 } else {
1287 $nameformat = $CFG->fullnamedisplay;
1290 if ($nameformat == 'language') {
1291 $nameformat = get_string('fullnamedisplay');
1294 $requirednames = order_in_string(\core_user\fields::get_name_fields(), $nameformat);
1296 if (!empty($requirednames)) {
1297 if ($this->is_sortable($column)) {
1298 // Done this way for the possibility of more than two sortable full name display fields.
1299 $this->headers[$index] = '';
1300 foreach ($requirednames as $name) {
1301 $sortname = $this->sort_link(get_string($name),
1302 $name, $primarysortcolumn === $name, $primarysortorder);
1303 $this->headers[$index] .= $sortname . ' / ';
1305 $helpicon = '';
1306 if (isset($this->helpforheaders[$index])) {
1307 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1309 $this->headers[$index] = substr($this->headers[$index], 0, -3) . $helpicon;
1312 } else if ($this->is_sortable($column)) {
1313 $helpicon = '';
1314 if (isset($this->helpforheaders[$index])) {
1315 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1317 $this->headers[$index] = $this->sort_link($this->headers[$index],
1318 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1322 $attributes = array(
1323 'class' => 'header c' . $index . $this->column_class[$column],
1324 'scope' => 'col',
1326 if ($this->headers[$index] === NULL) {
1327 $content = '&nbsp;';
1328 } else if (!empty($this->prefs['collapse'][$column])) {
1329 $content = $icon_hide;
1330 } else {
1331 if (is_array($this->column_style[$column])) {
1332 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1334 $helpicon = '';
1335 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1336 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1338 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1339 $icon_hide, array('class' => 'commands'));
1341 echo html_writer::tag('th', $content, $attributes);
1344 echo html_writer::end_tag('tr');
1345 echo html_writer::end_tag('thead');
1349 * Calculate the preferences for sort order based on user-supplied values and get params.
1351 protected function set_sorting_preferences(): void {
1352 $sortdata = $this->sortdata;
1354 if ($sortdata === null) {
1355 $sortdata = $this->prefs['sortby'];
1357 $sortorder = optional_param($this->request[TABLE_VAR_DIR], $this->sort_default_order, PARAM_INT);
1358 $sortby = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT);
1360 if (array_key_exists($sortby, $sortdata)) {
1361 // This key already exists somewhere. Change its sortorder and bring it to the top.
1362 unset($sortdata[$sortby]);
1364 $sortdata = array_merge([$sortby => $sortorder], $sortdata);
1367 $usernamefields = \core_user\fields::get_name_fields();
1368 $sortdata = array_filter($sortdata, function($sortby) use ($usernamefields) {
1369 $isvalidsort = $sortby && $this->is_sortable($sortby);
1370 $isvalidsort = $isvalidsort && empty($this->prefs['collapse'][$sortby]);
1371 $isrealcolumn = isset($this->columns[$sortby]);
1372 $isfullnamefield = $this->contains_fullname_columns() && in_array($sortby, $usernamefields);
1374 return $isvalidsort && ($isrealcolumn || $isfullnamefield);
1375 }, ARRAY_FILTER_USE_KEY);
1377 // Finally, make sure that no more than $this->maxsortkeys are present into the array.
1378 $sortdata = array_slice($sortdata, 0, $this->maxsortkeys);
1380 // If a default order is defined and it is not in the current list of order by columns, add it at the end.
1381 // This prevents results from being returned in a random order if the only order by column contains equal values.
1382 if (!empty($this->sort_default_column) && !array_key_exists($this->sort_default_column, $sortdata)) {
1383 $sortdata = array_merge($sortdata, [$this->sort_default_column => $this->sort_default_order]);
1386 // Apply the sortdata to the preference.
1387 $this->prefs['sortby'] = $sortdata;
1391 * Fill in the preferences for the initials bar.
1393 protected function set_initials_preferences(): void {
1394 $ifirst = $this->ifirst;
1395 $ilast = $this->ilast;
1397 if ($ifirst === null) {
1398 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
1401 if ($ilast === null) {
1402 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
1405 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
1406 $this->prefs['i_first'] = $ifirst;
1409 if (!is_null($ilast) && ($ilast === '' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
1410 $this->prefs['i_last'] = $ilast;
1416 * Set hide and show preferences.
1418 protected function set_hide_show_preferences(): void {
1420 if ($this->hiddencolumns !== null) {
1421 $this->prefs['collapse'] = array_fill_keys(array_filter($this->hiddencolumns, function($column) {
1422 return array_key_exists($column, $this->columns);
1423 }), true);
1424 } else {
1425 if ($column = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) {
1426 if (isset($this->columns[$column])) {
1427 $this->prefs['collapse'][$column] = true;
1432 if ($column = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) {
1433 unset($this->prefs['collapse'][$column]);
1436 foreach (array_keys($this->prefs['collapse']) as $column) {
1437 if (array_key_exists($column, $this->prefs['sortby'])) {
1438 unset($this->prefs['sortby'][$column]);
1444 * Set the list of hidden columns.
1446 * @param array $columns The list of hidden columns.
1448 public function set_hidden_columns(array $columns): void {
1449 $this->hiddencolumns = $columns;
1453 * Initialise table preferences.
1455 protected function initialise_table_preferences(): void {
1456 global $SESSION;
1458 // Load any existing user preferences.
1459 if ($this->persistent) {
1460 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
1461 $oldprefs = $this->prefs;
1462 } else if (isset($SESSION->flextable[$this->uniqueid])) {
1463 $this->prefs = $SESSION->flextable[$this->uniqueid];
1464 $oldprefs = $this->prefs;
1467 // Set up default preferences if needed.
1468 if (!$this->prefs || $this->is_resetting_preferences()) {
1469 $this->prefs = [
1470 'collapse' => [],
1471 'sortby' => [],
1472 'i_first' => '',
1473 'i_last' => '',
1474 'textsort' => $this->column_textsort,
1478 if (!isset($oldprefs)) {
1479 $oldprefs = $this->prefs;
1482 // Save user preferences if they have changed.
1483 if ($this->is_resetting_preferences()) {
1484 $this->sortdata = null;
1485 $this->ifirst = null;
1486 $this->ilast = null;
1489 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
1490 isset($this->columns[$showcol])) {
1491 $this->prefs['collapse'][$showcol] = false;
1492 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
1493 isset($this->columns[$hidecol])) {
1494 $this->prefs['collapse'][$hidecol] = true;
1495 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
1496 unset($this->prefs['sortby'][$hidecol]);
1500 $this->set_hide_show_preferences();
1501 $this->set_sorting_preferences();
1502 $this->set_initials_preferences();
1504 // Now, reduce the width of collapsed columns and remove the width from columns that should be expanded.
1505 foreach (array_keys($this->columns) as $column) {
1506 if (!empty($this->prefs['collapse'][$column])) {
1507 $this->column_style[$column]['width'] = '10px';
1508 } else {
1509 unset($this->column_style[$column]['width']);
1513 if (empty($this->baseurl)) {
1514 debugging('You should set baseurl when using flexible_table.');
1515 global $PAGE;
1516 $this->baseurl = $PAGE->url;
1519 if ($this->currpage == null) {
1520 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
1523 $this->save_preferences($oldprefs);
1527 * Save preferences.
1529 * @param array $oldprefs Old preferences to compare against.
1531 protected function save_preferences($oldprefs): void {
1532 global $SESSION;
1534 if ($this->prefs != $oldprefs) {
1535 if ($this->persistent) {
1536 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
1537 } else {
1538 $SESSION->flextable[$this->uniqueid] = $this->prefs;
1541 unset($oldprefs);
1545 * Set the preferred table sorting attributes.
1547 * @param string $sortby The field to sort by.
1548 * @param int $sortorder The sort order.
1550 public function set_sortdata(array $sortdata): void {
1551 $this->sortdata = [];
1552 foreach ($sortdata as $sortitem) {
1553 if (!array_key_exists($sortitem['sortby'], $this->sortdata)) {
1554 $this->sortdata[$sortitem['sortby']] = (int) $sortitem['sortorder'];
1560 * Get the default per page.
1562 * @return int
1564 public function get_default_per_page(): int {
1565 return $this->defaultperpage;
1569 * Set the default per page.
1571 * @param int $defaultperpage
1573 public function set_default_per_page(int $defaultperpage): void {
1574 $this->defaultperpage = $defaultperpage;
1578 * Set the preferred first name initial in an initials bar.
1580 * @param string $initial The character to set
1582 public function set_first_initial(string $initial): void {
1583 $this->ifirst = $initial;
1587 * Set the preferred last name initial in an initials bar.
1589 * @param string $initial The character to set
1591 public function set_last_initial(string $initial): void {
1592 $this->ilast = $initial;
1596 * Set the page number.
1598 * @param int $pagenumber The page number.
1600 public function set_page_number(int $pagenumber): void {
1601 $this->currpage = $pagenumber - 1;
1605 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1606 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1607 * @param int $order SORT_ASC or SORT_DESC
1608 * @return string HTML fragment.
1610 protected function sort_icon($isprimary, $order) {
1611 global $OUTPUT;
1613 if (!$isprimary) {
1614 return '';
1617 if ($order == SORT_ASC) {
1618 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1619 } else {
1620 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1625 * Generate the correct tool tip for changing the sort order. This is a
1626 * helper method used by {@link sort_link()}.
1627 * @param bool $isprimary whether the is column is the current primary sort column.
1628 * @param int $order SORT_ASC or SORT_DESC
1629 * @return string the correct title.
1631 protected function sort_order_name($isprimary, $order) {
1632 if ($isprimary && $order != SORT_ASC) {
1633 return get_string('desc');
1634 } else {
1635 return get_string('asc');
1640 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1641 * @param string $text the text for the link.
1642 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1643 * @param bool $isprimary whether the is column is the current primary sort column.
1644 * @param int $order SORT_ASC or SORT_DESC
1645 * @return string HTML fragment.
1647 protected function sort_link($text, $column, $isprimary, $order) {
1648 // If we are already sorting by this column, switch direction.
1649 if (array_key_exists($column, $this->prefs['sortby'])) {
1650 $sortorder = $this->prefs['sortby'][$column] == SORT_ASC ? SORT_DESC : SORT_ASC;
1651 } else {
1652 $sortorder = $order;
1655 $params = [
1656 $this->request[TABLE_VAR_SORT] => $column,
1657 $this->request[TABLE_VAR_DIR] => $sortorder,
1660 return html_writer::link($this->baseurl->out(false, $params),
1661 $text . get_accesshide(get_string('sortby') . ' ' .
1662 $text . ' ' . $this->sort_order_name($isprimary, $order)),
1664 'data-sortable' => $this->is_sortable($column),
1665 'data-sortby' => $column,
1666 'data-sortorder' => $sortorder,
1667 ]) . ' ' . $this->sort_icon($isprimary, $order);
1671 * Return primary sorting column/order, either the first preferred "sortby" value or defaults defined for the table
1673 * @return array
1675 protected function get_primary_sort_order(): array {
1676 if (reset($this->prefs['sortby'])) {
1677 return $this->get_sort_order();
1680 return [
1681 'sortby' => $this->sort_default_column,
1682 'sortorder' => $this->sort_default_order,
1687 * Return sorting attributes values.
1689 * @return array
1691 protected function get_sort_order(): array {
1692 $sortbys = $this->prefs['sortby'];
1693 $sortby = key($sortbys);
1695 return [
1696 'sortby' => $sortby,
1697 'sortorder' => $sortbys[$sortby],
1702 * Get dynamic class component.
1704 * @return string
1706 protected function get_component() {
1707 $tableclass = explode("\\", get_class($this));
1708 return reset($tableclass);
1712 * Get dynamic class handler.
1714 * @return string
1716 protected function get_handler() {
1717 $tableclass = explode("\\", get_class($this));
1718 return end($tableclass);
1722 * Get the dynamic table start wrapper.
1723 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1725 * @return string
1727 protected function get_dynamic_table_html_start(): string {
1728 if (is_a($this, \core_table\dynamic::class)) {
1729 $sortdata = array_map(function($sortby, $sortorder) {
1730 return [
1731 'sortby' => $sortby,
1732 'sortorder' => $sortorder,
1734 }, array_keys($this->prefs['sortby']), array_values($this->prefs['sortby']));;
1736 return html_writer::start_tag('div', [
1737 'class' => 'table-dynamic position-relative',
1738 'data-region' => 'core_table/dynamic',
1739 'data-table-handler' => $this->get_handler(),
1740 'data-table-component' => $this->get_component(),
1741 'data-table-uniqueid' => $this->uniqueid,
1742 'data-table-filters' => json_encode($this->get_filterset()),
1743 'data-table-sort-data' => json_encode($sortdata),
1744 'data-table-first-initial' => $this->prefs['i_first'],
1745 'data-table-last-initial' => $this->prefs['i_last'],
1746 'data-table-page-number' => $this->currpage + 1,
1747 'data-table-page-size' => $this->pagesize,
1748 'data-table-default-per-page' => $this->get_default_per_page(),
1749 'data-table-hidden-columns' => json_encode(array_keys($this->prefs['collapse'])),
1750 'data-table-total-rows' => $this->totalrows,
1754 return '';
1758 * Get the dynamic table end wrapper.
1759 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1761 * @return string
1763 protected function get_dynamic_table_html_end(): string {
1764 global $PAGE;
1766 if (is_a($this, \core_table\dynamic::class)) {
1767 $output = '';
1769 $perpageurl = new moodle_url($PAGE->url);
1771 // Generate "Show all/Show per page" link.
1772 if ($this->pagesize == TABLE_SHOW_ALL_PAGE_SIZE && $this->totalrows > $this->get_default_per_page()) {
1773 $perpagesize = $this->get_default_per_page();
1774 $perpagestring = get_string('showperpage', '', $this->get_default_per_page());
1775 } else if ($this->pagesize < $this->totalrows) {
1776 $perpagesize = TABLE_SHOW_ALL_PAGE_SIZE;
1777 $perpagestring = get_string('showall', '', $this->totalrows);
1779 if (isset($perpagesize) && isset($perpagestring)) {
1780 $perpageurl->param('perpage', $perpagesize);
1781 $output .= html_writer::link(
1782 $perpageurl,
1783 $perpagestring,
1785 'data-action' => 'showcount',
1786 'data-target-page-size' => $perpagesize,
1791 $PAGE->requires->js_call_amd('core_table/dynamic', 'init');
1792 $output .= html_writer::end_tag('div');
1793 return $output;
1796 return '';
1800 * This function is not part of the public api.
1802 function start_html() {
1803 global $OUTPUT;
1805 // Render the dynamic table header.
1806 echo $this->get_dynamic_table_html_start();
1808 // Render button to allow user to reset table preferences.
1809 echo $this->render_reset_button();
1811 // Do we need to print initial bars?
1812 $this->print_initials_bar();
1814 // Paging bar
1815 if ($this->use_pages) {
1816 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1817 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1818 echo $OUTPUT->render($pagingbar);
1821 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1822 echo $this->download_buttons();
1825 $this->wrap_html_start();
1826 // Start of main data table
1828 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1829 echo html_writer::start_tag('table', $this->attributes);
1834 * This function is not part of the public api.
1835 * @param array $styles CSS-property => value
1836 * @return string values suitably to go in a style="" attribute in HTML.
1838 function make_styles_string($styles) {
1839 if (empty($styles)) {
1840 return null;
1843 $string = '';
1844 foreach($styles as $property => $value) {
1845 $string .= $property . ':' . $value . ';';
1847 return $string;
1851 * Generate the HTML for the table preferences reset button.
1853 * @return string HTML fragment, empty string if no need to reset
1855 protected function render_reset_button() {
1857 if (!$this->can_be_reset()) {
1858 return '';
1861 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1863 $html = html_writer::start_div('resettable mdl-right');
1864 $html .= html_writer::link($url, get_string('resettable'));
1865 $html .= html_writer::end_div();
1867 return $html;
1871 * Are there some table preferences that can be reset?
1873 * If true, then the "reset table preferences" widget should be displayed.
1875 * @return bool
1877 protected function can_be_reset() {
1878 // Loop through preferences and make sure they are empty or set to the default value.
1879 foreach ($this->prefs as $prefname => $prefval) {
1880 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1881 // Check if the actual sorting differs from the default one.
1882 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1883 return true;
1886 } else if ($prefname === 'collapse' and !empty($prefval)) {
1887 // Check if there are some collapsed columns (all are expanded by default).
1888 foreach ($prefval as $columnname => $iscollapsed) {
1889 if ($iscollapsed) {
1890 return true;
1894 } else if (!empty($prefval)) {
1895 // For all other cases, we just check if some preference is set.
1896 return true;
1900 return false;
1904 * Get the context for the table.
1906 * Note: This function _must_ be overridden by dynamic tables to ensure that the context is correctly determined
1907 * from the filterset parameters.
1909 * @return context
1911 public function get_context(): context {
1912 global $PAGE;
1914 if (is_a($this, \core_table\dynamic::class)) {
1915 throw new coding_exception('The get_context function must be defined for a dynamic table');
1918 return $PAGE->context;
1922 * Set the filterset in the table class.
1924 * The use of filtersets is a requirement for dynamic tables, but can be used by other tables too if desired.
1926 * @param filterset $filterset The filterset object to get filters and table parameters from
1928 public function set_filterset(filterset $filterset): void {
1929 $this->filterset = $filterset;
1931 $this->guess_base_url();
1935 * Get the currently defined filterset.
1937 * @return filterset
1939 public function get_filterset(): ?filterset {
1940 return $this->filterset;
1944 * Attempt to guess the base URL.
1946 public function guess_base_url(): void {
1947 if (is_a($this, \core_table\dynamic::class)) {
1948 throw new coding_exception('The guess_base_url function must be defined for a dynamic table');
1955 * @package moodlecore
1956 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1957 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1959 class table_sql extends flexible_table {
1961 public $countsql = NULL;
1962 public $countparams = NULL;
1964 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1966 public $sql = NULL;
1968 * @var array|\Traversable Data fetched from the db.
1970 public $rawdata = NULL;
1973 * @var bool Overriding default for this.
1975 public $is_sortable = true;
1977 * @var bool Overriding default for this.
1979 public $is_collapsible = true;
1982 * @param string $uniqueid a string identifying this table.Used as a key in
1983 * session vars.
1985 function __construct($uniqueid) {
1986 parent::__construct($uniqueid);
1987 // some sensible defaults
1988 $this->set_attribute('class', 'generaltable generalbox');
1992 * Take the data returned from the db_query and go through all the rows
1993 * processing each col using either col_{columnname} method or other_cols
1994 * method or if other_cols returns NULL then put the data straight into the
1995 * table.
1997 * After calling this function, don't forget to call close_recordset.
1999 public function build_table() {
2001 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
2002 return;
2004 if (!$this->rawdata) {
2005 return;
2008 foreach ($this->rawdata as $row) {
2009 $formattedrow = $this->format_row($row);
2010 $this->add_data_keyed($formattedrow,
2011 $this->get_row_class($row));
2016 * Closes recordset (for use after building the table).
2018 public function close_recordset() {
2019 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
2020 $this->rawdata instanceof moodle_recordset)) {
2021 $this->rawdata->close();
2022 $this->rawdata = null;
2027 * Get any extra classes names to add to this row in the HTML.
2028 * @param $row array the data for this row.
2029 * @return string added to the class="" attribute of the tr.
2031 function get_row_class($row) {
2032 return '';
2036 * This is only needed if you want to use different sql to count rows.
2037 * Used for example when perhaps all db JOINS are not needed when counting
2038 * records. You don't need to call this function the count_sql
2039 * will be generated automatically.
2041 * We need to count rows returned by the db seperately to the query itself
2042 * as we need to know how many pages of data we have to display.
2044 function set_count_sql($sql, array $params = NULL) {
2045 $this->countsql = $sql;
2046 $this->countparams = $params;
2050 * Set the sql to query the db. Query will be :
2051 * SELECT $fields FROM $from WHERE $where
2052 * Of course you can use sub-queries, JOINS etc. by putting them in the
2053 * appropriate clause of the query.
2055 function set_sql($fields, $from, $where, array $params = array()) {
2056 $this->sql = new stdClass();
2057 $this->sql->fields = $fields;
2058 $this->sql->from = $from;
2059 $this->sql->where = $where;
2060 $this->sql->params = $params;
2064 * Query the db. Store results in the table object for use by build_table.
2066 * @param int $pagesize size of page for paginated displayed table.
2067 * @param bool $useinitialsbar do you want to use the initials bar. Bar
2068 * will only be used if there is a fullname column defined for the table.
2070 function query_db($pagesize, $useinitialsbar=true) {
2071 global $DB;
2072 if (!$this->is_downloading()) {
2073 if ($this->countsql === NULL) {
2074 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
2075 $this->countparams = $this->sql->params;
2077 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
2078 if ($useinitialsbar && !$this->is_downloading()) {
2079 $this->initialbars(true);
2082 list($wsql, $wparams) = $this->get_sql_where();
2083 if ($wsql) {
2084 $this->countsql .= ' AND '.$wsql;
2085 $this->countparams = array_merge($this->countparams, $wparams);
2087 $this->sql->where .= ' AND '.$wsql;
2088 $this->sql->params = array_merge($this->sql->params, $wparams);
2090 $total = $DB->count_records_sql($this->countsql, $this->countparams);
2091 } else {
2092 $total = $grandtotal;
2095 $this->pagesize($pagesize, $total);
2098 // Fetch the attempts
2099 $sort = $this->get_sql_sort();
2100 if ($sort) {
2101 $sort = "ORDER BY $sort";
2103 $sql = "SELECT
2104 {$this->sql->fields}
2105 FROM {$this->sql->from}
2106 WHERE {$this->sql->where}
2107 {$sort}";
2109 if (!$this->is_downloading()) {
2110 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
2111 } else {
2112 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
2117 * Convenience method to call a number of methods for you to display the
2118 * table.
2120 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
2121 global $DB;
2122 if (!$this->columns) {
2123 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
2124 $this->sql->params, IGNORE_MULTIPLE);
2125 //if columns is not set then define columns as the keys of the rows returned
2126 //from the db.
2127 $this->define_columns(array_keys((array)$onerow));
2128 $this->define_headers(array_keys((array)$onerow));
2130 $this->pagesize = $pagesize;
2131 $this->setup();
2132 $this->query_db($pagesize, $useinitialsbar);
2133 $this->build_table();
2134 $this->close_recordset();
2135 $this->finish_output();
2141 * @package moodlecore
2142 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2145 class table_default_export_format_parent {
2147 * @var flexible_table or child class reference pointing to table class
2148 * object from which to export data.
2150 var $table;
2153 * @var bool output started. Keeps track of whether any output has been
2154 * started yet.
2156 var $documentstarted = false;
2159 * Constructor
2161 * @param flexible_table $table
2163 public function __construct(&$table) {
2164 $this->table =& $table;
2168 * Old syntax of class constructor. Deprecated in PHP7.
2170 * @deprecated since Moodle 3.1
2172 public function table_default_export_format_parent(&$table) {
2173 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2174 self::__construct($table);
2177 function set_table(&$table) {
2178 $this->table =& $table;
2181 function add_data($row) {
2182 return false;
2185 function add_seperator() {
2186 return false;
2189 function document_started() {
2190 return $this->documentstarted;
2193 * Given text in a variety of format codings, this function returns
2194 * the text as safe HTML or as plain text dependent on what is appropriate
2195 * for the download format. The default removes all tags.
2197 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
2198 //use some whitespace to indicate where there was some line spacing.
2199 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
2200 return strip_tags($text);
2205 * Dataformat exporter
2207 * @package core
2208 * @subpackage tablelib
2209 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
2210 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2212 class table_dataformat_export_format extends table_default_export_format_parent {
2214 /** @var \core\dataformat\base $dataformat */
2215 protected $dataformat;
2217 /** @var $rownum */
2218 protected $rownum = 0;
2220 /** @var $columns */
2221 protected $columns;
2224 * Constructor
2226 * @param string $table An sql table
2227 * @param string $dataformat type of dataformat for export
2229 public function __construct(&$table, $dataformat) {
2230 parent::__construct($table);
2232 if (ob_get_length()) {
2233 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
2236 $classname = 'dataformat_' . $dataformat . '\writer';
2237 if (!class_exists($classname)) {
2238 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
2240 $this->dataformat = new $classname;
2242 // The dataformat export time to first byte could take a while to generate...
2243 set_time_limit(0);
2245 // Close the session so that the users other tabs in the same session are not blocked.
2246 \core\session\manager::write_close();
2250 * Whether the current dataformat supports export of HTML
2252 * @return bool
2254 public function supports_html(): bool {
2255 return $this->dataformat->supports_html();
2259 * Start document
2261 * @param string $filename
2262 * @param string $sheettitle
2264 public function start_document($filename, $sheettitle) {
2265 $this->documentstarted = true;
2266 $this->dataformat->set_filename($filename);
2267 $this->dataformat->send_http_headers();
2268 $this->dataformat->set_sheettitle($sheettitle);
2269 $this->dataformat->start_output();
2273 * Start export
2275 * @param string $sheettitle optional spreadsheet worksheet title
2277 public function start_table($sheettitle) {
2278 $this->dataformat->set_sheettitle($sheettitle);
2282 * Output headers
2284 * @param array $headers
2286 public function output_headers($headers) {
2287 $this->columns = $headers;
2288 if (method_exists($this->dataformat, 'write_header')) {
2289 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
2290 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
2291 $this->dataformat->write_header($headers);
2292 } else {
2293 $this->dataformat->start_sheet($headers);
2298 * Add a row of data
2300 * @param array $row One record of data
2302 public function add_data($row) {
2303 $this->dataformat->write_record($row, $this->rownum++);
2304 return true;
2308 * Finish export
2310 public function finish_table() {
2311 if (method_exists($this->dataformat, 'write_footer')) {
2312 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
2313 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
2314 $this->dataformat->write_footer($this->columns);
2315 } else {
2316 $this->dataformat->close_sheet($this->columns);
2321 * Finish download
2323 public function finish_document() {
2324 $this->dataformat->close_output();
2325 exit();