Merge branch 'MDL-64151-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / tablelib.php
blobd1213b89b47422b570aa49d38be137d36f8828a9
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 /**#@-*/
40 /**#@+
41 * Constants that indicate whether the paging bar for the table
42 * appears above or below the table.
44 define('TABLE_P_TOP', 1);
45 define('TABLE_P_BOTTOM', 2);
46 /**#@-*/
49 /**
50 * @package moodlecore
51 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 class flexible_table {
56 var $uniqueid = NULL;
57 var $attributes = array();
58 var $headers = array();
60 /**
61 * @var string A column which should be considered as a header column.
63 protected $headercolumn = null;
65 /**
66 * @var string For create header with help icon.
68 private $helpforheaders = array();
69 var $columns = array();
70 var $column_style = array();
71 var $column_class = array();
72 var $column_suppress = array();
73 var $column_nosort = array('userpic');
74 private $column_textsort = array();
75 /** @var boolean Stores if setup has already been called on this flixible table. */
76 var $setup = false;
77 var $baseurl = NULL;
78 var $request = array();
80 /**
81 * @var bool Whether or not to store table properties in the user_preferences table.
83 private $persistent = false;
84 var $is_collapsible = false;
85 var $is_sortable = false;
86 var $use_pages = false;
87 var $use_initials = false;
89 var $maxsortkeys = 2;
90 var $pagesize = 30;
91 var $currpage = 0;
92 var $totalrows = 0;
93 var $currentrow = 0;
94 var $sort_default_column = NULL;
95 var $sort_default_order = SORT_ASC;
97 /**
98 * Array of positions in which to display download controls.
100 var $showdownloadbuttonsat= array(TABLE_P_TOP);
103 * @var string Key of field returned by db query that is the id field of the
104 * user table or equivalent.
106 public $useridfield = 'id';
109 * @var string which download plugin to use. Default '' means none - print
110 * html table with paging. Property set by is_downloading which typically
111 * passes in cleaned data from $
113 var $download = '';
116 * @var bool whether data is downloadable from table. Determines whether
117 * to display download buttons. Set by method downloadable().
119 var $downloadable = false;
122 * @var bool Has start output been called yet?
124 var $started_output = false;
126 var $exportclass = null;
129 * @var array For storing user-customised table properties in the user_preferences db table.
131 private $prefs = array();
133 /** @var $sheettitle */
134 protected $sheettitle;
136 /** @var $filename */
137 protected $filename;
140 * Constructor
141 * @param string $uniqueid all tables have to have a unique id, this is used
142 * as a key when storing table properties like sort order in the session.
144 function __construct($uniqueid) {
145 $this->uniqueid = $uniqueid;
146 $this->request = array(
147 TABLE_VAR_SORT => 'tsort',
148 TABLE_VAR_HIDE => 'thide',
149 TABLE_VAR_SHOW => 'tshow',
150 TABLE_VAR_IFIRST => 'tifirst',
151 TABLE_VAR_ILAST => 'tilast',
152 TABLE_VAR_PAGE => 'page',
153 TABLE_VAR_RESET => 'treset'
158 * Call this to pass the download type. Use :
159 * $download = optional_param('download', '', PARAM_ALPHA);
160 * To get the download type. We assume that if you call this function with
161 * params that this table's data is downloadable, so we call is_downloadable
162 * for you (even if the param is '', which means no download this time.
163 * Also you can call this method with no params to get the current set
164 * download type.
165 * @param string $download dataformat type. One of csv, xhtml, ods, etc
166 * @param string $filename filename for downloads without file extension.
167 * @param string $sheettitle title for downloaded data.
168 * @return string download dataformat type. One of csv, xhtml, ods, etc
170 function is_downloading($download = null, $filename='', $sheettitle='') {
171 if ($download!==null) {
172 $this->sheettitle = $sheettitle;
173 $this->is_downloadable(true);
174 $this->download = $download;
175 $this->filename = clean_filename($filename);
176 $this->export_class_instance();
178 return $this->download;
182 * Get, and optionally set, the export class.
183 * @param $exportclass (optional) if passed, set the table to use this export class.
184 * @return table_default_export_format_parent the export class in use (after any set).
186 function export_class_instance($exportclass = null) {
187 if (!is_null($exportclass)) {
188 $this->started_output = true;
189 $this->exportclass = $exportclass;
190 $this->exportclass->table = $this;
191 } else if (is_null($this->exportclass) && !empty($this->download)) {
192 $this->exportclass = new table_dataformat_export_format($this, $this->download);
193 if (!$this->exportclass->document_started()) {
194 $this->exportclass->start_document($this->filename, $this->sheettitle);
197 return $this->exportclass;
201 * Probably don't need to call this directly. Calling is_downloading with a
202 * param automatically sets table as downloadable.
204 * @param bool $downloadable optional param to set whether data from
205 * table is downloadable. If ommitted this function can be used to get
206 * current state of table.
207 * @return bool whether table data is set to be downloadable.
209 function is_downloadable($downloadable = null) {
210 if ($downloadable !== null) {
211 $this->downloadable = $downloadable;
213 return $this->downloadable;
217 * Call with boolean true to store table layout changes in the user_preferences table.
218 * Note: user_preferences.value has a maximum length of 1333 characters.
219 * Call with no parameter to get current state of table persistence.
221 * @param bool $persistent Optional parameter to set table layout persistence.
222 * @return bool Whether or not the table layout preferences will persist.
224 public function is_persistent($persistent = null) {
225 if ($persistent == true) {
226 $this->persistent = true;
228 return $this->persistent;
232 * Where to show download buttons.
233 * @param array $showat array of postions in which to show download buttons.
234 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
236 function show_download_buttons_at($showat) {
237 $this->showdownloadbuttonsat = $showat;
241 * Sets the is_sortable variable to the given boolean, sort_default_column to
242 * the given string, and the sort_default_order to the given integer.
243 * @param bool $bool
244 * @param string $defaultcolumn
245 * @param int $defaultorder
246 * @return void
248 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
249 $this->is_sortable = $bool;
250 $this->sort_default_column = $defaultcolumn;
251 $this->sort_default_order = $defaultorder;
255 * Use text sorting functions for this column (required for text columns with Oracle).
256 * Be warned that you cannot use this with column aliases. You can only do this
257 * with real columns. See MDL-40481 for an example.
258 * @param string column name
260 function text_sorting($column) {
261 $this->column_textsort[] = $column;
265 * Do not sort using this column
266 * @param string column name
268 function no_sorting($column) {
269 $this->column_nosort[] = $column;
273 * Is the column sortable?
274 * @param string column name, null means table
275 * @return bool
277 function is_sortable($column = null) {
278 if (empty($column)) {
279 return $this->is_sortable;
281 if (!$this->is_sortable) {
282 return false;
284 return !in_array($column, $this->column_nosort);
288 * Sets the is_collapsible variable to the given boolean.
289 * @param bool $bool
290 * @return void
292 function collapsible($bool) {
293 $this->is_collapsible = $bool;
297 * Sets the use_pages variable to the given boolean.
298 * @param bool $bool
299 * @return void
301 function pageable($bool) {
302 $this->use_pages = $bool;
306 * Sets the use_initials variable to the given boolean.
307 * @param bool $bool
308 * @return void
310 function initialbars($bool) {
311 $this->use_initials = $bool;
315 * Sets the pagesize variable to the given integer, the totalrows variable
316 * to the given integer, and the use_pages variable to true.
317 * @param int $perpage
318 * @param int $total
319 * @return void
321 function pagesize($perpage, $total) {
322 $this->pagesize = $perpage;
323 $this->totalrows = $total;
324 $this->use_pages = true;
328 * Assigns each given variable in the array to the corresponding index
329 * in the request class variable.
330 * @param array $variables
331 * @return void
333 function set_control_variables($variables) {
334 foreach ($variables as $what => $variable) {
335 if (isset($this->request[$what])) {
336 $this->request[$what] = $variable;
342 * Gives the given $value to the $attribute index of $this->attributes.
343 * @param string $attribute
344 * @param mixed $value
345 * @return void
347 function set_attribute($attribute, $value) {
348 $this->attributes[$attribute] = $value;
352 * What this method does is set the column so that if the same data appears in
353 * consecutive rows, then it is not repeated.
355 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
356 * that when one student has made multiple attempts, their name is only printed in the row
357 * for their first attempt.
358 * @param int $column the index of a column.
360 function column_suppress($column) {
361 if (isset($this->column_suppress[$column])) {
362 $this->column_suppress[$column] = true;
367 * Sets the given $column index to the given $classname in $this->column_class.
368 * @param int $column
369 * @param string $classname
370 * @return void
372 function column_class($column, $classname) {
373 if (isset($this->column_class[$column])) {
374 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
379 * Sets the given $column index and $property index to the given $value in $this->column_style.
380 * @param int $column
381 * @param string $property
382 * @param mixed $value
383 * @return void
385 function column_style($column, $property, $value) {
386 if (isset($this->column_style[$column])) {
387 $this->column_style[$column][$property] = $value;
392 * Sets all columns' $propertys to the given $value in $this->column_style.
393 * @param int $property
394 * @param string $value
395 * @return void
397 function column_style_all($property, $value) {
398 foreach (array_keys($this->columns) as $column) {
399 $this->column_style[$column][$property] = $value;
404 * Sets $this->baseurl.
405 * @param moodle_url|string $url the url with params needed to call up this page
407 function define_baseurl($url) {
408 $this->baseurl = new moodle_url($url);
412 * @param array $columns an array of identifying names for columns. If
413 * columns are sorted then column names must correspond to a field in sql.
415 function define_columns($columns) {
416 $this->columns = array();
417 $this->column_style = array();
418 $this->column_class = array();
419 $colnum = 0;
421 foreach ($columns as $column) {
422 $this->columns[$column] = $colnum++;
423 $this->column_style[$column] = array();
424 $this->column_class[$column] = '';
425 $this->column_suppress[$column] = false;
430 * @param array $headers numerical keyed array of displayed string titles
431 * for each column.
433 function define_headers($headers) {
434 $this->headers = $headers;
438 * Mark a specific column as being a table header using the column name defined in define_columns.
440 * Note: Only one column can be a header, and it will be rendered using a th tag.
442 * @param string $column
444 public function define_header_column(string $column) {
445 $this->headercolumn = $column;
449 * Defines a help icon for the header
451 * Always use this function if you need to create header with sorting and help icon.
453 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
455 public function define_help_for_headers($helpicons) {
456 $this->helpforheaders = $helpicons;
460 * Must be called after table is defined. Use methods above first. Cannot
461 * use functions below till after calling this method.
462 * @return type?
464 function setup() {
465 global $SESSION;
467 if (empty($this->columns) || empty($this->uniqueid)) {
468 return false;
471 // Load any existing user preferences.
472 if ($this->persistent) {
473 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
474 $oldprefs = $this->prefs;
475 } else if (isset($SESSION->flextable[$this->uniqueid])) {
476 $this->prefs = $SESSION->flextable[$this->uniqueid];
477 $oldprefs = $this->prefs;
480 // Set up default preferences if needed.
481 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
482 $this->prefs = array(
483 'collapse' => array(),
484 'sortby' => array(),
485 'i_first' => '',
486 'i_last' => '',
487 'textsort' => $this->column_textsort,
491 if (!isset($oldprefs)) {
492 $oldprefs = $this->prefs;
495 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
496 isset($this->columns[$showcol])) {
497 $this->prefs['collapse'][$showcol] = false;
499 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
500 isset($this->columns[$hidecol])) {
501 $this->prefs['collapse'][$hidecol] = true;
502 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
503 unset($this->prefs['sortby'][$hidecol]);
507 // Now, update the column attributes for collapsed columns
508 foreach (array_keys($this->columns) as $column) {
509 if (!empty($this->prefs['collapse'][$column])) {
510 $this->column_style[$column]['width'] = '10px';
514 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
515 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
516 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
517 && isset($this->columns['fullname']))) {
519 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
520 // This key already exists somewhere. Change its sortorder and bring it to the top.
521 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
522 unset($this->prefs['sortby'][$sortcol]);
523 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
524 } else {
525 // Key doesn't exist, so just add it to the beginning of the array, ascending order
526 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
529 // Finally, make sure that no more than $this->maxsortkeys are present into the array
530 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
533 // 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.
534 // This prevents results from being returned in a random order if the only order by column contains equal values.
535 if (!empty($this->sort_default_column)) {
536 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
537 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
538 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
542 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
543 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
544 $this->prefs['i_last'] = $ilast;
547 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
548 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
549 $this->prefs['i_first'] = $ifirst;
552 // Save user preferences if they have changed.
553 if ($this->prefs != $oldprefs) {
554 if ($this->persistent) {
555 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
556 } else {
557 $SESSION->flextable[$this->uniqueid] = $this->prefs;
560 unset($oldprefs);
562 if (empty($this->baseurl)) {
563 debugging('You should set baseurl when using flexible_table.');
564 global $PAGE;
565 $this->baseurl = $PAGE->url;
568 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
569 $this->setup = true;
571 // Always introduce the "flexible" class for the table if not specified
572 if (empty($this->attributes)) {
573 $this->attributes['class'] = 'flexible';
574 } else if (!isset($this->attributes['class'])) {
575 $this->attributes['class'] = 'flexible';
576 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
577 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
582 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
583 * @param string $uniqueid the identifier for a table.
584 * @return SQL fragment that can be used in an ORDER BY clause.
586 public static function get_sort_for_table($uniqueid) {
587 global $SESSION;
588 if (isset($SESSION->flextable[$uniqueid])) {
589 $prefs = $SESSION->flextable[$uniqueid];
590 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
591 return '';
594 if (empty($prefs['sortby'])) {
595 return '';
597 if (empty($prefs['textsort'])) {
598 $prefs['textsort'] = array();
601 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
605 * Prepare an an order by clause from the list of columns to be sorted.
606 * @param array $cols column name => SORT_ASC or SORT_DESC
607 * @return SQL fragment that can be used in an ORDER BY clause.
609 public static function construct_order_by($cols, $textsortcols=array()) {
610 global $DB;
611 $bits = array();
613 foreach ($cols as $column => $order) {
614 if (in_array($column, $textsortcols)) {
615 $column = $DB->sql_order_by_text($column);
617 if ($order == SORT_ASC) {
618 $bits[] = $column . ' ASC';
619 } else {
620 $bits[] = $column . ' DESC';
624 return implode(', ', $bits);
628 * @return SQL fragment that can be used in an ORDER BY clause.
630 public function get_sql_sort() {
631 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
635 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
636 * @return array column name => SORT_... constant.
638 public function get_sort_columns() {
639 if (!$this->setup) {
640 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
643 if (empty($this->prefs['sortby'])) {
644 return array();
647 foreach ($this->prefs['sortby'] as $column => $notused) {
648 if (isset($this->columns[$column])) {
649 continue; // This column is OK.
651 if (in_array($column, get_all_user_name_fields()) &&
652 isset($this->columns['fullname'])) {
653 continue; // This column is OK.
655 // This column is not OK.
656 unset($this->prefs['sortby'][$column]);
659 return $this->prefs['sortby'];
663 * @return int the offset for LIMIT clause of SQL
665 function get_page_start() {
666 if (!$this->use_pages) {
667 return '';
669 return $this->currpage * $this->pagesize;
673 * @return int the pagesize for LIMIT clause of SQL
675 function get_page_size() {
676 if (!$this->use_pages) {
677 return '';
679 return $this->pagesize;
683 * @return string sql to add to where statement.
685 function get_sql_where() {
686 global $DB;
688 $conditions = array();
689 $params = array();
691 if (isset($this->columns['fullname'])) {
692 static $i = 0;
693 $i++;
695 if (!empty($this->prefs['i_first'])) {
696 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
697 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
699 if (!empty($this->prefs['i_last'])) {
700 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
701 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
705 return array(implode(" AND ", $conditions), $params);
709 * Add a row of data to the table. This function takes an array or object with
710 * column names as keys or property names.
712 * It ignores any elements with keys that are not defined as columns. It
713 * puts in empty strings into the row when there is no element in the passed
714 * array corresponding to a column in the table. It puts the row elements in
715 * the proper order (internally row table data is stored by in arrays with
716 * a numerical index corresponding to the column number).
718 * @param object|array $rowwithkeys array keys or object property names are column names,
719 * as defined in call to define_columns.
720 * @param string $classname CSS class name to add to this row's tr tag.
722 function add_data_keyed($rowwithkeys, $classname = '') {
723 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
727 * Add a number of rows to the table at once. And optionally finish output after they have been added.
729 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
730 * object or array is added to table. We expect properties for the row array as would be
731 * passed to add_data_keyed.
732 * @param bool $finish
734 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
735 foreach ($rowstoadd as $row) {
736 if (is_null($row)) {
737 $this->add_separator();
738 } else {
739 $this->add_data_keyed($this->format_row($row));
742 if ($finish) {
743 $this->finish_output(!$this->is_downloading());
748 * Add a seperator line to table.
750 function add_separator() {
751 if (!$this->setup) {
752 return false;
754 $this->add_data(NULL);
758 * This method actually directly echoes the row passed to it now or adds it
759 * to the download. If this is the first row and start_output has not
760 * already been called this method also calls start_output to open the table
761 * or send headers for the downloaded.
762 * Can be used as before. print_html now calls finish_html to close table.
764 * @param array $row a numerically keyed row of data to add to the table.
765 * @param string $classname CSS class name to add to this row's tr tag.
766 * @return bool success.
768 function add_data($row, $classname = '') {
769 if (!$this->setup) {
770 return false;
772 if (!$this->started_output) {
773 $this->start_output();
775 if ($this->exportclass!==null) {
776 if ($row === null) {
777 $this->exportclass->add_seperator();
778 } else {
779 $this->exportclass->add_data($row);
781 } else {
782 $this->print_row($row, $classname);
784 return true;
788 * You should call this to finish outputting the table data after adding
789 * data to the table with add_data or add_data_keyed.
792 function finish_output($closeexportclassdoc = true) {
793 if ($this->exportclass!==null) {
794 $this->exportclass->finish_table();
795 if ($closeexportclassdoc) {
796 $this->exportclass->finish_document();
798 } else {
799 $this->finish_html();
804 * Hook that can be overridden in child classes to wrap a table in a form
805 * for example. Called only when there is data to display and not
806 * downloading.
808 function wrap_html_start() {
812 * Hook that can be overridden in child classes to wrap a table in a form
813 * for example. Called only when there is data to display and not
814 * downloading.
816 function wrap_html_finish() {
820 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
821 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
822 * displaying table as html, adding a div wrap, etc.
824 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
826 * @param array|object $row row of data from db used to make one row of the table.
827 * @return array one row for the table, added using add_data_keyed method.
829 function format_row($row) {
830 if (is_array($row)) {
831 $row = (object)$row;
833 $formattedrow = array();
834 foreach (array_keys($this->columns) as $column) {
835 $colmethodname = 'col_'.$column;
836 if (method_exists($this, $colmethodname)) {
837 $formattedcolumn = $this->$colmethodname($row);
838 } else {
839 $formattedcolumn = $this->other_cols($column, $row);
840 if ($formattedcolumn===NULL) {
841 $formattedcolumn = $row->$column;
844 $formattedrow[$column] = $formattedcolumn;
846 return $formattedrow;
850 * Fullname is treated as a special columname in tablelib and should always
851 * be treated the same as the fullname of a user.
852 * @uses $this->useridfield if the userid field is not expected to be id
853 * then you need to override $this->useridfield to point at the correct
854 * field for the user id.
856 * @param object $row the data from the db containing all fields from the
857 * users table necessary to construct the full name of the user in
858 * current language.
859 * @return string contents of cell in column 'fullname', for this row.
861 function col_fullname($row) {
862 global $COURSE;
864 $name = fullname($row);
865 if ($this->download) {
866 return $name;
869 $userid = $row->{$this->useridfield};
870 if ($COURSE->id == SITEID) {
871 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
872 } else {
873 $profileurl = new moodle_url('/user/view.php',
874 array('id' => $userid, 'course' => $COURSE->id));
876 return html_writer::link($profileurl, $name);
880 * You can override this method in a child class. See the description of
881 * build_table which calls this method.
883 function other_cols($column, $row) {
884 return NULL;
888 * Used from col_* functions when text is to be displayed. Does the
889 * right thing - either converts text to html or strips any html tags
890 * depending on if we are downloading and what is the download type. Params
891 * are the same as format_text function in weblib.php but some default
892 * options are changed.
894 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
895 if (!$this->is_downloading()) {
896 if (is_null($options)) {
897 $options = new stdClass;
899 //some sensible defaults
900 if (!isset($options->para)) {
901 $options->para = false;
903 if (!isset($options->newlines)) {
904 $options->newlines = false;
906 if (!isset($options->smiley)) {
907 $options->smiley = false;
909 if (!isset($options->filter)) {
910 $options->filter = false;
912 return format_text($text, $format, $options);
913 } else {
914 $eci = $this->export_class_instance();
915 return $eci->format_text($text, $format, $options, $courseid);
919 * This method is deprecated although the old api is still supported.
920 * @deprecated 1.9.2 - Jun 2, 2008
922 function print_html() {
923 if (!$this->setup) {
924 return false;
926 $this->finish_html();
930 * This function is not part of the public api.
931 * @return string initial of first name we are currently filtering by
933 function get_initial_first() {
934 if (!$this->use_initials) {
935 return NULL;
938 return $this->prefs['i_first'];
942 * This function is not part of the public api.
943 * @return string initial of last name we are currently filtering by
945 function get_initial_last() {
946 if (!$this->use_initials) {
947 return NULL;
950 return $this->prefs['i_last'];
954 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
955 * @param array $alpha of letters in the alphabet.
956 * @param string $current the currently selected letter.
957 * @param string $class class name to add to this initial bar.
958 * @param string $title the name to put in front of this initial bar.
959 * @param string $urlvar URL parameter name for this initial.
961 * @deprecated since Moodle 3.3
963 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
965 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
966 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
968 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
969 $title . ' : ';
970 if ($current) {
971 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
972 } else {
973 echo html_writer::tag('strong', get_string('all'));
976 foreach ($alpha as $letter) {
977 if ($letter === $current) {
978 echo html_writer::tag('strong', $letter);
979 } else {
980 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
984 echo html_writer::end_tag('div');
988 * This function is not part of the public api.
990 function print_initials_bar() {
991 global $OUTPUT;
993 $ifirst = $this->get_initial_first();
994 $ilast = $this->get_initial_last();
995 if (is_null($ifirst)) {
996 $ifirst = '';
998 if (is_null($ilast)) {
999 $ilast = '';
1002 if ((!empty($ifirst) || !empty($ilast) ||$this->use_initials)
1003 && isset($this->columns['fullname'])) {
1004 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
1005 $prefixlast = $this->request[TABLE_VAR_ILAST];
1006 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
1007 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
1013 * This function is not part of the public api.
1015 function print_nothing_to_display() {
1016 global $OUTPUT;
1018 // Render button to allow user to reset table preferences.
1019 echo $this->render_reset_button();
1021 $this->print_initials_bar();
1023 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1027 * This function is not part of the public api.
1029 function get_row_from_keyed($rowwithkeys) {
1030 if (is_object($rowwithkeys)) {
1031 $rowwithkeys = (array)$rowwithkeys;
1033 $row = array();
1034 foreach (array_keys($this->columns) as $column) {
1035 if (isset($rowwithkeys[$column])) {
1036 $row [] = $rowwithkeys[$column];
1037 } else {
1038 $row[] ='';
1041 return $row;
1045 * Get the html for the download buttons
1047 * Usually only use internally
1049 public function download_buttons() {
1050 global $OUTPUT;
1052 if ($this->is_downloadable() && !$this->is_downloading()) {
1053 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1054 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1055 } else {
1056 return '';
1061 * This function is not part of the public api.
1062 * You don't normally need to call this. It is called automatically when
1063 * needed when you start adding data to the table.
1066 function start_output() {
1067 $this->started_output = true;
1068 if ($this->exportclass!==null) {
1069 $this->exportclass->start_table($this->sheettitle);
1070 $this->exportclass->output_headers($this->headers);
1071 } else {
1072 $this->start_html();
1073 $this->print_headers();
1074 echo html_writer::start_tag('tbody');
1079 * This function is not part of the public api.
1081 function print_row($row, $classname = '') {
1082 echo $this->get_row_html($row, $classname);
1086 * Generate html code for the passed row.
1088 * @param array $row Row data.
1089 * @param string $classname classes to add.
1091 * @return string $html html code for the row passed.
1093 public function get_row_html($row, $classname = '') {
1094 static $suppress_lastrow = NULL;
1095 $rowclasses = array();
1097 if ($classname) {
1098 $rowclasses[] = $classname;
1101 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1102 $html = '';
1104 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1106 // If we have a separator, print it
1107 if ($row === NULL) {
1108 $colcount = count($this->columns);
1109 $html .= html_writer::tag('td', html_writer::tag('div', '',
1110 array('class' => 'tabledivider')), array('colspan' => $colcount));
1112 } else {
1113 $colbyindex = array_flip($this->columns);
1114 foreach ($row as $index => $data) {
1115 $column = $colbyindex[$index];
1117 $attributes = [
1118 'class' => "cell c{$index}" . $this->column_class[$column],
1119 'id' => "{$rowid}_c{$index}",
1120 'style' => $this->make_styles_string($this->column_style[$column]),
1123 $celltype = 'td';
1124 if ($this->headercolumn && $column == $this->headercolumn) {
1125 $celltype = 'th';
1126 $attributes['scope'] = 'row';
1129 if (empty($this->prefs['collapse'][$column])) {
1130 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1131 $content = '&nbsp;';
1132 } else {
1133 $content = $data;
1135 } else {
1136 $content = '&nbsp;';
1139 $html .= html_writer::tag($celltype, $content, $attributes);
1143 $html .= html_writer::end_tag('tr');
1145 $suppress_enabled = array_sum($this->column_suppress);
1146 if ($suppress_enabled) {
1147 $suppress_lastrow = $row;
1149 $this->currentrow++;
1150 return $html;
1154 * This function is not part of the public api.
1156 function finish_html() {
1157 global $OUTPUT;
1158 if (!$this->started_output) {
1159 //no data has been added to the table.
1160 $this->print_nothing_to_display();
1162 } else {
1163 // Print empty rows to fill the table to the current pagesize.
1164 // This is done so the header aria-controls attributes do not point to
1165 // non existant elements.
1166 $emptyrow = array_fill(0, count($this->columns), '');
1167 while ($this->currentrow < $this->pagesize) {
1168 $this->print_row($emptyrow, 'emptyrow');
1171 echo html_writer::end_tag('tbody');
1172 echo html_writer::end_tag('table');
1173 echo html_writer::end_tag('div');
1174 $this->wrap_html_finish();
1176 // Paging bar
1177 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1178 echo $this->download_buttons();
1181 if($this->use_pages) {
1182 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1183 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1184 echo $OUTPUT->render($pagingbar);
1190 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1191 * used by {@link print_headers()}.
1192 * @param string $column the column name, index into various names.
1193 * @param int $index numerical index of the column.
1194 * @return string HTML fragment.
1196 protected function show_hide_link($column, $index) {
1197 global $OUTPUT;
1198 // Some headers contain <br /> tags, do not include in title, hence the
1199 // strip tags.
1201 $ariacontrols = '';
1202 for ($i = 0; $i < $this->pagesize; $i++) {
1203 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1206 $ariacontrols = trim($ariacontrols);
1208 if (!empty($this->prefs['collapse'][$column])) {
1209 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1210 'aria-expanded' => 'false',
1211 'aria-controls' => $ariacontrols);
1212 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1213 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1215 } else if ($this->headers[$index] !== NULL) {
1216 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1217 'aria-expanded' => 'true',
1218 'aria-controls' => $ariacontrols);
1219 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1220 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1225 * This function is not part of the public api.
1227 function print_headers() {
1228 global $CFG, $OUTPUT, $PAGE;
1230 echo html_writer::start_tag('thead');
1231 echo html_writer::start_tag('tr');
1232 foreach ($this->columns as $column => $index) {
1234 $icon_hide = '';
1235 if ($this->is_collapsible) {
1236 $icon_hide = $this->show_hide_link($column, $index);
1239 $primarysortcolumn = '';
1240 $primarysortorder = '';
1241 if (reset($this->prefs['sortby'])) {
1242 $primarysortcolumn = key($this->prefs['sortby']);
1243 $primarysortorder = current($this->prefs['sortby']);
1246 switch ($column) {
1248 case 'fullname':
1249 // Check the full name display for sortable fields.
1250 if (has_capability('moodle/site:viewfullnames', $PAGE->context)) {
1251 $nameformat = $CFG->alternativefullnameformat;
1252 } else {
1253 $nameformat = $CFG->fullnamedisplay;
1256 if ($nameformat == 'language') {
1257 $nameformat = get_string('fullnamedisplay');
1260 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1262 if (!empty($requirednames)) {
1263 if ($this->is_sortable($column)) {
1264 // Done this way for the possibility of more than two sortable full name display fields.
1265 $this->headers[$index] = '';
1266 foreach ($requirednames as $name) {
1267 $sortname = $this->sort_link(get_string($name),
1268 $name, $primarysortcolumn === $name, $primarysortorder);
1269 $this->headers[$index] .= $sortname . ' / ';
1271 $helpicon = '';
1272 if (isset($this->helpforheaders[$index])) {
1273 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1275 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1278 break;
1280 case 'userpic':
1281 // do nothing, do not display sortable links
1282 break;
1284 default:
1285 if ($this->is_sortable($column)) {
1286 $helpicon = '';
1287 if (isset($this->helpforheaders[$index])) {
1288 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1290 $this->headers[$index] = $this->sort_link($this->headers[$index],
1291 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1295 $attributes = array(
1296 'class' => 'header c' . $index . $this->column_class[$column],
1297 'scope' => 'col',
1299 if ($this->headers[$index] === NULL) {
1300 $content = '&nbsp;';
1301 } else if (!empty($this->prefs['collapse'][$column])) {
1302 $content = $icon_hide;
1303 } else {
1304 if (is_array($this->column_style[$column])) {
1305 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1307 $helpicon = '';
1308 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1309 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1311 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1312 $icon_hide, array('class' => 'commands'));
1314 echo html_writer::tag('th', $content, $attributes);
1317 echo html_writer::end_tag('tr');
1318 echo html_writer::end_tag('thead');
1322 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1323 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1324 * @param int $order SORT_ASC or SORT_DESC
1325 * @return string HTML fragment.
1327 protected function sort_icon($isprimary, $order) {
1328 global $OUTPUT;
1330 if (!$isprimary) {
1331 return '';
1334 if ($order == SORT_ASC) {
1335 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1336 } else {
1337 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1342 * Generate the correct tool tip for changing the sort order. This is a
1343 * helper method used by {@link sort_link()}.
1344 * @param bool $isprimary whether the is column is the current primary sort column.
1345 * @param int $order SORT_ASC or SORT_DESC
1346 * @return string the correct title.
1348 protected function sort_order_name($isprimary, $order) {
1349 if ($isprimary && $order != SORT_ASC) {
1350 return get_string('desc');
1351 } else {
1352 return get_string('asc');
1357 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1358 * @param string $text the text for the link.
1359 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1360 * @param bool $isprimary whether the is column is the current primary sort column.
1361 * @param int $order SORT_ASC or SORT_DESC
1362 * @return string HTML fragment.
1364 protected function sort_link($text, $column, $isprimary, $order) {
1365 return html_writer::link($this->baseurl->out(false,
1366 array($this->request[TABLE_VAR_SORT] => $column)),
1367 $text . get_accesshide(get_string('sortby') . ' ' .
1368 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1369 $this->sort_icon($isprimary, $order);
1373 * This function is not part of the public api.
1375 function start_html() {
1376 global $OUTPUT;
1378 // Render button to allow user to reset table preferences.
1379 echo $this->render_reset_button();
1381 // Do we need to print initial bars?
1382 $this->print_initials_bar();
1384 // Paging bar
1385 if ($this->use_pages) {
1386 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1387 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1388 echo $OUTPUT->render($pagingbar);
1391 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1392 echo $this->download_buttons();
1395 $this->wrap_html_start();
1396 // Start of main data table
1398 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1399 echo html_writer::start_tag('table', $this->attributes);
1404 * This function is not part of the public api.
1405 * @param array $styles CSS-property => value
1406 * @return string values suitably to go in a style="" attribute in HTML.
1408 function make_styles_string($styles) {
1409 if (empty($styles)) {
1410 return null;
1413 $string = '';
1414 foreach($styles as $property => $value) {
1415 $string .= $property . ':' . $value . ';';
1417 return $string;
1421 * Generate the HTML for the table preferences reset button.
1423 * @return string HTML fragment, empty string if no need to reset
1425 protected function render_reset_button() {
1427 if (!$this->can_be_reset()) {
1428 return '';
1431 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1433 $html = html_writer::start_div('resettable mdl-right');
1434 $html .= html_writer::link($url, get_string('resettable'));
1435 $html .= html_writer::end_div();
1437 return $html;
1441 * Are there some table preferences that can be reset?
1443 * If true, then the "reset table preferences" widget should be displayed.
1445 * @return bool
1447 protected function can_be_reset() {
1449 // Loop through preferences and make sure they are empty or set to the default value.
1450 foreach ($this->prefs as $prefname => $prefval) {
1452 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1453 // Check if the actual sorting differs from the default one.
1454 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1455 return true;
1458 } else if ($prefname === 'collapse' and !empty($prefval)) {
1459 // Check if there are some collapsed columns (all are expanded by default).
1460 foreach ($prefval as $columnname => $iscollapsed) {
1461 if ($iscollapsed) {
1462 return true;
1466 } else if (!empty($prefval)) {
1467 // For all other cases, we just check if some preference is set.
1468 return true;
1472 return false;
1478 * @package moodlecore
1479 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1482 class table_sql extends flexible_table {
1484 public $countsql = NULL;
1485 public $countparams = NULL;
1487 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1489 public $sql = NULL;
1491 * @var array|\Traversable Data fetched from the db.
1493 public $rawdata = NULL;
1496 * @var bool Overriding default for this.
1498 public $is_sortable = true;
1500 * @var bool Overriding default for this.
1502 public $is_collapsible = true;
1505 * @param string $uniqueid a string identifying this table.Used as a key in
1506 * session vars.
1508 function __construct($uniqueid) {
1509 parent::__construct($uniqueid);
1510 // some sensible defaults
1511 $this->set_attribute('cellspacing', '0');
1512 $this->set_attribute('class', 'generaltable generalbox');
1516 * Take the data returned from the db_query and go through all the rows
1517 * processing each col using either col_{columnname} method or other_cols
1518 * method or if other_cols returns NULL then put the data straight into the
1519 * table.
1521 * After calling this function, don't forget to call close_recordset.
1523 public function build_table() {
1525 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1526 return;
1528 if (!$this->rawdata) {
1529 return;
1532 foreach ($this->rawdata as $row) {
1533 $formattedrow = $this->format_row($row);
1534 $this->add_data_keyed($formattedrow,
1535 $this->get_row_class($row));
1540 * Closes recordset (for use after building the table).
1542 public function close_recordset() {
1543 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1544 $this->rawdata instanceof moodle_recordset)) {
1545 $this->rawdata->close();
1546 $this->rawdata = null;
1551 * Get any extra classes names to add to this row in the HTML.
1552 * @param $row array the data for this row.
1553 * @return string added to the class="" attribute of the tr.
1555 function get_row_class($row) {
1556 return '';
1560 * This is only needed if you want to use different sql to count rows.
1561 * Used for example when perhaps all db JOINS are not needed when counting
1562 * records. You don't need to call this function the count_sql
1563 * will be generated automatically.
1565 * We need to count rows returned by the db seperately to the query itself
1566 * as we need to know how many pages of data we have to display.
1568 function set_count_sql($sql, array $params = NULL) {
1569 $this->countsql = $sql;
1570 $this->countparams = $params;
1574 * Set the sql to query the db. Query will be :
1575 * SELECT $fields FROM $from WHERE $where
1576 * Of course you can use sub-queries, JOINS etc. by putting them in the
1577 * appropriate clause of the query.
1579 function set_sql($fields, $from, $where, array $params = array()) {
1580 $this->sql = new stdClass();
1581 $this->sql->fields = $fields;
1582 $this->sql->from = $from;
1583 $this->sql->where = $where;
1584 $this->sql->params = $params;
1588 * Query the db. Store results in the table object for use by build_table.
1590 * @param int $pagesize size of page for paginated displayed table.
1591 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1592 * will only be used if there is a fullname column defined for the table.
1594 function query_db($pagesize, $useinitialsbar=true) {
1595 global $DB;
1596 if (!$this->is_downloading()) {
1597 if ($this->countsql === NULL) {
1598 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1599 $this->countparams = $this->sql->params;
1601 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1602 if ($useinitialsbar && !$this->is_downloading()) {
1603 $this->initialbars($grandtotal > $pagesize);
1606 list($wsql, $wparams) = $this->get_sql_where();
1607 if ($wsql) {
1608 $this->countsql .= ' AND '.$wsql;
1609 $this->countparams = array_merge($this->countparams, $wparams);
1611 $this->sql->where .= ' AND '.$wsql;
1612 $this->sql->params = array_merge($this->sql->params, $wparams);
1614 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1615 } else {
1616 $total = $grandtotal;
1619 $this->pagesize($pagesize, $total);
1622 // Fetch the attempts
1623 $sort = $this->get_sql_sort();
1624 if ($sort) {
1625 $sort = "ORDER BY $sort";
1627 $sql = "SELECT
1628 {$this->sql->fields}
1629 FROM {$this->sql->from}
1630 WHERE {$this->sql->where}
1631 {$sort}";
1633 if (!$this->is_downloading()) {
1634 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1635 } else {
1636 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1641 * Convenience method to call a number of methods for you to display the
1642 * table.
1644 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1645 global $DB;
1646 if (!$this->columns) {
1647 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1648 $this->sql->params, IGNORE_MULTIPLE);
1649 //if columns is not set then define columns as the keys of the rows returned
1650 //from the db.
1651 $this->define_columns(array_keys((array)$onerow));
1652 $this->define_headers(array_keys((array)$onerow));
1654 $this->setup();
1655 $this->query_db($pagesize, $useinitialsbar);
1656 $this->build_table();
1657 $this->close_recordset();
1658 $this->finish_output();
1664 * @package moodlecore
1665 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1668 class table_default_export_format_parent {
1670 * @var flexible_table or child class reference pointing to table class
1671 * object from which to export data.
1673 var $table;
1676 * @var bool output started. Keeps track of whether any output has been
1677 * started yet.
1679 var $documentstarted = false;
1682 * Constructor
1684 * @param flexible_table $table
1686 public function __construct(&$table) {
1687 $this->table =& $table;
1691 * Old syntax of class constructor. Deprecated in PHP7.
1693 * @deprecated since Moodle 3.1
1695 public function table_default_export_format_parent(&$table) {
1696 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1697 self::__construct($table);
1700 function set_table(&$table) {
1701 $this->table =& $table;
1704 function add_data($row) {
1705 return false;
1708 function add_seperator() {
1709 return false;
1712 function document_started() {
1713 return $this->documentstarted;
1716 * Given text in a variety of format codings, this function returns
1717 * the text as safe HTML or as plain text dependent on what is appropriate
1718 * for the download format. The default removes all tags.
1720 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1721 //use some whitespace to indicate where there was some line spacing.
1722 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1723 return strip_tags($text);
1728 * Dataformat exporter
1730 * @package core
1731 * @subpackage tablelib
1732 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1735 class table_dataformat_export_format extends table_default_export_format_parent {
1737 /** @var $dataformat */
1738 protected $dataformat;
1740 /** @var $rownum */
1741 protected $rownum = 0;
1743 /** @var $columns */
1744 protected $columns;
1747 * Constructor
1749 * @param string $table An sql table
1750 * @param string $dataformat type of dataformat for export
1752 public function __construct(&$table, $dataformat) {
1753 parent::__construct($table);
1755 if (ob_get_length()) {
1756 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1759 $classname = 'dataformat_' . $dataformat . '\writer';
1760 if (!class_exists($classname)) {
1761 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1763 $this->dataformat = new $classname;
1765 // The dataformat export time to first byte could take a while to generate...
1766 set_time_limit(0);
1768 // Close the session so that the users other tabs in the same session are not blocked.
1769 \core\session\manager::write_close();
1773 * Start document
1775 * @param string $filename
1776 * @param string $sheettitle
1778 public function start_document($filename, $sheettitle) {
1779 $this->documentstarted = true;
1780 $this->dataformat->set_filename($filename);
1781 $this->dataformat->send_http_headers();
1782 $this->dataformat->set_sheettitle($sheettitle);
1783 $this->dataformat->start_output();
1787 * Start export
1789 * @param string $sheettitle optional spreadsheet worksheet title
1791 public function start_table($sheettitle) {
1792 $this->dataformat->set_sheettitle($sheettitle);
1796 * Output headers
1798 * @param array $headers
1800 public function output_headers($headers) {
1801 $this->columns = $headers;
1802 if (method_exists($this->dataformat, 'write_header')) {
1803 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
1804 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1805 $this->dataformat->write_header($headers);
1806 } else {
1807 $this->dataformat->start_sheet($headers);
1812 * Add a row of data
1814 * @param array $row One record of data
1816 public function add_data($row) {
1817 $this->dataformat->write_record($row, $this->rownum++);
1818 return true;
1822 * Finish export
1824 public function finish_table() {
1825 if (method_exists($this->dataformat, 'write_footer')) {
1826 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
1827 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1828 $this->dataformat->write_footer($this->columns);
1829 } else {
1830 $this->dataformat->close_sheet($this->columns);
1835 * Finish download
1837 public function finish_document() {
1838 $this->dataformat->close_output();
1839 exit();