Merge branch 'MDL-67827-37' of git://github.com/andrewnicols/moodle into MOODLE_37_STABLE
[moodle.git] / lib / tablelib.php
blobe61f9ba7fb6a607c2f8ce61d72c6139461942003
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 /**#@-*/
50 /**
51 * @package moodlecore
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 {
57 var $uniqueid = NULL;
58 var $attributes = array();
59 var $headers = array();
61 /**
62 * @var string A column which should be considered as a header column.
64 protected $headercolumn = null;
66 /**
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. */
77 var $setup = false;
78 var $baseurl = NULL;
79 var $request = array();
81 /**
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;
87 var $use_pages = false;
88 var $use_initials = false;
90 var $maxsortkeys = 2;
91 var $pagesize = 30;
92 var $currpage = 0;
93 var $totalrows = 0;
94 var $currentrow = 0;
95 var $sort_default_column = NULL;
96 var $sort_default_order = SORT_ASC;
98 /**
99 * Array of positions in which to display download controls.
101 var $showdownloadbuttonsat= array(TABLE_P_TOP);
104 * @var string Key of field returned by db query that is the id field of the
105 * user table or equivalent.
107 public $useridfield = 'id';
110 * @var string which download plugin to use. Default '' means none - print
111 * html table with paging. Property set by is_downloading which typically
112 * passes in cleaned data from $
114 var $download = '';
117 * @var bool whether data is downloadable from table. Determines whether
118 * to display download buttons. Set by method downloadable().
120 var $downloadable = false;
123 * @var bool Has start output been called yet?
125 var $started_output = false;
127 var $exportclass = null;
130 * @var array For storing user-customised table properties in the user_preferences db table.
132 private $prefs = array();
134 /** @var $sheettitle */
135 protected $sheettitle;
137 /** @var $filename */
138 protected $filename;
141 * Constructor
142 * @param string $uniqueid all tables have to have a unique id, this is used
143 * as a key when storing table properties like sort order in the session.
145 function __construct($uniqueid) {
146 $this->uniqueid = $uniqueid;
147 $this->request = array(
148 TABLE_VAR_SORT => 'tsort',
149 TABLE_VAR_HIDE => 'thide',
150 TABLE_VAR_SHOW => 'tshow',
151 TABLE_VAR_IFIRST => 'tifirst',
152 TABLE_VAR_ILAST => 'tilast',
153 TABLE_VAR_PAGE => 'page',
154 TABLE_VAR_RESET => 'treset',
155 TABLE_VAR_DIR => 'tdir',
160 * Call this to pass the download type. Use :
161 * $download = optional_param('download', '', PARAM_ALPHA);
162 * To get the download type. We assume that if you call this function with
163 * params that this table's data is downloadable, so we call is_downloadable
164 * for you (even if the param is '', which means no download this time.
165 * Also you can call this method with no params to get the current set
166 * download type.
167 * @param string $download dataformat type. One of csv, xhtml, ods, etc
168 * @param string $filename filename for downloads without file extension.
169 * @param string $sheettitle title for downloaded data.
170 * @return string download dataformat type. One of csv, xhtml, ods, etc
172 function is_downloading($download = null, $filename='', $sheettitle='') {
173 if ($download!==null) {
174 $this->sheettitle = $sheettitle;
175 $this->is_downloadable(true);
176 $this->download = $download;
177 $this->filename = clean_filename($filename);
178 $this->export_class_instance();
180 return $this->download;
184 * Get, and optionally set, the export class.
185 * @param $exportclass (optional) if passed, set the table to use this export class.
186 * @return table_default_export_format_parent the export class in use (after any set).
188 function export_class_instance($exportclass = null) {
189 if (!is_null($exportclass)) {
190 $this->started_output = true;
191 $this->exportclass = $exportclass;
192 $this->exportclass->table = $this;
193 } else if (is_null($this->exportclass) && !empty($this->download)) {
194 $this->exportclass = new table_dataformat_export_format($this, $this->download);
195 if (!$this->exportclass->document_started()) {
196 $this->exportclass->start_document($this->filename, $this->sheettitle);
199 return $this->exportclass;
203 * Probably don't need to call this directly. Calling is_downloading with a
204 * param automatically sets table as downloadable.
206 * @param bool $downloadable optional param to set whether data from
207 * table is downloadable. If ommitted this function can be used to get
208 * current state of table.
209 * @return bool whether table data is set to be downloadable.
211 function is_downloadable($downloadable = null) {
212 if ($downloadable !== null) {
213 $this->downloadable = $downloadable;
215 return $this->downloadable;
219 * Call with boolean true to store table layout changes in the user_preferences table.
220 * Note: user_preferences.value has a maximum length of 1333 characters.
221 * Call with no parameter to get current state of table persistence.
223 * @param bool $persistent Optional parameter to set table layout persistence.
224 * @return bool Whether or not the table layout preferences will persist.
226 public function is_persistent($persistent = null) {
227 if ($persistent == true) {
228 $this->persistent = true;
230 return $this->persistent;
234 * Where to show download buttons.
235 * @param array $showat array of postions in which to show download buttons.
236 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
238 function show_download_buttons_at($showat) {
239 $this->showdownloadbuttonsat = $showat;
243 * Sets the is_sortable variable to the given boolean, sort_default_column to
244 * the given string, and the sort_default_order to the given integer.
245 * @param bool $bool
246 * @param string $defaultcolumn
247 * @param int $defaultorder
248 * @return void
250 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
251 $this->is_sortable = $bool;
252 $this->sort_default_column = $defaultcolumn;
253 $this->sort_default_order = $defaultorder;
257 * Use text sorting functions for this column (required for text columns with Oracle).
258 * Be warned that you cannot use this with column aliases. You can only do this
259 * with real columns. See MDL-40481 for an example.
260 * @param string column name
262 function text_sorting($column) {
263 $this->column_textsort[] = $column;
267 * Do not sort using this column
268 * @param string column name
270 function no_sorting($column) {
271 $this->column_nosort[] = $column;
275 * Is the column sortable?
276 * @param string column name, null means table
277 * @return bool
279 function is_sortable($column = null) {
280 if (empty($column)) {
281 return $this->is_sortable;
283 if (!$this->is_sortable) {
284 return false;
286 return !in_array($column, $this->column_nosort);
290 * Sets the is_collapsible variable to the given boolean.
291 * @param bool $bool
292 * @return void
294 function collapsible($bool) {
295 $this->is_collapsible = $bool;
299 * Sets the use_pages variable to the given boolean.
300 * @param bool $bool
301 * @return void
303 function pageable($bool) {
304 $this->use_pages = $bool;
308 * Sets the use_initials variable to the given boolean.
309 * @param bool $bool
310 * @return void
312 function initialbars($bool) {
313 $this->use_initials = $bool;
317 * Sets the pagesize variable to the given integer, the totalrows variable
318 * to the given integer, and the use_pages variable to true.
319 * @param int $perpage
320 * @param int $total
321 * @return void
323 function pagesize($perpage, $total) {
324 $this->pagesize = $perpage;
325 $this->totalrows = $total;
326 $this->use_pages = true;
330 * Assigns each given variable in the array to the corresponding index
331 * in the request class variable.
332 * @param array $variables
333 * @return void
335 function set_control_variables($variables) {
336 foreach ($variables as $what => $variable) {
337 if (isset($this->request[$what])) {
338 $this->request[$what] = $variable;
344 * Gives the given $value to the $attribute index of $this->attributes.
345 * @param string $attribute
346 * @param mixed $value
347 * @return void
349 function set_attribute($attribute, $value) {
350 $this->attributes[$attribute] = $value;
354 * What this method does is set the column so that if the same data appears in
355 * consecutive rows, then it is not repeated.
357 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
358 * that when one student has made multiple attempts, their name is only printed in the row
359 * for their first attempt.
360 * @param int $column the index of a column.
362 function column_suppress($column) {
363 if (isset($this->column_suppress[$column])) {
364 $this->column_suppress[$column] = true;
369 * Sets the given $column index to the given $classname in $this->column_class.
370 * @param int $column
371 * @param string $classname
372 * @return void
374 function column_class($column, $classname) {
375 if (isset($this->column_class[$column])) {
376 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
381 * Sets the given $column index and $property index to the given $value in $this->column_style.
382 * @param int $column
383 * @param string $property
384 * @param mixed $value
385 * @return void
387 function column_style($column, $property, $value) {
388 if (isset($this->column_style[$column])) {
389 $this->column_style[$column][$property] = $value;
394 * Sets all columns' $propertys to the given $value in $this->column_style.
395 * @param int $property
396 * @param string $value
397 * @return void
399 function column_style_all($property, $value) {
400 foreach (array_keys($this->columns) as $column) {
401 $this->column_style[$column][$property] = $value;
406 * Sets $this->baseurl.
407 * @param moodle_url|string $url the url with params needed to call up this page
409 function define_baseurl($url) {
410 $this->baseurl = new moodle_url($url);
414 * @param array $columns an array of identifying names for columns. If
415 * columns are sorted then column names must correspond to a field in sql.
417 function define_columns($columns) {
418 $this->columns = array();
419 $this->column_style = array();
420 $this->column_class = array();
421 $colnum = 0;
423 foreach ($columns as $column) {
424 $this->columns[$column] = $colnum++;
425 $this->column_style[$column] = array();
426 $this->column_class[$column] = '';
427 $this->column_suppress[$column] = false;
432 * @param array $headers numerical keyed array of displayed string titles
433 * for each column.
435 function define_headers($headers) {
436 $this->headers = $headers;
440 * Mark a specific column as being a table header using the column name defined in define_columns.
442 * Note: Only one column can be a header, and it will be rendered using a th tag.
444 * @param string $column
446 public function define_header_column(string $column) {
447 $this->headercolumn = $column;
451 * Defines a help icon for the header
453 * Always use this function if you need to create header with sorting and help icon.
455 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
457 public function define_help_for_headers($helpicons) {
458 $this->helpforheaders = $helpicons;
462 * Must be called after table is defined. Use methods above first. Cannot
463 * use functions below till after calling this method.
464 * @return type?
466 function setup() {
467 global $SESSION;
469 if (empty($this->columns) || empty($this->uniqueid)) {
470 return false;
473 // Load any existing user preferences.
474 if ($this->persistent) {
475 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
476 $oldprefs = $this->prefs;
477 } else if (isset($SESSION->flextable[$this->uniqueid])) {
478 $this->prefs = $SESSION->flextable[$this->uniqueid];
479 $oldprefs = $this->prefs;
482 // Set up default preferences if needed.
483 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
484 $this->prefs = array(
485 'collapse' => array(),
486 'sortby' => array(),
487 'i_first' => '',
488 'i_last' => '',
489 'textsort' => $this->column_textsort,
493 if (!isset($oldprefs)) {
494 $oldprefs = $this->prefs;
497 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
498 isset($this->columns[$showcol])) {
499 $this->prefs['collapse'][$showcol] = false;
501 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
502 isset($this->columns[$hidecol])) {
503 $this->prefs['collapse'][$hidecol] = true;
504 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
505 unset($this->prefs['sortby'][$hidecol]);
509 // Now, update the column attributes for collapsed columns
510 foreach (array_keys($this->columns) as $column) {
511 if (!empty($this->prefs['collapse'][$column])) {
512 $this->column_style[$column]['width'] = '10px';
516 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
517 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
518 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
519 && isset($this->columns['fullname']))) {
521 $sortdir = optional_param($this->request[TABLE_VAR_DIR], $this->sort_default_order, PARAM_INT);
523 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
524 // This key already exists somewhere. Change its sortorder and bring it to the top.
525 $sortorder = $this->prefs['sortby'][$sortcol] = $sortdir;
526 unset($this->prefs['sortby'][$sortcol]);
527 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
528 } else {
529 // Key doesn't exist, so just add it to the beginning of the array, ascending order
530 $this->prefs['sortby'] = array_merge(array($sortcol => $sortdir), $this->prefs['sortby']);
533 // Finally, make sure that no more than $this->maxsortkeys are present into the array
534 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
537 // MDL-35375 - If a default order is defined and it is not in the current list of order by columns, add it at the end.
538 // This prevents results from being returned in a random order if the only order by column contains equal values.
539 if (!empty($this->sort_default_column)) {
540 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
541 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
542 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
546 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
547 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
548 $this->prefs['i_last'] = $ilast;
551 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
552 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
553 $this->prefs['i_first'] = $ifirst;
556 // Save user preferences if they have changed.
557 if ($this->prefs != $oldprefs) {
558 if ($this->persistent) {
559 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
560 } else {
561 $SESSION->flextable[$this->uniqueid] = $this->prefs;
564 unset($oldprefs);
566 if (empty($this->baseurl)) {
567 debugging('You should set baseurl when using flexible_table.');
568 global $PAGE;
569 $this->baseurl = $PAGE->url;
572 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
573 $this->setup = true;
575 // Always introduce the "flexible" class for the table if not specified
576 if (empty($this->attributes)) {
577 $this->attributes['class'] = 'flexible';
578 } else if (!isset($this->attributes['class'])) {
579 $this->attributes['class'] = 'flexible';
580 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
581 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
586 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
587 * @param string $uniqueid the identifier for a table.
588 * @return SQL fragment that can be used in an ORDER BY clause.
590 public static function get_sort_for_table($uniqueid) {
591 global $SESSION;
592 if (isset($SESSION->flextable[$uniqueid])) {
593 $prefs = $SESSION->flextable[$uniqueid];
594 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
595 return '';
598 if (empty($prefs['sortby'])) {
599 return '';
601 if (empty($prefs['textsort'])) {
602 $prefs['textsort'] = array();
605 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
609 * Prepare an an order by clause from the list of columns to be sorted.
610 * @param array $cols column name => SORT_ASC or SORT_DESC
611 * @return SQL fragment that can be used in an ORDER BY clause.
613 public static function construct_order_by($cols, $textsortcols=array()) {
614 global $DB;
615 $bits = array();
617 foreach ($cols as $column => $order) {
618 if (in_array($column, $textsortcols)) {
619 $column = $DB->sql_order_by_text($column);
621 if ($order == SORT_ASC) {
622 $bits[] = $column . ' ASC';
623 } else {
624 $bits[] = $column . ' DESC';
628 return implode(', ', $bits);
632 * @return SQL fragment that can be used in an ORDER BY clause.
634 public function get_sql_sort() {
635 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
639 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
640 * @return array column name => SORT_... constant.
642 public function get_sort_columns() {
643 if (!$this->setup) {
644 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
647 if (empty($this->prefs['sortby'])) {
648 return array();
651 foreach ($this->prefs['sortby'] as $column => $notused) {
652 if (isset($this->columns[$column])) {
653 continue; // This column is OK.
655 if (in_array($column, get_all_user_name_fields()) &&
656 isset($this->columns['fullname'])) {
657 continue; // This column is OK.
659 // This column is not OK.
660 unset($this->prefs['sortby'][$column]);
663 return $this->prefs['sortby'];
667 * @return int the offset for LIMIT clause of SQL
669 function get_page_start() {
670 if (!$this->use_pages) {
671 return '';
673 return $this->currpage * $this->pagesize;
677 * @return int the pagesize for LIMIT clause of SQL
679 function get_page_size() {
680 if (!$this->use_pages) {
681 return '';
683 return $this->pagesize;
687 * @return string sql to add to where statement.
689 function get_sql_where() {
690 global $DB;
692 $conditions = array();
693 $params = array();
695 if (isset($this->columns['fullname'])) {
696 static $i = 0;
697 $i++;
699 if (!empty($this->prefs['i_first'])) {
700 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
701 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
703 if (!empty($this->prefs['i_last'])) {
704 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
705 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
709 return array(implode(" AND ", $conditions), $params);
713 * Add a row of data to the table. This function takes an array or object with
714 * column names as keys or property names.
716 * It ignores any elements with keys that are not defined as columns. It
717 * puts in empty strings into the row when there is no element in the passed
718 * array corresponding to a column in the table. It puts the row elements in
719 * the proper order (internally row table data is stored by in arrays with
720 * a numerical index corresponding to the column number).
722 * @param object|array $rowwithkeys array keys or object property names are column names,
723 * as defined in call to define_columns.
724 * @param string $classname CSS class name to add to this row's tr tag.
726 function add_data_keyed($rowwithkeys, $classname = '') {
727 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
731 * Add a number of rows to the table at once. And optionally finish output after they have been added.
733 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
734 * object or array is added to table. We expect properties for the row array as would be
735 * passed to add_data_keyed.
736 * @param bool $finish
738 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
739 foreach ($rowstoadd as $row) {
740 if (is_null($row)) {
741 $this->add_separator();
742 } else {
743 $this->add_data_keyed($this->format_row($row));
746 if ($finish) {
747 $this->finish_output(!$this->is_downloading());
752 * Add a seperator line to table.
754 function add_separator() {
755 if (!$this->setup) {
756 return false;
758 $this->add_data(NULL);
762 * This method actually directly echoes the row passed to it now or adds it
763 * to the download. If this is the first row and start_output has not
764 * already been called this method also calls start_output to open the table
765 * or send headers for the downloaded.
766 * Can be used as before. print_html now calls finish_html to close table.
768 * @param array $row a numerically keyed row of data to add to the table.
769 * @param string $classname CSS class name to add to this row's tr tag.
770 * @return bool success.
772 function add_data($row, $classname = '') {
773 if (!$this->setup) {
774 return false;
776 if (!$this->started_output) {
777 $this->start_output();
779 if ($this->exportclass!==null) {
780 if ($row === null) {
781 $this->exportclass->add_seperator();
782 } else {
783 $this->exportclass->add_data($row);
785 } else {
786 $this->print_row($row, $classname);
788 return true;
792 * You should call this to finish outputting the table data after adding
793 * data to the table with add_data or add_data_keyed.
796 function finish_output($closeexportclassdoc = true) {
797 if ($this->exportclass!==null) {
798 $this->exportclass->finish_table();
799 if ($closeexportclassdoc) {
800 $this->exportclass->finish_document();
802 } else {
803 $this->finish_html();
808 * Hook that can be overridden in child classes to wrap a table in a form
809 * for example. Called only when there is data to display and not
810 * downloading.
812 function wrap_html_start() {
816 * Hook that can be overridden in child classes to wrap a table in a form
817 * for example. Called only when there is data to display and not
818 * downloading.
820 function wrap_html_finish() {
824 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
825 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
826 * displaying table as html, adding a div wrap, etc.
828 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
830 * @param array|object $row row of data from db used to make one row of the table.
831 * @return array one row for the table, added using add_data_keyed method.
833 function format_row($row) {
834 if (is_array($row)) {
835 $row = (object)$row;
837 $formattedrow = array();
838 foreach (array_keys($this->columns) as $column) {
839 $colmethodname = 'col_'.$column;
840 if (method_exists($this, $colmethodname)) {
841 $formattedcolumn = $this->$colmethodname($row);
842 } else {
843 $formattedcolumn = $this->other_cols($column, $row);
844 if ($formattedcolumn===NULL) {
845 $formattedcolumn = $row->$column;
848 $formattedrow[$column] = $formattedcolumn;
850 return $formattedrow;
854 * Fullname is treated as a special columname in tablelib and should always
855 * be treated the same as the fullname of a user.
856 * @uses $this->useridfield if the userid field is not expected to be id
857 * then you need to override $this->useridfield to point at the correct
858 * field for the user id.
860 * @param object $row the data from the db containing all fields from the
861 * users table necessary to construct the full name of the user in
862 * current language.
863 * @return string contents of cell in column 'fullname', for this row.
865 function col_fullname($row) {
866 global $PAGE, $COURSE;
868 $name = fullname($row, has_capability('moodle/site:viewfullnames', $PAGE->context));
869 if ($this->download) {
870 return $name;
873 $userid = $row->{$this->useridfield};
874 if ($COURSE->id == SITEID) {
875 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
876 } else {
877 $profileurl = new moodle_url('/user/view.php',
878 array('id' => $userid, 'course' => $COURSE->id));
880 return html_writer::link($profileurl, $name);
884 * You can override this method in a child class. See the description of
885 * build_table which calls this method.
887 function other_cols($column, $row) {
888 return NULL;
892 * Used from col_* functions when text is to be displayed. Does the
893 * right thing - either converts text to html or strips any html tags
894 * depending on if we are downloading and what is the download type. Params
895 * are the same as format_text function in weblib.php but some default
896 * options are changed.
898 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
899 if (!$this->is_downloading()) {
900 if (is_null($options)) {
901 $options = new stdClass;
903 //some sensible defaults
904 if (!isset($options->para)) {
905 $options->para = false;
907 if (!isset($options->newlines)) {
908 $options->newlines = false;
910 if (!isset($options->smiley)) {
911 $options->smiley = false;
913 if (!isset($options->filter)) {
914 $options->filter = false;
916 return format_text($text, $format, $options);
917 } else {
918 $eci = $this->export_class_instance();
919 return $eci->format_text($text, $format, $options, $courseid);
923 * This method is deprecated although the old api is still supported.
924 * @deprecated 1.9.2 - Jun 2, 2008
926 function print_html() {
927 if (!$this->setup) {
928 return false;
930 $this->finish_html();
934 * This function is not part of the public api.
935 * @return string initial of first name we are currently filtering by
937 function get_initial_first() {
938 if (!$this->use_initials) {
939 return NULL;
942 return $this->prefs['i_first'];
946 * This function is not part of the public api.
947 * @return string initial of last name we are currently filtering by
949 function get_initial_last() {
950 if (!$this->use_initials) {
951 return NULL;
954 return $this->prefs['i_last'];
958 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
959 * @param array $alpha of letters in the alphabet.
960 * @param string $current the currently selected letter.
961 * @param string $class class name to add to this initial bar.
962 * @param string $title the name to put in front of this initial bar.
963 * @param string $urlvar URL parameter name for this initial.
965 * @deprecated since Moodle 3.3
967 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
969 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
970 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
972 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
973 $title . ' : ';
974 if ($current) {
975 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
976 } else {
977 echo html_writer::tag('strong', get_string('all'));
980 foreach ($alpha as $letter) {
981 if ($letter === $current) {
982 echo html_writer::tag('strong', $letter);
983 } else {
984 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
988 echo html_writer::end_tag('div');
992 * This function is not part of the public api.
994 function print_initials_bar() {
995 global $OUTPUT;
997 $ifirst = $this->get_initial_first();
998 $ilast = $this->get_initial_last();
999 if (is_null($ifirst)) {
1000 $ifirst = '';
1002 if (is_null($ilast)) {
1003 $ilast = '';
1006 if ((!empty($ifirst) || !empty($ilast) ||$this->use_initials)
1007 && isset($this->columns['fullname'])) {
1008 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
1009 $prefixlast = $this->request[TABLE_VAR_ILAST];
1010 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
1011 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
1017 * This function is not part of the public api.
1019 function print_nothing_to_display() {
1020 global $OUTPUT;
1022 // Render button to allow user to reset table preferences.
1023 echo $this->render_reset_button();
1025 $this->print_initials_bar();
1027 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1031 * This function is not part of the public api.
1033 function get_row_from_keyed($rowwithkeys) {
1034 if (is_object($rowwithkeys)) {
1035 $rowwithkeys = (array)$rowwithkeys;
1037 $row = array();
1038 foreach (array_keys($this->columns) as $column) {
1039 if (isset($rowwithkeys[$column])) {
1040 $row [] = $rowwithkeys[$column];
1041 } else {
1042 $row[] ='';
1045 return $row;
1049 * Get the html for the download buttons
1051 * Usually only use internally
1053 public function download_buttons() {
1054 global $OUTPUT;
1056 if ($this->is_downloadable() && !$this->is_downloading()) {
1057 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1058 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1059 } else {
1060 return '';
1065 * This function is not part of the public api.
1066 * You don't normally need to call this. It is called automatically when
1067 * needed when you start adding data to the table.
1070 function start_output() {
1071 $this->started_output = true;
1072 if ($this->exportclass!==null) {
1073 $this->exportclass->start_table($this->sheettitle);
1074 $this->exportclass->output_headers($this->headers);
1075 } else {
1076 $this->start_html();
1077 $this->print_headers();
1078 echo html_writer::start_tag('tbody');
1083 * This function is not part of the public api.
1085 function print_row($row, $classname = '') {
1086 echo $this->get_row_html($row, $classname);
1090 * Generate html code for the passed row.
1092 * @param array $row Row data.
1093 * @param string $classname classes to add.
1095 * @return string $html html code for the row passed.
1097 public function get_row_html($row, $classname = '') {
1098 static $suppress_lastrow = NULL;
1099 $rowclasses = array();
1101 if ($classname) {
1102 $rowclasses[] = $classname;
1105 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1106 $html = '';
1108 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1110 // If we have a separator, print it
1111 if ($row === NULL) {
1112 $colcount = count($this->columns);
1113 $html .= html_writer::tag('td', html_writer::tag('div', '',
1114 array('class' => 'tabledivider')), array('colspan' => $colcount));
1116 } else {
1117 $colbyindex = array_flip($this->columns);
1118 foreach ($row as $index => $data) {
1119 $column = $colbyindex[$index];
1121 $attributes = [
1122 'class' => "cell c{$index}" . $this->column_class[$column],
1123 'id' => "{$rowid}_c{$index}",
1124 'style' => $this->make_styles_string($this->column_style[$column]),
1127 $celltype = 'td';
1128 if ($this->headercolumn && $column == $this->headercolumn) {
1129 $celltype = 'th';
1130 $attributes['scope'] = 'row';
1133 if (empty($this->prefs['collapse'][$column])) {
1134 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1135 $content = '&nbsp;';
1136 } else {
1137 $content = $data;
1139 } else {
1140 $content = '&nbsp;';
1143 $html .= html_writer::tag($celltype, $content, $attributes);
1147 $html .= html_writer::end_tag('tr');
1149 $suppress_enabled = array_sum($this->column_suppress);
1150 if ($suppress_enabled) {
1151 $suppress_lastrow = $row;
1153 $this->currentrow++;
1154 return $html;
1158 * This function is not part of the public api.
1160 function finish_html() {
1161 global $OUTPUT;
1162 if (!$this->started_output) {
1163 //no data has been added to the table.
1164 $this->print_nothing_to_display();
1166 } else {
1167 // Print empty rows to fill the table to the current pagesize.
1168 // This is done so the header aria-controls attributes do not point to
1169 // non existant elements.
1170 $emptyrow = array_fill(0, count($this->columns), '');
1171 while ($this->currentrow < $this->pagesize) {
1172 $this->print_row($emptyrow, 'emptyrow');
1175 echo html_writer::end_tag('tbody');
1176 echo html_writer::end_tag('table');
1177 echo html_writer::end_tag('div');
1178 $this->wrap_html_finish();
1180 // Paging bar
1181 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1182 echo $this->download_buttons();
1185 if($this->use_pages) {
1186 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1187 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1188 echo $OUTPUT->render($pagingbar);
1194 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1195 * used by {@link print_headers()}.
1196 * @param string $column the column name, index into various names.
1197 * @param int $index numerical index of the column.
1198 * @return string HTML fragment.
1200 protected function show_hide_link($column, $index) {
1201 global $OUTPUT;
1202 // Some headers contain <br /> tags, do not include in title, hence the
1203 // strip tags.
1205 $ariacontrols = '';
1206 for ($i = 0; $i < $this->pagesize; $i++) {
1207 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1210 $ariacontrols = trim($ariacontrols);
1212 if (!empty($this->prefs['collapse'][$column])) {
1213 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1214 'aria-expanded' => 'false',
1215 'aria-controls' => $ariacontrols);
1216 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1217 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1219 } else if ($this->headers[$index] !== NULL) {
1220 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1221 'aria-expanded' => 'true',
1222 'aria-controls' => $ariacontrols);
1223 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1224 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1229 * This function is not part of the public api.
1231 function print_headers() {
1232 global $CFG, $OUTPUT, $PAGE;
1234 echo html_writer::start_tag('thead');
1235 echo html_writer::start_tag('tr');
1236 foreach ($this->columns as $column => $index) {
1238 $icon_hide = '';
1239 if ($this->is_collapsible) {
1240 $icon_hide = $this->show_hide_link($column, $index);
1243 $primarysortcolumn = '';
1244 $primarysortorder = '';
1245 if (reset($this->prefs['sortby'])) {
1246 $primarysortcolumn = key($this->prefs['sortby']);
1247 $primarysortorder = current($this->prefs['sortby']);
1250 switch ($column) {
1252 case 'fullname':
1253 // Check the full name display for sortable fields.
1254 if (has_capability('moodle/site:viewfullnames', $PAGE->context)) {
1255 $nameformat = $CFG->alternativefullnameformat;
1256 } else {
1257 $nameformat = $CFG->fullnamedisplay;
1260 if ($nameformat == 'language') {
1261 $nameformat = get_string('fullnamedisplay');
1264 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1266 if (!empty($requirednames)) {
1267 if ($this->is_sortable($column)) {
1268 // Done this way for the possibility of more than two sortable full name display fields.
1269 $this->headers[$index] = '';
1270 foreach ($requirednames as $name) {
1271 $sortname = $this->sort_link(get_string($name),
1272 $name, $primarysortcolumn === $name, $primarysortorder);
1273 $this->headers[$index] .= $sortname . ' / ';
1275 $helpicon = '';
1276 if (isset($this->helpforheaders[$index])) {
1277 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1279 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1282 break;
1284 case 'userpic':
1285 // do nothing, do not display sortable links
1286 break;
1288 default:
1289 if ($this->is_sortable($column)) {
1290 $helpicon = '';
1291 if (isset($this->helpforheaders[$index])) {
1292 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1294 $this->headers[$index] = $this->sort_link($this->headers[$index],
1295 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1299 $attributes = array(
1300 'class' => 'header c' . $index . $this->column_class[$column],
1301 'scope' => 'col',
1303 if ($this->headers[$index] === NULL) {
1304 $content = '&nbsp;';
1305 } else if (!empty($this->prefs['collapse'][$column])) {
1306 $content = $icon_hide;
1307 } else {
1308 if (is_array($this->column_style[$column])) {
1309 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1311 $helpicon = '';
1312 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1313 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1315 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1316 $icon_hide, array('class' => 'commands'));
1318 echo html_writer::tag('th', $content, $attributes);
1321 echo html_writer::end_tag('tr');
1322 echo html_writer::end_tag('thead');
1326 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1327 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1328 * @param int $order SORT_ASC or SORT_DESC
1329 * @return string HTML fragment.
1331 protected function sort_icon($isprimary, $order) {
1332 global $OUTPUT;
1334 if (!$isprimary) {
1335 return '';
1338 if ($order == SORT_ASC) {
1339 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1340 } else {
1341 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1346 * Generate the correct tool tip for changing the sort order. This is a
1347 * helper method used by {@link sort_link()}.
1348 * @param bool $isprimary whether the is column is the current primary sort column.
1349 * @param int $order SORT_ASC or SORT_DESC
1350 * @return string the correct title.
1352 protected function sort_order_name($isprimary, $order) {
1353 if ($isprimary && $order != SORT_ASC) {
1354 return get_string('desc');
1355 } else {
1356 return get_string('asc');
1361 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1362 * @param string $text the text for the link.
1363 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1364 * @param bool $isprimary whether the is column is the current primary sort column.
1365 * @param int $order SORT_ASC or SORT_DESC
1366 * @return string HTML fragment.
1368 protected function sort_link($text, $column, $isprimary, $order) {
1369 // If we are already sorting by this column, switch direction.
1370 if (array_key_exists($column, $this->prefs['sortby'])) {
1371 $sortorder = $this->prefs['sortby'][$column] == SORT_ASC ? SORT_DESC : SORT_ASC;
1372 } else {
1373 $sortorder = $order;
1376 $params = [
1377 $this->request[TABLE_VAR_SORT] => $column,
1378 $this->request[TABLE_VAR_DIR] => $sortorder,
1381 return html_writer::link($this->baseurl->out(false, $params),
1382 $text . get_accesshide(get_string('sortby') . ' ' .
1383 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1384 $this->sort_icon($isprimary, $order);
1388 * This function is not part of the public api.
1390 function start_html() {
1391 global $OUTPUT;
1393 // Render button to allow user to reset table preferences.
1394 echo $this->render_reset_button();
1396 // Do we need to print initial bars?
1397 $this->print_initials_bar();
1399 // Paging bar
1400 if ($this->use_pages) {
1401 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1402 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1403 echo $OUTPUT->render($pagingbar);
1406 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1407 echo $this->download_buttons();
1410 $this->wrap_html_start();
1411 // Start of main data table
1413 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1414 echo html_writer::start_tag('table', $this->attributes);
1419 * This function is not part of the public api.
1420 * @param array $styles CSS-property => value
1421 * @return string values suitably to go in a style="" attribute in HTML.
1423 function make_styles_string($styles) {
1424 if (empty($styles)) {
1425 return null;
1428 $string = '';
1429 foreach($styles as $property => $value) {
1430 $string .= $property . ':' . $value . ';';
1432 return $string;
1436 * Generate the HTML for the table preferences reset button.
1438 * @return string HTML fragment, empty string if no need to reset
1440 protected function render_reset_button() {
1442 if (!$this->can_be_reset()) {
1443 return '';
1446 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1448 $html = html_writer::start_div('resettable mdl-right');
1449 $html .= html_writer::link($url, get_string('resettable'));
1450 $html .= html_writer::end_div();
1452 return $html;
1456 * Are there some table preferences that can be reset?
1458 * If true, then the "reset table preferences" widget should be displayed.
1460 * @return bool
1462 protected function can_be_reset() {
1464 // Loop through preferences and make sure they are empty or set to the default value.
1465 foreach ($this->prefs as $prefname => $prefval) {
1467 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1468 // Check if the actual sorting differs from the default one.
1469 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1470 return true;
1473 } else if ($prefname === 'collapse' and !empty($prefval)) {
1474 // Check if there are some collapsed columns (all are expanded by default).
1475 foreach ($prefval as $columnname => $iscollapsed) {
1476 if ($iscollapsed) {
1477 return true;
1481 } else if (!empty($prefval)) {
1482 // For all other cases, we just check if some preference is set.
1483 return true;
1487 return false;
1493 * @package moodlecore
1494 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1497 class table_sql extends flexible_table {
1499 public $countsql = NULL;
1500 public $countparams = NULL;
1502 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1504 public $sql = NULL;
1506 * @var array|\Traversable Data fetched from the db.
1508 public $rawdata = NULL;
1511 * @var bool Overriding default for this.
1513 public $is_sortable = true;
1515 * @var bool Overriding default for this.
1517 public $is_collapsible = true;
1520 * @param string $uniqueid a string identifying this table.Used as a key in
1521 * session vars.
1523 function __construct($uniqueid) {
1524 parent::__construct($uniqueid);
1525 // some sensible defaults
1526 $this->set_attribute('cellspacing', '0');
1527 $this->set_attribute('class', 'generaltable generalbox');
1531 * Take the data returned from the db_query and go through all the rows
1532 * processing each col using either col_{columnname} method or other_cols
1533 * method or if other_cols returns NULL then put the data straight into the
1534 * table.
1536 * After calling this function, don't forget to call close_recordset.
1538 public function build_table() {
1540 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1541 return;
1543 if (!$this->rawdata) {
1544 return;
1547 foreach ($this->rawdata as $row) {
1548 $formattedrow = $this->format_row($row);
1549 $this->add_data_keyed($formattedrow,
1550 $this->get_row_class($row));
1555 * Closes recordset (for use after building the table).
1557 public function close_recordset() {
1558 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1559 $this->rawdata instanceof moodle_recordset)) {
1560 $this->rawdata->close();
1561 $this->rawdata = null;
1566 * Get any extra classes names to add to this row in the HTML.
1567 * @param $row array the data for this row.
1568 * @return string added to the class="" attribute of the tr.
1570 function get_row_class($row) {
1571 return '';
1575 * This is only needed if you want to use different sql to count rows.
1576 * Used for example when perhaps all db JOINS are not needed when counting
1577 * records. You don't need to call this function the count_sql
1578 * will be generated automatically.
1580 * We need to count rows returned by the db seperately to the query itself
1581 * as we need to know how many pages of data we have to display.
1583 function set_count_sql($sql, array $params = NULL) {
1584 $this->countsql = $sql;
1585 $this->countparams = $params;
1589 * Set the sql to query the db. Query will be :
1590 * SELECT $fields FROM $from WHERE $where
1591 * Of course you can use sub-queries, JOINS etc. by putting them in the
1592 * appropriate clause of the query.
1594 function set_sql($fields, $from, $where, array $params = array()) {
1595 $this->sql = new stdClass();
1596 $this->sql->fields = $fields;
1597 $this->sql->from = $from;
1598 $this->sql->where = $where;
1599 $this->sql->params = $params;
1603 * Query the db. Store results in the table object for use by build_table.
1605 * @param int $pagesize size of page for paginated displayed table.
1606 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1607 * will only be used if there is a fullname column defined for the table.
1609 function query_db($pagesize, $useinitialsbar=true) {
1610 global $DB;
1611 if (!$this->is_downloading()) {
1612 if ($this->countsql === NULL) {
1613 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1614 $this->countparams = $this->sql->params;
1616 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1617 if ($useinitialsbar && !$this->is_downloading()) {
1618 $this->initialbars($grandtotal > $pagesize);
1621 list($wsql, $wparams) = $this->get_sql_where();
1622 if ($wsql) {
1623 $this->countsql .= ' AND '.$wsql;
1624 $this->countparams = array_merge($this->countparams, $wparams);
1626 $this->sql->where .= ' AND '.$wsql;
1627 $this->sql->params = array_merge($this->sql->params, $wparams);
1629 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1630 } else {
1631 $total = $grandtotal;
1634 $this->pagesize($pagesize, $total);
1637 // Fetch the attempts
1638 $sort = $this->get_sql_sort();
1639 if ($sort) {
1640 $sort = "ORDER BY $sort";
1642 $sql = "SELECT
1643 {$this->sql->fields}
1644 FROM {$this->sql->from}
1645 WHERE {$this->sql->where}
1646 {$sort}";
1648 if (!$this->is_downloading()) {
1649 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1650 } else {
1651 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1656 * Convenience method to call a number of methods for you to display the
1657 * table.
1659 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1660 global $DB;
1661 if (!$this->columns) {
1662 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1663 $this->sql->params, IGNORE_MULTIPLE);
1664 //if columns is not set then define columns as the keys of the rows returned
1665 //from the db.
1666 $this->define_columns(array_keys((array)$onerow));
1667 $this->define_headers(array_keys((array)$onerow));
1669 $this->setup();
1670 $this->query_db($pagesize, $useinitialsbar);
1671 $this->build_table();
1672 $this->close_recordset();
1673 $this->finish_output();
1679 * @package moodlecore
1680 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1681 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1683 class table_default_export_format_parent {
1685 * @var flexible_table or child class reference pointing to table class
1686 * object from which to export data.
1688 var $table;
1691 * @var bool output started. Keeps track of whether any output has been
1692 * started yet.
1694 var $documentstarted = false;
1697 * Constructor
1699 * @param flexible_table $table
1701 public function __construct(&$table) {
1702 $this->table =& $table;
1706 * Old syntax of class constructor. Deprecated in PHP7.
1708 * @deprecated since Moodle 3.1
1710 public function table_default_export_format_parent(&$table) {
1711 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1712 self::__construct($table);
1715 function set_table(&$table) {
1716 $this->table =& $table;
1719 function add_data($row) {
1720 return false;
1723 function add_seperator() {
1724 return false;
1727 function document_started() {
1728 return $this->documentstarted;
1731 * Given text in a variety of format codings, this function returns
1732 * the text as safe HTML or as plain text dependent on what is appropriate
1733 * for the download format. The default removes all tags.
1735 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1736 //use some whitespace to indicate where there was some line spacing.
1737 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1738 return strip_tags($text);
1743 * Dataformat exporter
1745 * @package core
1746 * @subpackage tablelib
1747 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1748 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1750 class table_dataformat_export_format extends table_default_export_format_parent {
1752 /** @var $dataformat */
1753 protected $dataformat;
1755 /** @var $rownum */
1756 protected $rownum = 0;
1758 /** @var $columns */
1759 protected $columns;
1762 * Constructor
1764 * @param string $table An sql table
1765 * @param string $dataformat type of dataformat for export
1767 public function __construct(&$table, $dataformat) {
1768 parent::__construct($table);
1770 if (ob_get_length()) {
1771 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1774 $classname = 'dataformat_' . $dataformat . '\writer';
1775 if (!class_exists($classname)) {
1776 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1778 $this->dataformat = new $classname;
1780 // The dataformat export time to first byte could take a while to generate...
1781 set_time_limit(0);
1783 // Close the session so that the users other tabs in the same session are not blocked.
1784 \core\session\manager::write_close();
1788 * Start document
1790 * @param string $filename
1791 * @param string $sheettitle
1793 public function start_document($filename, $sheettitle) {
1794 $this->documentstarted = true;
1795 $this->dataformat->set_filename($filename);
1796 $this->dataformat->send_http_headers();
1797 $this->dataformat->set_sheettitle($sheettitle);
1798 $this->dataformat->start_output();
1802 * Start export
1804 * @param string $sheettitle optional spreadsheet worksheet title
1806 public function start_table($sheettitle) {
1807 $this->dataformat->set_sheettitle($sheettitle);
1811 * Output headers
1813 * @param array $headers
1815 public function output_headers($headers) {
1816 $this->columns = $headers;
1817 if (method_exists($this->dataformat, 'write_header')) {
1818 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
1819 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1820 $this->dataformat->write_header($headers);
1821 } else {
1822 $this->dataformat->start_sheet($headers);
1827 * Add a row of data
1829 * @param array $row One record of data
1831 public function add_data($row) {
1832 $this->dataformat->write_record($row, $this->rownum++);
1833 return true;
1837 * Finish export
1839 public function finish_table() {
1840 if (method_exists($this->dataformat, 'write_footer')) {
1841 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
1842 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1843 $this->dataformat->write_footer($this->columns);
1844 } else {
1845 $this->dataformat->close_sheet($this->columns);
1850 * Finish download
1852 public function finish_document() {
1853 $this->dataformat->close_output();
1854 exit();