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);
52 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class flexible_table {
58 var $attributes = array();
59 var $headers = array();
62 * @var string A column which should be considered as a header column.
64 protected $headercolumn = null;
67 * @var string For create header with help icon.
69 private $helpforheaders = array();
70 var $columns = array();
71 var $column_style = array();
72 var $column_class = array();
73 var $column_suppress = array();
74 var $column_nosort = array('userpic');
75 private $column_textsort = array();
76 /** @var boolean Stores if setup has already been called on this flixible table. */
79 var $request = array();
82 * @var bool Whether or not to store table properties in the user_preferences table.
84 private $persistent = false;
85 var $is_collapsible = false;
86 var $is_sortable = false;
89 * @var string The field name to sort by.
94 * @var string $sortorder The direction for sorting.
98 /** @var string The manually set first name initial preference */
101 /** @var string The manually set last name initial preference */
104 var $use_pages = false;
105 var $use_initials = false;
107 var $maxsortkeys = 2;
112 var $sort_default_column = NULL;
113 var $sort_default_order = SORT_ASC;
116 * Array of positions in which to display download controls.
118 var $showdownloadbuttonsat= array(TABLE_P_TOP);
121 * @var string Key of field returned by db query that is the id field of the
122 * user table or equivalent.
124 public $useridfield = 'id';
127 * @var string which download plugin to use. Default '' means none - print
128 * html table with paging. Property set by is_downloading which typically
129 * passes in cleaned data from $
134 * @var bool whether data is downloadable from table. Determines whether
135 * to display download buttons. Set by method downloadable().
137 var $downloadable = false;
140 * @var bool Has start output been called yet?
142 var $started_output = false;
144 var $exportclass = null;
147 * @var array For storing user-customised table properties in the user_preferences db table.
149 private $prefs = array();
151 /** @var $sheettitle */
152 protected $sheettitle;
154 /** @var $filename */
159 * @param string $uniqueid all tables have to have a unique id, this is used
160 * as a key when storing table properties like sort order in the session.
162 function __construct($uniqueid) {
163 $this->uniqueid = $uniqueid;
164 $this->request = array(
165 TABLE_VAR_SORT => 'tsort',
166 TABLE_VAR_HIDE => 'thide',
167 TABLE_VAR_SHOW => 'tshow',
168 TABLE_VAR_IFIRST => 'tifirst',
169 TABLE_VAR_ILAST => 'tilast',
170 TABLE_VAR_PAGE => 'page',
171 TABLE_VAR_RESET => 'treset',
172 TABLE_VAR_DIR => 'tdir',
177 * Call this to pass the download type. Use :
178 * $download = optional_param('download', '', PARAM_ALPHA);
179 * To get the download type. We assume that if you call this function with
180 * params that this table's data is downloadable, so we call is_downloadable
181 * for you (even if the param is '', which means no download this time.
182 * Also you can call this method with no params to get the current set
184 * @param string $download dataformat type. One of csv, xhtml, ods, etc
185 * @param string $filename filename for downloads without file extension.
186 * @param string $sheettitle title for downloaded data.
187 * @return string download dataformat type. One of csv, xhtml, ods, etc
189 function is_downloading($download = null, $filename='', $sheettitle='') {
190 if ($download!==null) {
191 $this->sheettitle = $sheettitle;
192 $this->is_downloadable(true);
193 $this->download = $download;
194 $this->filename = clean_filename($filename);
195 $this->export_class_instance();
197 return $this->download;
201 * Get, and optionally set, the export class.
202 * @param $exportclass (optional) if passed, set the table to use this export class.
203 * @return table_default_export_format_parent the export class in use (after any set).
205 function export_class_instance($exportclass = null) {
206 if (!is_null($exportclass)) {
207 $this->started_output = true;
208 $this->exportclass = $exportclass;
209 $this->exportclass->table = $this;
210 } else if (is_null($this->exportclass) && !empty($this->download)) {
211 $this->exportclass = new table_dataformat_export_format($this, $this->download);
212 if (!$this->exportclass->document_started()) {
213 $this->exportclass->start_document($this->filename, $this->sheettitle);
216 return $this->exportclass;
220 * Probably don't need to call this directly. Calling is_downloading with a
221 * param automatically sets table as downloadable.
223 * @param bool $downloadable optional param to set whether data from
224 * table is downloadable. If ommitted this function can be used to get
225 * current state of table.
226 * @return bool whether table data is set to be downloadable.
228 function is_downloadable($downloadable = null) {
229 if ($downloadable !== null) {
230 $this->downloadable = $downloadable;
232 return $this->downloadable;
236 * Call with boolean true to store table layout changes in the user_preferences table.
237 * Note: user_preferences.value has a maximum length of 1333 characters.
238 * Call with no parameter to get current state of table persistence.
240 * @param bool $persistent Optional parameter to set table layout persistence.
241 * @return bool Whether or not the table layout preferences will persist.
243 public function is_persistent($persistent = null) {
244 if ($persistent == true) {
245 $this->persistent = true;
247 return $this->persistent;
251 * Where to show download buttons.
252 * @param array $showat array of postions in which to show download buttons.
253 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
255 function show_download_buttons_at($showat) {
256 $this->showdownloadbuttonsat = $showat;
260 * Sets the is_sortable variable to the given boolean, sort_default_column to
261 * the given string, and the sort_default_order to the given integer.
263 * @param string $defaultcolumn
264 * @param int $defaultorder
267 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
268 $this->is_sortable = $bool;
269 $this->sort_default_column = $defaultcolumn;
270 $this->sort_default_order = $defaultorder;
274 * Use text sorting functions for this column (required for text columns with Oracle).
275 * Be warned that you cannot use this with column aliases. You can only do this
276 * with real columns. See MDL-40481 for an example.
277 * @param string column name
279 function text_sorting($column) {
280 $this->column_textsort[] = $column;
284 * Do not sort using this column
285 * @param string column name
287 function no_sorting($column) {
288 $this->column_nosort[] = $column;
292 * Is the column sortable?
293 * @param string column name, null means table
296 function is_sortable($column = null) {
297 if (empty($column)) {
298 return $this->is_sortable;
300 if (!$this->is_sortable) {
303 return !in_array($column, $this->column_nosort);
307 * Sets the is_collapsible variable to the given boolean.
311 function collapsible($bool) {
312 $this->is_collapsible = $bool;
316 * Sets the use_pages variable to the given boolean.
320 function pageable($bool) {
321 $this->use_pages = $bool;
325 * Sets the use_initials variable to the given boolean.
329 function initialbars($bool) {
330 $this->use_initials = $bool;
334 * Sets the pagesize variable to the given integer, the totalrows variable
335 * to the given integer, and the use_pages variable to true.
336 * @param int $perpage
340 function pagesize($perpage, $total) {
341 $this->pagesize = $perpage;
342 $this->totalrows = $total;
343 $this->use_pages = true;
347 * Assigns each given variable in the array to the corresponding index
348 * in the request class variable.
349 * @param array $variables
352 function set_control_variables($variables) {
353 foreach ($variables as $what => $variable) {
354 if (isset($this->request[$what])) {
355 $this->request[$what] = $variable;
361 * Gives the given $value to the $attribute index of $this->attributes.
362 * @param string $attribute
363 * @param mixed $value
366 function set_attribute($attribute, $value) {
367 $this->attributes[$attribute] = $value;
371 * What this method does is set the column so that if the same data appears in
372 * consecutive rows, then it is not repeated.
374 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
375 * that when one student has made multiple attempts, their name is only printed in the row
376 * for their first attempt.
377 * @param int $column the index of a column.
379 function column_suppress($column) {
380 if (isset($this->column_suppress[$column])) {
381 $this->column_suppress[$column] = true;
386 * Sets the given $column index to the given $classname in $this->column_class.
388 * @param string $classname
391 function column_class($column, $classname) {
392 if (isset($this->column_class[$column])) {
393 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
398 * Sets the given $column index and $property index to the given $value in $this->column_style.
400 * @param string $property
401 * @param mixed $value
404 function column_style($column, $property, $value) {
405 if (isset($this->column_style[$column])) {
406 $this->column_style[$column][$property] = $value;
411 * Sets all columns' $propertys to the given $value in $this->column_style.
412 * @param int $property
413 * @param string $value
416 function column_style_all($property, $value) {
417 foreach (array_keys($this->columns) as $column) {
418 $this->column_style[$column][$property] = $value;
423 * Sets $this->baseurl.
424 * @param moodle_url|string $url the url with params needed to call up this page
426 function define_baseurl($url) {
427 $this->baseurl = new moodle_url($url);
431 * @param array $columns an array of identifying names for columns. If
432 * columns are sorted then column names must correspond to a field in sql.
434 function define_columns($columns) {
435 $this->columns = array();
436 $this->column_style = array();
437 $this->column_class = array();
440 foreach ($columns as $column) {
441 $this->columns[$column] = $colnum++;
442 $this->column_style[$column] = array();
443 $this->column_class[$column] = '';
444 $this->column_suppress[$column] = false;
449 * @param array $headers numerical keyed array of displayed string titles
452 function define_headers($headers) {
453 $this->headers = $headers;
457 * Mark a specific column as being a table header using the column name defined in define_columns.
459 * Note: Only one column can be a header, and it will be rendered using a th tag.
461 * @param string $column
463 public function define_header_column(string $column) {
464 $this->headercolumn = $column;
468 * Defines a help icon for the header
470 * Always use this function if you need to create header with sorting and help icon.
472 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
474 public function define_help_for_headers($helpicons) {
475 $this->helpforheaders = $helpicons;
479 * Must be called after table is defined. Use methods above first. Cannot
480 * use functions below till after calling this method.
486 if (empty($this->columns) || empty($this->uniqueid)) {
490 // Load any existing user preferences.
491 if ($this->persistent) {
492 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
493 $oldprefs = $this->prefs;
494 } else if (isset($SESSION->flextable[$this->uniqueid])) {
495 $this->prefs = $SESSION->flextable[$this->uniqueid];
496 $oldprefs = $this->prefs;
499 // Set up default preferences if needed.
500 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
501 $this->prefs = array(
502 'collapse' => array(),
506 'textsort' => $this->column_textsort,
510 if (!isset($oldprefs)) {
511 $oldprefs = $this->prefs;
514 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
515 isset($this->columns[$showcol])) {
516 $this->prefs['collapse'][$showcol] = false;
518 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
519 isset($this->columns[$hidecol])) {
520 $this->prefs['collapse'][$hidecol] = true;
521 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
522 unset($this->prefs['sortby'][$hidecol]);
526 // Now, update the column attributes for collapsed columns
527 foreach (array_keys($this->columns) as $column) {
528 if (!empty($this->prefs['collapse'][$column])) {
529 $this->column_style[$column]['width'] = '10px';
533 $this->set_sorting_preferences();
534 $this->set_initials_preferences();
536 // Save user preferences if they have changed.
537 if ($this->prefs != $oldprefs) {
538 if ($this->persistent) {
539 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
541 $SESSION->flextable[$this->uniqueid] = $this->prefs;
546 if (empty($this->baseurl)) {
547 debugging('You should set baseurl when using flexible_table.');
549 $this->baseurl = $PAGE->url;
552 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
555 // Always introduce the "flexible" class for the table if not specified
556 if (empty($this->attributes)) {
557 $this->attributes['class'] = 'flexible table table-striped table-hover';
558 } else if (!isset($this->attributes['class'])) {
559 $this->attributes['class'] = 'flexible table table-striped table-hover';
560 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
561 $this->attributes['class'] = trim('flexible table table-striped table-hover ' . $this->attributes['class']);
566 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
567 * @param string $uniqueid the identifier for a table.
568 * @return SQL fragment that can be used in an ORDER BY clause.
570 public static function get_sort_for_table($uniqueid) {
572 if (isset($SESSION->flextable[$uniqueid])) {
573 $prefs = $SESSION->flextable[$uniqueid];
574 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
578 if (empty($prefs['sortby'])) {
581 if (empty($prefs['textsort'])) {
582 $prefs['textsort'] = array();
585 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
589 * Prepare an an order by clause from the list of columns to be sorted.
590 * @param array $cols column name => SORT_ASC or SORT_DESC
591 * @return SQL fragment that can be used in an ORDER BY clause.
593 public static function construct_order_by($cols, $textsortcols=array()) {
597 foreach ($cols as $column => $order) {
598 if (in_array($column, $textsortcols)) {
599 $column = $DB->sql_order_by_text($column);
601 if ($order == SORT_ASC) {
602 $bits[] = $column . ' ASC';
604 $bits[] = $column . ' DESC';
608 return implode(', ', $bits);
612 * @return SQL fragment that can be used in an ORDER BY clause.
614 public function get_sql_sort() {
615 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
619 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
620 * @return array column name => SORT_... constant.
622 public function get_sort_columns() {
624 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
627 if (empty($this->prefs['sortby'])) {
631 foreach ($this->prefs['sortby'] as $column => $notused) {
632 if (isset($this->columns[$column])) {
633 continue; // This column is OK.
635 if (in_array($column, get_all_user_name_fields()) &&
636 isset($this->columns['fullname'])) {
637 continue; // This column is OK.
639 // This column is not OK.
640 unset($this->prefs['sortby'][$column]);
643 return $this->prefs['sortby'];
647 * @return int the offset for LIMIT clause of SQL
649 function get_page_start() {
650 if (!$this->use_pages) {
653 return $this->currpage * $this->pagesize;
657 * @return int the pagesize for LIMIT clause of SQL
659 function get_page_size() {
660 if (!$this->use_pages) {
663 return $this->pagesize;
667 * @return string sql to add to where statement.
669 function get_sql_where() {
672 $conditions = array();
675 if (isset($this->columns['fullname'])) {
679 if (!empty($this->prefs['i_first'])) {
680 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
681 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
683 if (!empty($this->prefs['i_last'])) {
684 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
685 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
689 return array(implode(" AND ", $conditions), $params);
693 * Add a row of data to the table. This function takes an array or object with
694 * column names as keys or property names.
696 * It ignores any elements with keys that are not defined as columns. It
697 * puts in empty strings into the row when there is no element in the passed
698 * array corresponding to a column in the table. It puts the row elements in
699 * the proper order (internally row table data is stored by in arrays with
700 * a numerical index corresponding to the column number).
702 * @param object|array $rowwithkeys array keys or object property names are column names,
703 * as defined in call to define_columns.
704 * @param string $classname CSS class name to add to this row's tr tag.
706 function add_data_keyed($rowwithkeys, $classname = '') {
707 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
711 * Add a number of rows to the table at once. And optionally finish output after they have been added.
713 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
714 * object or array is added to table. We expect properties for the row array as would be
715 * passed to add_data_keyed.
716 * @param bool $finish
718 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
719 foreach ($rowstoadd as $row) {
721 $this->add_separator();
723 $this->add_data_keyed($this->format_row($row));
727 $this->finish_output(!$this->is_downloading());
732 * Add a seperator line to table.
734 function add_separator() {
738 $this->add_data(NULL);
742 * This method actually directly echoes the row passed to it now or adds it
743 * to the download. If this is the first row and start_output has not
744 * already been called this method also calls start_output to open the table
745 * or send headers for the downloaded.
746 * Can be used as before. print_html now calls finish_html to close table.
748 * @param array $row a numerically keyed row of data to add to the table.
749 * @param string $classname CSS class name to add to this row's tr tag.
750 * @return bool success.
752 function add_data($row, $classname = '') {
756 if (!$this->started_output) {
757 $this->start_output();
759 if ($this->exportclass!==null) {
761 $this->exportclass->add_seperator();
763 $this->exportclass->add_data($row);
766 $this->print_row($row, $classname);
772 * You should call this to finish outputting the table data after adding
773 * data to the table with add_data or add_data_keyed.
776 function finish_output($closeexportclassdoc = true) {
777 if ($this->exportclass!==null) {
778 $this->exportclass->finish_table();
779 if ($closeexportclassdoc) {
780 $this->exportclass->finish_document();
783 $this->finish_html();
788 * Hook that can be overridden in child classes to wrap a table in a form
789 * for example. Called only when there is data to display and not
792 function wrap_html_start() {
796 * Hook that can be overridden in child classes to wrap a table in a form
797 * for example. Called only when there is data to display and not
800 function wrap_html_finish() {
804 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
805 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
806 * displaying table as html, adding a div wrap, etc.
808 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
810 * @param array|object $row row of data from db used to make one row of the table.
811 * @return array one row for the table, added using add_data_keyed method.
813 function format_row($row) {
814 if (is_array($row)) {
817 $formattedrow = array();
818 foreach (array_keys($this->columns) as $column) {
819 $colmethodname = 'col_'.$column;
820 if (method_exists($this, $colmethodname)) {
821 $formattedcolumn = $this->$colmethodname($row);
823 $formattedcolumn = $this->other_cols($column, $row);
824 if ($formattedcolumn===NULL) {
825 $formattedcolumn = $row->$column;
828 $formattedrow[$column] = $formattedcolumn;
830 return $formattedrow;
834 * Fullname is treated as a special columname in tablelib and should always
835 * be treated the same as the fullname of a user.
836 * @uses $this->useridfield if the userid field is not expected to be id
837 * then you need to override $this->useridfield to point at the correct
838 * field for the user id.
840 * @param object $row the data from the db containing all fields from the
841 * users table necessary to construct the full name of the user in
843 * @return string contents of cell in column 'fullname', for this row.
845 function col_fullname($row) {
846 global $PAGE, $COURSE;
848 $name = fullname($row, has_capability('moodle/site:viewfullnames', $PAGE->context));
849 if ($this->download) {
853 $userid = $row->{$this->useridfield};
854 if ($COURSE->id == SITEID) {
855 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
857 $profileurl = new moodle_url('/user/view.php',
858 array('id' => $userid, 'course' => $COURSE->id));
860 return html_writer::link($profileurl, $name);
864 * You can override this method in a child class. See the description of
865 * build_table which calls this method.
867 function other_cols($column, $row) {
872 * Used from col_* functions when text is to be displayed. Does the
873 * right thing - either converts text to html or strips any html tags
874 * depending on if we are downloading and what is the download type. Params
875 * are the same as format_text function in weblib.php but some default
876 * options are changed.
878 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
879 if (!$this->is_downloading()) {
880 if (is_null($options)) {
881 $options = new stdClass;
883 //some sensible defaults
884 if (!isset($options->para)) {
885 $options->para = false;
887 if (!isset($options->newlines)) {
888 $options->newlines = false;
890 if (!isset($options->smiley)) {
891 $options->smiley = false;
893 if (!isset($options->filter)) {
894 $options->filter = false;
896 return format_text($text, $format, $options);
898 $eci = $this->export_class_instance();
899 return $eci->format_text($text, $format, $options, $courseid);
903 * This method is deprecated although the old api is still supported.
904 * @deprecated 1.9.2 - Jun 2, 2008
906 function print_html() {
910 $this->finish_html();
914 * This function is not part of the public api.
915 * @return string initial of first name we are currently filtering by
917 function get_initial_first() {
918 if (!$this->use_initials) {
922 return $this->prefs['i_first'];
926 * This function is not part of the public api.
927 * @return string initial of last name we are currently filtering by
929 function get_initial_last() {
930 if (!$this->use_initials) {
934 return $this->prefs['i_last'];
938 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
939 * @param array $alpha of letters in the alphabet.
940 * @param string $current the currently selected letter.
941 * @param string $class class name to add to this initial bar.
942 * @param string $title the name to put in front of this initial bar.
943 * @param string $urlvar URL parameter name for this initial.
945 * @deprecated since Moodle 3.3
947 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
949 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
950 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
952 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
955 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
957 echo html_writer::tag('strong', get_string('all'));
960 foreach ($alpha as $letter) {
961 if ($letter === $current) {
962 echo html_writer::tag('strong', $letter);
964 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
968 echo html_writer::end_tag('div');
972 * This function is not part of the public api.
974 function print_initials_bar() {
977 $ifirst = $this->get_initial_first();
978 $ilast = $this->get_initial_last();
979 if (is_null($ifirst)) {
982 if (is_null($ilast)) {
986 if ((!empty($ifirst) || !empty($ilast) ||$this->use_initials)
987 && isset($this->columns['fullname'])) {
988 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
989 $prefixlast = $this->request[TABLE_VAR_ILAST];
990 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
991 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
997 * This function is not part of the public api.
999 function print_nothing_to_display() {
1002 // Render the dynamic table header.
1003 echo $this->get_dynamic_table_html_start();
1005 // Render button to allow user to reset table preferences.
1006 echo $this->render_reset_button();
1008 $this->print_initials_bar();
1010 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1012 // Render the dynamic table footer.
1013 echo $this->get_dynamic_table_html_end();
1017 * This function is not part of the public api.
1019 function get_row_from_keyed($rowwithkeys) {
1020 if (is_object($rowwithkeys)) {
1021 $rowwithkeys = (array)$rowwithkeys;
1024 foreach (array_keys($this->columns) as $column) {
1025 if (isset($rowwithkeys[$column])) {
1026 $row [] = $rowwithkeys[$column];
1035 * Get the html for the download buttons
1037 * Usually only use internally
1039 public function download_buttons() {
1042 if ($this->is_downloadable() && !$this->is_downloading()) {
1043 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1044 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1051 * This function is not part of the public api.
1052 * You don't normally need to call this. It is called automatically when
1053 * needed when you start adding data to the table.
1056 function start_output() {
1057 $this->started_output = true;
1058 if ($this->exportclass!==null) {
1059 $this->exportclass->start_table($this->sheettitle);
1060 $this->exportclass->output_headers($this->headers);
1062 $this->start_html();
1063 $this->print_headers();
1064 echo html_writer::start_tag('tbody');
1069 * This function is not part of the public api.
1071 function print_row($row, $classname = '') {
1072 echo $this->get_row_html($row, $classname);
1076 * Generate html code for the passed row.
1078 * @param array $row Row data.
1079 * @param string $classname classes to add.
1081 * @return string $html html code for the row passed.
1083 public function get_row_html($row, $classname = '') {
1084 static $suppress_lastrow = NULL;
1085 $rowclasses = array();
1088 $rowclasses[] = $classname;
1091 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1094 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1096 // If we have a separator, print it
1097 if ($row === NULL) {
1098 $colcount = count($this->columns);
1099 $html .= html_writer::tag('td', html_writer::tag('div', '',
1100 array('class' => 'tabledivider')), array('colspan' => $colcount));
1103 $colbyindex = array_flip($this->columns);
1104 foreach ($row as $index => $data) {
1105 $column = $colbyindex[$index];
1108 'class' => "cell c{$index}" . $this->column_class[$column],
1109 'id' => "{$rowid}_c{$index}",
1110 'style' => $this->make_styles_string($this->column_style[$column]),
1114 if ($this->headercolumn && $column == $this->headercolumn) {
1116 $attributes['scope'] = 'row';
1119 if (empty($this->prefs['collapse'][$column])) {
1120 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1121 $content = ' ';
1126 $content = ' ';
1129 $html .= html_writer::tag($celltype, $content, $attributes);
1133 $html .= html_writer::end_tag('tr');
1135 $suppress_enabled = array_sum($this->column_suppress);
1136 if ($suppress_enabled) {
1137 $suppress_lastrow = $row;
1139 $this->currentrow++;
1144 * This function is not part of the public api.
1146 function finish_html() {
1147 global $OUTPUT, $PAGE;
1149 if (!$this->started_output) {
1150 //no data has been added to the table.
1151 $this->print_nothing_to_display();
1154 // Print empty rows to fill the table to the current pagesize.
1155 // This is done so the header aria-controls attributes do not point to
1156 // non existant elements.
1157 $emptyrow = array_fill(0, count($this->columns), '');
1158 while ($this->currentrow < $this->pagesize) {
1159 $this->print_row($emptyrow, 'emptyrow');
1162 echo html_writer::end_tag('tbody');
1163 echo html_writer::end_tag('table');
1164 echo html_writer::end_tag('div');
1165 $this->wrap_html_finish();
1168 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1169 echo $this->download_buttons();
1172 if($this->use_pages) {
1173 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1174 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1175 echo $OUTPUT->render($pagingbar);
1178 // Render the dynamic table footer.
1179 echo $this->get_dynamic_table_html_end();
1184 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1185 * used by {@link print_headers()}.
1186 * @param string $column the column name, index into various names.
1187 * @param int $index numerical index of the column.
1188 * @return string HTML fragment.
1190 protected function show_hide_link($column, $index) {
1192 // Some headers contain <br /> tags, do not include in title, hence the
1196 for ($i = 0; $i < $this->pagesize; $i++) {
1197 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1200 $ariacontrols = trim($ariacontrols);
1202 if (!empty($this->prefs['collapse'][$column])) {
1203 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1204 'aria-expanded' => 'false',
1205 'aria-controls' => $ariacontrols);
1206 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1207 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1209 } else if ($this->headers[$index] !== NULL) {
1210 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1211 'aria-expanded' => 'true',
1212 'aria-controls' => $ariacontrols);
1213 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1214 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1219 * This function is not part of the public api.
1221 function print_headers() {
1222 global $CFG, $OUTPUT, $PAGE;
1224 echo html_writer::start_tag('thead');
1225 echo html_writer::start_tag('tr');
1226 foreach ($this->columns as $column => $index) {
1229 if ($this->is_collapsible) {
1230 $icon_hide = $this->show_hide_link($column, $index);
1233 $primarysortcolumn = '';
1234 $primarysortorder = '';
1235 if (reset($this->prefs['sortby'])) {
1236 $primarysortcolumn = key($this->prefs['sortby']);
1237 $primarysortorder = current($this->prefs['sortby']);
1243 // Check the full name display for sortable fields.
1244 if (has_capability('moodle/site:viewfullnames', $PAGE->context)) {
1245 $nameformat = $CFG->alternativefullnameformat;
1247 $nameformat = $CFG->fullnamedisplay;
1250 if ($nameformat == 'language') {
1251 $nameformat = get_string('fullnamedisplay');
1254 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1256 if (!empty($requirednames)) {
1257 if ($this->is_sortable($column)) {
1258 // Done this way for the possibility of more than two sortable full name display fields.
1259 $this->headers[$index] = '';
1260 foreach ($requirednames as $name) {
1261 $sortname = $this->sort_link(get_string($name),
1262 $name, $primarysortcolumn === $name, $primarysortorder);
1263 $this->headers[$index] .= $sortname . ' / ';
1266 if (isset($this->helpforheaders[$index])) {
1267 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1269 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1275 // do nothing, do not display sortable links
1279 if ($this->is_sortable($column)) {
1281 if (isset($this->helpforheaders[$index])) {
1282 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1284 $this->headers[$index] = $this->sort_link($this->headers[$index],
1285 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1289 $attributes = array(
1290 'class' => 'header c' . $index . $this->column_class[$column],
1293 if ($this->headers[$index] === NULL) {
1294 $content = ' ';
1295 } else if (!empty($this->prefs['collapse'][$column])) {
1296 $content = $icon_hide;
1298 if (is_array($this->column_style[$column])) {
1299 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1302 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1303 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1305 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1306 $icon_hide, array('class' => 'commands'));
1308 echo html_writer::tag('th', $content, $attributes);
1311 echo html_writer::end_tag('tr');
1312 echo html_writer::end_tag('thead');
1316 * Calculate the preferences for sort order based on user-supplied values and get params.
1318 protected function set_sorting_preferences(): void {
1319 $sortorder = $this->sortorder;
1320 $sortby = $this->sortby;
1322 if ($sortorder === null || $sortby === null) {
1323 $sortorder = optional_param($this->request[TABLE_VAR_DIR], $this->sort_default_order, PARAM_INT);
1324 $sortby = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT);
1327 $isvalidsort = $sortby && $this->is_sortable($sortby);
1328 $isvalidsort = $isvalidsort && empty($this->prefs['collapse'][$sortby]);
1329 $isrealcolumn = isset($this->columns[$sortby]);
1330 $isfullnamefield = isset($this->columns['fullname']) && in_array($sortby, get_all_user_name_fields());
1332 if ($isvalidsort && ($isrealcolumn || $isfullnamefield)) {
1333 if (array_key_exists($sortby, $this->prefs['sortby'])) {
1334 // This key already exists somewhere. Change its sortorder and bring it to the top.
1335 $sortorder = $this->prefs['sortby'][$sortby] = $sortorder;
1336 unset($this->prefs['sortby'][$sortby]);
1337 $this->prefs['sortby'] = array_merge(array($sortby => $sortorder), $this->prefs['sortby']);
1339 // Key doesn't exist, so just add it to the beginning of the array, ascending order.
1340 $this->prefs['sortby'] = array_merge(array($sortby => $sortorder), $this->prefs['sortby']);
1343 // Finally, make sure that no more than $this->maxsortkeys are present into the array.
1344 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
1347 // If a default order is defined and it is not in the current list of order by columns, add it at the end.
1348 // This prevents results from being returned in a random order if the only order by column contains equal values.
1349 if (!empty($this->sort_default_column) && !array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
1350 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
1351 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
1356 * Fill in the preferences for the initials bar.
1358 protected function set_initials_preferences(): void {
1359 $ifirst = $this->ifirst;
1360 $ilast = $this->ilast;
1362 if ($ifirst === null) {
1363 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
1366 if ($ilast === null) {
1367 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
1370 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
1371 $this->prefs['i_first'] = $ifirst;
1374 if (!is_null($ilast) && ($ilast === '' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
1375 $this->prefs['i_last'] = $ilast;
1381 * Set the preferred table sorting attributes.
1383 * @param string $sortby The field to sort by.
1384 * @param int $sortorder The sort order.
1386 public function set_sorting(string $sortby, int $sortorder): void {
1387 $this->sortby = $sortby;
1388 $this->sortorder = $sortorder;
1392 * Set the preferred first name initial in an initials bar.
1394 * @param string $initial The character to set
1396 public function set_first_initial(string $initial): void {
1397 $this->ifirst = $initial;
1401 * Set the preferred last name initial in an initials bar.
1403 * @param string $initial The character to set
1405 public function set_last_initial(string $initial): void {
1406 $this->ilast = $initial;
1410 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1411 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1412 * @param int $order SORT_ASC or SORT_DESC
1413 * @return string HTML fragment.
1415 protected function sort_icon($isprimary, $order) {
1422 if ($order == SORT_ASC) {
1423 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1425 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1430 * Generate the correct tool tip for changing the sort order. This is a
1431 * helper method used by {@link sort_link()}.
1432 * @param bool $isprimary whether the is column is the current primary sort column.
1433 * @param int $order SORT_ASC or SORT_DESC
1434 * @return string the correct title.
1436 protected function sort_order_name($isprimary, $order) {
1437 if ($isprimary && $order != SORT_ASC) {
1438 return get_string('desc');
1440 return get_string('asc');
1445 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1446 * @param string $text the text for the link.
1447 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1448 * @param bool $isprimary whether the is column is the current primary sort column.
1449 * @param int $order SORT_ASC or SORT_DESC
1450 * @return string HTML fragment.
1452 protected function sort_link($text, $column, $isprimary, $order) {
1453 // If we are already sorting by this column, switch direction.
1454 if (array_key_exists($column, $this->prefs['sortby'])) {
1455 $sortorder = $this->prefs['sortby'][$column] == SORT_ASC ? SORT_DESC : SORT_ASC;
1457 $sortorder = $order;
1461 $this->request[TABLE_VAR_SORT] => $column,
1462 $this->request[TABLE_VAR_DIR] => $sortorder,
1465 return html_writer::link($this->baseurl->out(false, $params),
1466 $text . get_accesshide(get_string('sortby') . ' ' .
1467 $text . ' ' . $this->sort_order_name($isprimary, $order)),
1469 'data-sortable' => $this->is_sortable($column),
1470 'data-sortby' => $column,
1471 'data-sortorder' => $sortorder,
1472 ]) . ' ' . $this->sort_icon($isprimary, $order);
1476 * Return sorting attributes values.
1480 protected function get_sort_order(): array {
1481 $sortbys = $this->prefs['sortby'];
1482 $sortby = key($sortbys);
1485 'sortby' => $sortby,
1486 'sortorder' => $sortbys[$sortby],
1491 * Get the dynamic table start wrapper.
1492 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1496 protected function get_dynamic_table_html_start(): string {
1497 if (is_a($this, \core_table\dynamic::class)) {
1498 $sortdata = $this->get_sort_order();
1499 return html_writer::start_tag('div', [
1500 'data-region' => 'core_table/dynamic',
1501 'data-table-handler' => get_class($this),
1502 'data-table-uniqueid' => $this->uniqueid,
1503 'data-table-filters' => json_encode($this->get_filterset()),
1504 'data-table-sort-by' => $sortdata['sortby'],
1505 'data-table-sort-order' => $sortdata['sortorder'],
1506 'data-table-first-initial' => $this->prefs['i_first'],
1507 'data-table-last-initial' => $this->prefs['i_last'],
1515 * Get the dynamic table end wrapper.
1516 * If this is not a dynamic table, then an empty string is returned making this safe to blindly call.
1520 protected function get_dynamic_table_html_end(): string {
1523 if (is_a($this, \core_table\dynamic::class)) {
1524 $PAGE->requires->js_call_amd('core_table/dynamic', 'init');
1525 return html_writer::end_tag('div');
1532 * This function is not part of the public api.
1534 function start_html() {
1537 // Render the dynamic table header.
1538 echo $this->get_dynamic_table_html_start();
1540 // Render button to allow user to reset table preferences.
1541 echo $this->render_reset_button();
1543 // Do we need to print initial bars?
1544 $this->print_initials_bar();
1547 if ($this->use_pages) {
1548 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1549 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1550 echo $OUTPUT->render($pagingbar);
1553 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1554 echo $this->download_buttons();
1557 $this->wrap_html_start();
1558 // Start of main data table
1560 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1561 echo html_writer::start_tag('table', $this->attributes);
1566 * This function is not part of the public api.
1567 * @param array $styles CSS-property => value
1568 * @return string values suitably to go in a style="" attribute in HTML.
1570 function make_styles_string($styles) {
1571 if (empty($styles)) {
1576 foreach($styles as $property => $value) {
1577 $string .= $property . ':' . $value . ';';
1583 * Generate the HTML for the table preferences reset button.
1585 * @return string HTML fragment, empty string if no need to reset
1587 protected function render_reset_button() {
1589 if (!$this->can_be_reset()) {
1593 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1595 $html = html_writer::start_div('resettable mdl-right');
1596 $html .= html_writer::link($url, get_string('resettable'));
1597 $html .= html_writer::end_div();
1603 * Are there some table preferences that can be reset?
1605 * If true, then the "reset table preferences" widget should be displayed.
1609 protected function can_be_reset() {
1610 // Loop through preferences and make sure they are empty or set to the default value.
1611 foreach ($this->prefs as $prefname => $prefval) {
1612 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1613 // Check if the actual sorting differs from the default one.
1614 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1618 } else if ($prefname === 'collapse' and !empty($prefval)) {
1619 // Check if there are some collapsed columns (all are expanded by default).
1620 foreach ($prefval as $columnname => $iscollapsed) {
1626 } else if (!empty($prefval)) {
1627 // For all other cases, we just check if some preference is set.
1638 * @package moodlecore
1639 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1640 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1642 class table_sql extends flexible_table {
1644 public $countsql = NULL;
1645 public $countparams = NULL;
1647 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1651 * @var array|\Traversable Data fetched from the db.
1653 public $rawdata = NULL;
1656 * @var bool Overriding default for this.
1658 public $is_sortable = true;
1660 * @var bool Overriding default for this.
1662 public $is_collapsible = true;
1665 * @param string $uniqueid a string identifying this table.Used as a key in
1668 function __construct($uniqueid) {
1669 parent::__construct($uniqueid);
1670 // some sensible defaults
1671 $this->set_attribute('class', 'generaltable generalbox');
1675 * Take the data returned from the db_query and go through all the rows
1676 * processing each col using either col_{columnname} method or other_cols
1677 * method or if other_cols returns NULL then put the data straight into the
1680 * After calling this function, don't forget to call close_recordset.
1682 public function build_table() {
1684 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1687 if (!$this->rawdata) {
1691 foreach ($this->rawdata as $row) {
1692 $formattedrow = $this->format_row($row);
1693 $this->add_data_keyed($formattedrow,
1694 $this->get_row_class($row));
1699 * Closes recordset (for use after building the table).
1701 public function close_recordset() {
1702 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1703 $this->rawdata instanceof moodle_recordset)) {
1704 $this->rawdata->close();
1705 $this->rawdata = null;
1710 * Get any extra classes names to add to this row in the HTML.
1711 * @param $row array the data for this row.
1712 * @return string added to the class="" attribute of the tr.
1714 function get_row_class($row) {
1719 * This is only needed if you want to use different sql to count rows.
1720 * Used for example when perhaps all db JOINS are not needed when counting
1721 * records. You don't need to call this function the count_sql
1722 * will be generated automatically.
1724 * We need to count rows returned by the db seperately to the query itself
1725 * as we need to know how many pages of data we have to display.
1727 function set_count_sql($sql, array $params = NULL) {
1728 $this->countsql = $sql;
1729 $this->countparams = $params;
1733 * Set the sql to query the db. Query will be :
1734 * SELECT $fields FROM $from WHERE $where
1735 * Of course you can use sub-queries, JOINS etc. by putting them in the
1736 * appropriate clause of the query.
1738 function set_sql($fields, $from, $where, array $params = array()) {
1739 $this->sql = new stdClass();
1740 $this->sql->fields = $fields;
1741 $this->sql->from = $from;
1742 $this->sql->where = $where;
1743 $this->sql->params = $params;
1747 * Query the db. Store results in the table object for use by build_table.
1749 * @param int $pagesize size of page for paginated displayed table.
1750 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1751 * will only be used if there is a fullname column defined for the table.
1753 function query_db($pagesize, $useinitialsbar=true) {
1755 if (!$this->is_downloading()) {
1756 if ($this->countsql === NULL) {
1757 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1758 $this->countparams = $this->sql->params;
1760 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1761 if ($useinitialsbar && !$this->is_downloading()) {
1762 $this->initialbars(true);
1765 list($wsql, $wparams) = $this->get_sql_where();
1767 $this->countsql .= ' AND '.$wsql;
1768 $this->countparams = array_merge($this->countparams, $wparams);
1770 $this->sql->where .= ' AND '.$wsql;
1771 $this->sql->params = array_merge($this->sql->params, $wparams);
1773 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1775 $total = $grandtotal;
1778 $this->pagesize($pagesize, $total);
1781 // Fetch the attempts
1782 $sort = $this->get_sql_sort();
1784 $sort = "ORDER BY $sort";
1787 {$this->sql->fields}
1788 FROM {$this->sql->from}
1789 WHERE {$this->sql->where}
1792 if (!$this->is_downloading()) {
1793 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1795 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1800 * Convenience method to call a number of methods for you to display the
1803 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1805 if (!$this->columns) {
1806 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1807 $this->sql->params, IGNORE_MULTIPLE);
1808 //if columns is not set then define columns as the keys of the rows returned
1810 $this->define_columns(array_keys((array)$onerow));
1811 $this->define_headers(array_keys((array)$onerow));
1814 $this->query_db($pagesize, $useinitialsbar);
1815 $this->build_table();
1816 $this->close_recordset();
1817 $this->finish_output();
1823 * @package moodlecore
1824 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1827 class table_default_export_format_parent {
1829 * @var flexible_table or child class reference pointing to table class
1830 * object from which to export data.
1835 * @var bool output started. Keeps track of whether any output has been
1838 var $documentstarted = false;
1843 * @param flexible_table $table
1845 public function __construct(&$table) {
1846 $this->table =& $table;
1850 * Old syntax of class constructor. Deprecated in PHP7.
1852 * @deprecated since Moodle 3.1
1854 public function table_default_export_format_parent(&$table) {
1855 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1856 self::__construct($table);
1859 function set_table(&$table) {
1860 $this->table =& $table;
1863 function add_data($row) {
1867 function add_seperator() {
1871 function document_started() {
1872 return $this->documentstarted;
1875 * Given text in a variety of format codings, this function returns
1876 * the text as safe HTML or as plain text dependent on what is appropriate
1877 * for the download format. The default removes all tags.
1879 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1880 //use some whitespace to indicate where there was some line spacing.
1881 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1882 return strip_tags($text);
1887 * Dataformat exporter
1890 * @subpackage tablelib
1891 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1892 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1894 class table_dataformat_export_format extends table_default_export_format_parent {
1896 /** @var $dataformat */
1897 protected $dataformat;
1900 protected $rownum = 0;
1902 /** @var $columns */
1908 * @param string $table An sql table
1909 * @param string $dataformat type of dataformat for export
1911 public function __construct(&$table, $dataformat) {
1912 parent::__construct($table);
1914 if (ob_get_length()) {
1915 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1918 $classname = 'dataformat_' . $dataformat . '\writer';
1919 if (!class_exists($classname)) {
1920 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1922 $this->dataformat = new $classname;
1924 // The dataformat export time to first byte could take a while to generate...
1927 // Close the session so that the users other tabs in the same session are not blocked.
1928 \core\session\manager::write_close();
1934 * @param string $filename
1935 * @param string $sheettitle
1937 public function start_document($filename, $sheettitle) {
1938 $this->documentstarted = true;
1939 $this->dataformat->set_filename($filename);
1940 $this->dataformat->send_http_headers();
1941 $this->dataformat->set_sheettitle($sheettitle);
1942 $this->dataformat->start_output();
1948 * @param string $sheettitle optional spreadsheet worksheet title
1950 public function start_table($sheettitle) {
1951 $this->dataformat->set_sheettitle($sheettitle);
1957 * @param array $headers
1959 public function output_headers($headers) {
1960 $this->columns = $headers;
1961 if (method_exists($this->dataformat, 'write_header')) {
1962 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
1963 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1964 $this->dataformat->write_header($headers);
1966 $this->dataformat->start_sheet($headers);
1973 * @param array $row One record of data
1975 public function add_data($row) {
1976 $this->dataformat->write_record($row, $this->rownum++);
1983 public function finish_table() {
1984 if (method_exists($this->dataformat, 'write_footer')) {
1985 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
1986 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1987 $this->dataformat->write_footer($this->columns);
1989 $this->dataformat->close_sheet($this->columns);
1996 public function finish_document() {
1997 $this->dataformat->close_output();