MDL-61321 mod_feedback: Return all the items responses
[moodle.git] / lib / tablelib.php
blob835c751e5222426c696bc525e9a3347bfdbe5cef
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 For create header with help icon.
63 private $helpforheaders = array();
64 var $columns = array();
65 var $column_style = array();
66 var $column_class = array();
67 var $column_suppress = array();
68 var $column_nosort = array('userpic');
69 private $column_textsort = array();
70 /** @var boolean Stores if setup has already been called on this flixible table. */
71 var $setup = false;
72 var $baseurl = NULL;
73 var $request = array();
75 /**
76 * @var bool Whether or not to store table properties in the user_preferences table.
78 private $persistent = false;
79 var $is_collapsible = false;
80 var $is_sortable = false;
81 var $use_pages = false;
82 var $use_initials = false;
84 var $maxsortkeys = 2;
85 var $pagesize = 30;
86 var $currpage = 0;
87 var $totalrows = 0;
88 var $currentrow = 0;
89 var $sort_default_column = NULL;
90 var $sort_default_order = SORT_ASC;
92 /**
93 * Array of positions in which to display download controls.
95 var $showdownloadbuttonsat= array(TABLE_P_TOP);
97 /**
98 * @var string Key of field returned by db query that is the id field of the
99 * user table or equivalent.
101 public $useridfield = 'id';
104 * @var string which download plugin to use. Default '' means none - print
105 * html table with paging. Property set by is_downloading which typically
106 * passes in cleaned data from $
108 var $download = '';
111 * @var bool whether data is downloadable from table. Determines whether
112 * to display download buttons. Set by method downloadable().
114 var $downloadable = false;
117 * @var bool Has start output been called yet?
119 var $started_output = false;
121 var $exportclass = null;
124 * @var array For storing user-customised table properties in the user_preferences db table.
126 private $prefs = array();
128 /** @var $sheettitle */
129 protected $sheettitle;
131 /** @var $filename */
132 protected $filename;
135 * Constructor
136 * @param string $uniqueid all tables have to have a unique id, this is used
137 * as a key when storing table properties like sort order in the session.
139 function __construct($uniqueid) {
140 $this->uniqueid = $uniqueid;
141 $this->request = array(
142 TABLE_VAR_SORT => 'tsort',
143 TABLE_VAR_HIDE => 'thide',
144 TABLE_VAR_SHOW => 'tshow',
145 TABLE_VAR_IFIRST => 'tifirst',
146 TABLE_VAR_ILAST => 'tilast',
147 TABLE_VAR_PAGE => 'page',
148 TABLE_VAR_RESET => 'treset'
153 * Call this to pass the download type. Use :
154 * $download = optional_param('download', '', PARAM_ALPHA);
155 * To get the download type. We assume that if you call this function with
156 * params that this table's data is downloadable, so we call is_downloadable
157 * for you (even if the param is '', which means no download this time.
158 * Also you can call this method with no params to get the current set
159 * download type.
160 * @param string $download dataformat type. One of csv, xhtml, ods, etc
161 * @param string $filename filename for downloads without file extension.
162 * @param string $sheettitle title for downloaded data.
163 * @return string download dataformat type. One of csv, xhtml, ods, etc
165 function is_downloading($download = null, $filename='', $sheettitle='') {
166 if ($download!==null) {
167 $this->sheettitle = $sheettitle;
168 $this->is_downloadable(true);
169 $this->download = $download;
170 $this->filename = clean_filename($filename);
171 $this->export_class_instance();
173 return $this->download;
177 * Get, and optionally set, the export class.
178 * @param $exportclass (optional) if passed, set the table to use this export class.
179 * @return table_default_export_format_parent the export class in use (after any set).
181 function export_class_instance($exportclass = null) {
182 if (!is_null($exportclass)) {
183 $this->started_output = true;
184 $this->exportclass = $exportclass;
185 $this->exportclass->table = $this;
186 } else if (is_null($this->exportclass) && !empty($this->download)) {
187 $this->exportclass = new table_dataformat_export_format($this, $this->download);
188 if (!$this->exportclass->document_started()) {
189 $this->exportclass->start_document($this->filename, $this->sheettitle);
192 return $this->exportclass;
196 * Probably don't need to call this directly. Calling is_downloading with a
197 * param automatically sets table as downloadable.
199 * @param bool $downloadable optional param to set whether data from
200 * table is downloadable. If ommitted this function can be used to get
201 * current state of table.
202 * @return bool whether table data is set to be downloadable.
204 function is_downloadable($downloadable = null) {
205 if ($downloadable !== null) {
206 $this->downloadable = $downloadable;
208 return $this->downloadable;
212 * Call with boolean true to store table layout changes in the user_preferences table.
213 * Note: user_preferences.value has a maximum length of 1333 characters.
214 * Call with no parameter to get current state of table persistence.
216 * @param bool $persistent Optional parameter to set table layout persistence.
217 * @return bool Whether or not the table layout preferences will persist.
219 public function is_persistent($persistent = null) {
220 if ($persistent == true) {
221 $this->persistent = true;
223 return $this->persistent;
227 * Where to show download buttons.
228 * @param array $showat array of postions in which to show download buttons.
229 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
231 function show_download_buttons_at($showat) {
232 $this->showdownloadbuttonsat = $showat;
236 * Sets the is_sortable variable to the given boolean, sort_default_column to
237 * the given string, and the sort_default_order to the given integer.
238 * @param bool $bool
239 * @param string $defaultcolumn
240 * @param int $defaultorder
241 * @return void
243 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
244 $this->is_sortable = $bool;
245 $this->sort_default_column = $defaultcolumn;
246 $this->sort_default_order = $defaultorder;
250 * Use text sorting functions for this column (required for text columns with Oracle).
251 * Be warned that you cannot use this with column aliases. You can only do this
252 * with real columns. See MDL-40481 for an example.
253 * @param string column name
255 function text_sorting($column) {
256 $this->column_textsort[] = $column;
260 * Do not sort using this column
261 * @param string column name
263 function no_sorting($column) {
264 $this->column_nosort[] = $column;
268 * Is the column sortable?
269 * @param string column name, null means table
270 * @return bool
272 function is_sortable($column = null) {
273 if (empty($column)) {
274 return $this->is_sortable;
276 if (!$this->is_sortable) {
277 return false;
279 return !in_array($column, $this->column_nosort);
283 * Sets the is_collapsible variable to the given boolean.
284 * @param bool $bool
285 * @return void
287 function collapsible($bool) {
288 $this->is_collapsible = $bool;
292 * Sets the use_pages variable to the given boolean.
293 * @param bool $bool
294 * @return void
296 function pageable($bool) {
297 $this->use_pages = $bool;
301 * Sets the use_initials variable to the given boolean.
302 * @param bool $bool
303 * @return void
305 function initialbars($bool) {
306 $this->use_initials = $bool;
310 * Sets the pagesize variable to the given integer, the totalrows variable
311 * to the given integer, and the use_pages variable to true.
312 * @param int $perpage
313 * @param int $total
314 * @return void
316 function pagesize($perpage, $total) {
317 $this->pagesize = $perpage;
318 $this->totalrows = $total;
319 $this->use_pages = true;
323 * Assigns each given variable in the array to the corresponding index
324 * in the request class variable.
325 * @param array $variables
326 * @return void
328 function set_control_variables($variables) {
329 foreach ($variables as $what => $variable) {
330 if (isset($this->request[$what])) {
331 $this->request[$what] = $variable;
337 * Gives the given $value to the $attribute index of $this->attributes.
338 * @param string $attribute
339 * @param mixed $value
340 * @return void
342 function set_attribute($attribute, $value) {
343 $this->attributes[$attribute] = $value;
347 * What this method does is set the column so that if the same data appears in
348 * consecutive rows, then it is not repeated.
350 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
351 * that when one student has made multiple attempts, their name is only printed in the row
352 * for their first attempt.
353 * @param int $column the index of a column.
355 function column_suppress($column) {
356 if (isset($this->column_suppress[$column])) {
357 $this->column_suppress[$column] = true;
362 * Sets the given $column index to the given $classname in $this->column_class.
363 * @param int $column
364 * @param string $classname
365 * @return void
367 function column_class($column, $classname) {
368 if (isset($this->column_class[$column])) {
369 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
374 * Sets the given $column index and $property index to the given $value in $this->column_style.
375 * @param int $column
376 * @param string $property
377 * @param mixed $value
378 * @return void
380 function column_style($column, $property, $value) {
381 if (isset($this->column_style[$column])) {
382 $this->column_style[$column][$property] = $value;
387 * Sets all columns' $propertys to the given $value in $this->column_style.
388 * @param int $property
389 * @param string $value
390 * @return void
392 function column_style_all($property, $value) {
393 foreach (array_keys($this->columns) as $column) {
394 $this->column_style[$column][$property] = $value;
399 * Sets $this->baseurl.
400 * @param moodle_url|string $url the url with params needed to call up this page
402 function define_baseurl($url) {
403 $this->baseurl = new moodle_url($url);
407 * @param array $columns an array of identifying names for columns. If
408 * columns are sorted then column names must correspond to a field in sql.
410 function define_columns($columns) {
411 $this->columns = array();
412 $this->column_style = array();
413 $this->column_class = array();
414 $colnum = 0;
416 foreach ($columns as $column) {
417 $this->columns[$column] = $colnum++;
418 $this->column_style[$column] = array();
419 $this->column_class[$column] = '';
420 $this->column_suppress[$column] = false;
425 * @param array $headers numerical keyed array of displayed string titles
426 * for each column.
428 function define_headers($headers) {
429 $this->headers = $headers;
433 * Defines a help icon for the header
435 * Always use this function if you need to create header with sorting and help icon.
437 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
439 public function define_help_for_headers($helpicons) {
440 $this->helpforheaders = $helpicons;
444 * Must be called after table is defined. Use methods above first. Cannot
445 * use functions below till after calling this method.
446 * @return type?
448 function setup() {
449 global $SESSION;
451 if (empty($this->columns) || empty($this->uniqueid)) {
452 return false;
455 // Load any existing user preferences.
456 if ($this->persistent) {
457 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
458 $oldprefs = $this->prefs;
459 } else if (isset($SESSION->flextable[$this->uniqueid])) {
460 $this->prefs = $SESSION->flextable[$this->uniqueid];
461 $oldprefs = $this->prefs;
464 // Set up default preferences if needed.
465 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
466 $this->prefs = array(
467 'collapse' => array(),
468 'sortby' => array(),
469 'i_first' => '',
470 'i_last' => '',
471 'textsort' => $this->column_textsort,
475 if (!isset($oldprefs)) {
476 $oldprefs = $this->prefs;
479 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
480 isset($this->columns[$showcol])) {
481 $this->prefs['collapse'][$showcol] = false;
483 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
484 isset($this->columns[$hidecol])) {
485 $this->prefs['collapse'][$hidecol] = true;
486 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
487 unset($this->prefs['sortby'][$hidecol]);
491 // Now, update the column attributes for collapsed columns
492 foreach (array_keys($this->columns) as $column) {
493 if (!empty($this->prefs['collapse'][$column])) {
494 $this->column_style[$column]['width'] = '10px';
498 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
499 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
500 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
501 && isset($this->columns['fullname']))) {
503 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
504 // This key already exists somewhere. Change its sortorder and bring it to the top.
505 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
506 unset($this->prefs['sortby'][$sortcol]);
507 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
508 } else {
509 // Key doesn't exist, so just add it to the beginning of the array, ascending order
510 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
513 // Finally, make sure that no more than $this->maxsortkeys are present into the array
514 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
517 // 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.
518 // This prevents results from being returned in a random order if the only order by column contains equal values.
519 if (!empty($this->sort_default_column)) {
520 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
521 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
522 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
526 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
527 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
528 $this->prefs['i_last'] = $ilast;
531 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
532 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
533 $this->prefs['i_first'] = $ifirst;
536 // Save user preferences if they have changed.
537 if ($this->prefs != $oldprefs) {
538 if ($this->persistent) {
539 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
540 } else {
541 $SESSION->flextable[$this->uniqueid] = $this->prefs;
544 unset($oldprefs);
546 if (empty($this->baseurl)) {
547 debugging('You should set baseurl when using flexible_table.');
548 global $PAGE;
549 $this->baseurl = $PAGE->url;
552 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
553 $this->setup = true;
555 // Always introduce the "flexible" class for the table if not specified
556 if (empty($this->attributes)) {
557 $this->attributes['class'] = 'flexible';
558 } else if (!isset($this->attributes['class'])) {
559 $this->attributes['class'] = 'flexible';
560 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
561 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
566 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
567 * @param string $uniqueid the identifier for a table.
568 * @return SQL fragment that can be used in an ORDER BY clause.
570 public static function get_sort_for_table($uniqueid) {
571 global $SESSION;
572 if (isset($SESSION->flextable[$uniqueid])) {
573 $prefs = $SESSION->flextable[$uniqueid];
574 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
575 return '';
578 if (empty($prefs['sortby'])) {
579 return '';
581 if (empty($prefs['textsort'])) {
582 $prefs['textsort'] = array();
585 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
589 * Prepare an an order by clause from the list of columns to be sorted.
590 * @param array $cols column name => SORT_ASC or SORT_DESC
591 * @return SQL fragment that can be used in an ORDER BY clause.
593 public static function construct_order_by($cols, $textsortcols=array()) {
594 global $DB;
595 $bits = array();
597 foreach ($cols as $column => $order) {
598 if (in_array($column, $textsortcols)) {
599 $column = $DB->sql_order_by_text($column);
601 if ($order == SORT_ASC) {
602 $bits[] = $column . ' ASC';
603 } else {
604 $bits[] = $column . ' DESC';
608 return implode(', ', $bits);
612 * @return SQL fragment that can be used in an ORDER BY clause.
614 public function get_sql_sort() {
615 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
619 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
620 * @return array column name => SORT_... constant.
622 public function get_sort_columns() {
623 if (!$this->setup) {
624 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
627 if (empty($this->prefs['sortby'])) {
628 return array();
631 foreach ($this->prefs['sortby'] as $column => $notused) {
632 if (isset($this->columns[$column])) {
633 continue; // This column is OK.
635 if (in_array($column, get_all_user_name_fields()) &&
636 isset($this->columns['fullname'])) {
637 continue; // This column is OK.
639 // This column is not OK.
640 unset($this->prefs['sortby'][$column]);
643 return $this->prefs['sortby'];
647 * @return int the offset for LIMIT clause of SQL
649 function get_page_start() {
650 if (!$this->use_pages) {
651 return '';
653 return $this->currpage * $this->pagesize;
657 * @return int the pagesize for LIMIT clause of SQL
659 function get_page_size() {
660 if (!$this->use_pages) {
661 return '';
663 return $this->pagesize;
667 * @return string sql to add to where statement.
669 function get_sql_where() {
670 global $DB;
672 $conditions = array();
673 $params = array();
675 if (isset($this->columns['fullname'])) {
676 static $i = 0;
677 $i++;
679 if (!empty($this->prefs['i_first'])) {
680 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
681 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
683 if (!empty($this->prefs['i_last'])) {
684 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
685 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
689 return array(implode(" AND ", $conditions), $params);
693 * Add a row of data to the table. This function takes an array or object with
694 * column names as keys or property names.
696 * It ignores any elements with keys that are not defined as columns. It
697 * puts in empty strings into the row when there is no element in the passed
698 * array corresponding to a column in the table. It puts the row elements in
699 * the proper order (internally row table data is stored by in arrays with
700 * a numerical index corresponding to the column number).
702 * @param object|array $rowwithkeys array keys or object property names are column names,
703 * as defined in call to define_columns.
704 * @param string $classname CSS class name to add to this row's tr tag.
706 function add_data_keyed($rowwithkeys, $classname = '') {
707 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
711 * Add a number of rows to the table at once. And optionally finish output after they have been added.
713 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
714 * object or array is added to table. We expect properties for the row array as would be
715 * passed to add_data_keyed.
716 * @param bool $finish
718 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
719 foreach ($rowstoadd as $row) {
720 if (is_null($row)) {
721 $this->add_separator();
722 } else {
723 $this->add_data_keyed($this->format_row($row));
726 if ($finish) {
727 $this->finish_output(!$this->is_downloading());
732 * Add a seperator line to table.
734 function add_separator() {
735 if (!$this->setup) {
736 return false;
738 $this->add_data(NULL);
742 * This method actually directly echoes the row passed to it now or adds it
743 * to the download. If this is the first row and start_output has not
744 * already been called this method also calls start_output to open the table
745 * or send headers for the downloaded.
746 * Can be used as before. print_html now calls finish_html to close table.
748 * @param array $row a numerically keyed row of data to add to the table.
749 * @param string $classname CSS class name to add to this row's tr tag.
750 * @return bool success.
752 function add_data($row, $classname = '') {
753 if (!$this->setup) {
754 return false;
756 if (!$this->started_output) {
757 $this->start_output();
759 if ($this->exportclass!==null) {
760 if ($row === null) {
761 $this->exportclass->add_seperator();
762 } else {
763 $this->exportclass->add_data($row);
765 } else {
766 $this->print_row($row, $classname);
768 return true;
772 * You should call this to finish outputting the table data after adding
773 * data to the table with add_data or add_data_keyed.
776 function finish_output($closeexportclassdoc = true) {
777 if ($this->exportclass!==null) {
778 $this->exportclass->finish_table();
779 if ($closeexportclassdoc) {
780 $this->exportclass->finish_document();
782 } else {
783 $this->finish_html();
788 * Hook that can be overridden in child classes to wrap a table in a form
789 * for example. Called only when there is data to display and not
790 * downloading.
792 function wrap_html_start() {
796 * Hook that can be overridden in child classes to wrap a table in a form
797 * for example. Called only when there is data to display and not
798 * downloading.
800 function wrap_html_finish() {
804 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
805 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
806 * displaying table as html, adding a div wrap, etc.
808 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
810 * @param array|object $row row of data from db used to make one row of the table.
811 * @return array one row for the table, added using add_data_keyed method.
813 function format_row($row) {
814 if (is_array($row)) {
815 $row = (object)$row;
817 $formattedrow = array();
818 foreach (array_keys($this->columns) as $column) {
819 $colmethodname = 'col_'.$column;
820 if (method_exists($this, $colmethodname)) {
821 $formattedcolumn = $this->$colmethodname($row);
822 } else {
823 $formattedcolumn = $this->other_cols($column, $row);
824 if ($formattedcolumn===NULL) {
825 $formattedcolumn = $row->$column;
828 $formattedrow[$column] = $formattedcolumn;
830 return $formattedrow;
834 * Fullname is treated as a special columname in tablelib and should always
835 * be treated the same as the fullname of a user.
836 * @uses $this->useridfield if the userid field is not expected to be id
837 * then you need to override $this->useridfield to point at the correct
838 * field for the user id.
840 * @param object $row the data from the db containing all fields from the
841 * users table necessary to construct the full name of the user in
842 * current language.
843 * @return string contents of cell in column 'fullname', for this row.
845 function col_fullname($row) {
846 global $COURSE;
848 $name = fullname($row);
849 if ($this->download) {
850 return $name;
853 $userid = $row->{$this->useridfield};
854 if ($COURSE->id == SITEID) {
855 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
856 } else {
857 $profileurl = new moodle_url('/user/view.php',
858 array('id' => $userid, 'course' => $COURSE->id));
860 return html_writer::link($profileurl, $name);
864 * You can override this method in a child class. See the description of
865 * build_table which calls this method.
867 function other_cols($column, $row) {
868 return NULL;
872 * Used from col_* functions when text is to be displayed. Does the
873 * right thing - either converts text to html or strips any html tags
874 * depending on if we are downloading and what is the download type. Params
875 * are the same as format_text function in weblib.php but some default
876 * options are changed.
878 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
879 if (!$this->is_downloading()) {
880 if (is_null($options)) {
881 $options = new stdClass;
883 //some sensible defaults
884 if (!isset($options->para)) {
885 $options->para = false;
887 if (!isset($options->newlines)) {
888 $options->newlines = false;
890 if (!isset($options->smiley)) {
891 $options->smiley = false;
893 if (!isset($options->filter)) {
894 $options->filter = false;
896 return format_text($text, $format, $options);
897 } else {
898 $eci = $this->export_class_instance();
899 return $eci->format_text($text, $format, $options, $courseid);
903 * This method is deprecated although the old api is still supported.
904 * @deprecated 1.9.2 - Jun 2, 2008
906 function print_html() {
907 if (!$this->setup) {
908 return false;
910 $this->finish_html();
914 * This function is not part of the public api.
915 * @return string initial of first name we are currently filtering by
917 * @deprecated since Moodle 3.3
919 function get_initial_first() {
920 debugging('Method get_initial_first() is no longer used and has been deprecated, ' .
921 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
922 if (!$this->use_initials) {
923 return NULL;
926 return $this->prefs['i_first'];
930 * This function is not part of the public api.
931 * @return string initial of last name we are currently filtering by
933 * @deprecated since Moodle 3.3
935 function get_initial_last() {
936 debugging('Method get_initial_last() is no longer used and has been deprecated, ' .
937 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
938 if (!$this->use_initials) {
939 return NULL;
942 return $this->prefs['i_last'];
946 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
947 * @param array $alpha of letters in the alphabet.
948 * @param string $current the currently selected letter.
949 * @param string $class class name to add to this initial bar.
950 * @param string $title the name to put in front of this initial bar.
951 * @param string $urlvar URL parameter name for this initial.
953 * @deprecated since Moodle 3.3
955 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
957 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
958 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
960 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
961 $title . ' : ';
962 if ($current) {
963 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
964 } else {
965 echo html_writer::tag('strong', get_string('all'));
968 foreach ($alpha as $letter) {
969 if ($letter === $current) {
970 echo html_writer::tag('strong', $letter);
971 } else {
972 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
976 echo html_writer::end_tag('div');
980 * This function is not part of the public api.
982 function print_initials_bar() {
983 global $OUTPUT;
985 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
986 && isset($this->columns['fullname'])) {
988 if (!empty($this->prefs['i_first'])) {
989 $ifirst = $this->prefs['i_first'];
990 } else {
991 $ifirst = '';
994 if (!empty($this->prefs['i_last'])) {
995 $ilast = $this->prefs['i_last'];
996 } else {
997 $ilast = '';
1000 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
1001 $prefixlast = $this->request[TABLE_VAR_ILAST];
1002 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
1003 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
1009 * This function is not part of the public api.
1011 function print_nothing_to_display() {
1012 global $OUTPUT;
1014 // Render button to allow user to reset table preferences.
1015 echo $this->render_reset_button();
1017 $this->print_initials_bar();
1019 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1023 * This function is not part of the public api.
1025 function get_row_from_keyed($rowwithkeys) {
1026 if (is_object($rowwithkeys)) {
1027 $rowwithkeys = (array)$rowwithkeys;
1029 $row = array();
1030 foreach (array_keys($this->columns) as $column) {
1031 if (isset($rowwithkeys[$column])) {
1032 $row [] = $rowwithkeys[$column];
1033 } else {
1034 $row[] ='';
1037 return $row;
1041 * Get the html for the download buttons
1043 * Usually only use internally
1045 public function download_buttons() {
1046 global $OUTPUT;
1048 if ($this->is_downloadable() && !$this->is_downloading()) {
1049 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1050 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1051 } else {
1052 return '';
1057 * This function is not part of the public api.
1058 * You don't normally need to call this. It is called automatically when
1059 * needed when you start adding data to the table.
1062 function start_output() {
1063 $this->started_output = true;
1064 if ($this->exportclass!==null) {
1065 $this->exportclass->start_table($this->sheettitle);
1066 $this->exportclass->output_headers($this->headers);
1067 } else {
1068 $this->start_html();
1069 $this->print_headers();
1070 echo html_writer::start_tag('tbody');
1075 * This function is not part of the public api.
1077 function print_row($row, $classname = '') {
1078 echo $this->get_row_html($row, $classname);
1082 * Generate html code for the passed row.
1084 * @param array $row Row data.
1085 * @param string $classname classes to add.
1087 * @return string $html html code for the row passed.
1089 public function get_row_html($row, $classname = '') {
1090 static $suppress_lastrow = NULL;
1091 $rowclasses = array();
1093 if ($classname) {
1094 $rowclasses[] = $classname;
1097 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1098 $html = '';
1100 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1102 // If we have a separator, print it
1103 if ($row === NULL) {
1104 $colcount = count($this->columns);
1105 $html .= html_writer::tag('td', html_writer::tag('div', '',
1106 array('class' => 'tabledivider')), array('colspan' => $colcount));
1108 } else {
1109 $colbyindex = array_flip($this->columns);
1110 foreach ($row as $index => $data) {
1111 $column = $colbyindex[$index];
1113 if (empty($this->prefs['collapse'][$column])) {
1114 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1115 $content = '&nbsp;';
1116 } else {
1117 $content = $data;
1119 } else {
1120 $content = '&nbsp;';
1123 $html .= html_writer::tag('td', $content, array(
1124 'class' => 'cell c' . $index . $this->column_class[$column],
1125 'id' => $rowid . '_c' . $index,
1126 'style' => $this->make_styles_string($this->column_style[$column])));
1130 $html .= html_writer::end_tag('tr');
1132 $suppress_enabled = array_sum($this->column_suppress);
1133 if ($suppress_enabled) {
1134 $suppress_lastrow = $row;
1136 $this->currentrow++;
1137 return $html;
1141 * This function is not part of the public api.
1143 function finish_html() {
1144 global $OUTPUT;
1145 if (!$this->started_output) {
1146 //no data has been added to the table.
1147 $this->print_nothing_to_display();
1149 } else {
1150 // Print empty rows to fill the table to the current pagesize.
1151 // This is done so the header aria-controls attributes do not point to
1152 // non existant elements.
1153 $emptyrow = array_fill(0, count($this->columns), '');
1154 while ($this->currentrow < $this->pagesize) {
1155 $this->print_row($emptyrow, 'emptyrow');
1158 echo html_writer::end_tag('tbody');
1159 echo html_writer::end_tag('table');
1160 echo html_writer::end_tag('div');
1161 $this->wrap_html_finish();
1163 // Paging bar
1164 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1165 echo $this->download_buttons();
1168 if($this->use_pages) {
1169 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1170 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1171 echo $OUTPUT->render($pagingbar);
1177 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1178 * used by {@link print_headers()}.
1179 * @param string $column the column name, index into various names.
1180 * @param int $index numerical index of the column.
1181 * @return string HTML fragment.
1183 protected function show_hide_link($column, $index) {
1184 global $OUTPUT;
1185 // Some headers contain <br /> tags, do not include in title, hence the
1186 // strip tags.
1188 $ariacontrols = '';
1189 for ($i = 0; $i < $this->pagesize; $i++) {
1190 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1193 $ariacontrols = trim($ariacontrols);
1195 if (!empty($this->prefs['collapse'][$column])) {
1196 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1197 'aria-expanded' => 'false',
1198 'aria-controls' => $ariacontrols);
1199 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1200 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1202 } else if ($this->headers[$index] !== NULL) {
1203 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1204 'aria-expanded' => 'true',
1205 'aria-controls' => $ariacontrols);
1206 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1207 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1212 * This function is not part of the public api.
1214 function print_headers() {
1215 global $CFG, $OUTPUT;
1217 echo html_writer::start_tag('thead');
1218 echo html_writer::start_tag('tr');
1219 foreach ($this->columns as $column => $index) {
1221 $icon_hide = '';
1222 if ($this->is_collapsible) {
1223 $icon_hide = $this->show_hide_link($column, $index);
1226 $primarysortcolumn = '';
1227 $primarysortorder = '';
1228 if (reset($this->prefs['sortby'])) {
1229 $primarysortcolumn = key($this->prefs['sortby']);
1230 $primarysortorder = current($this->prefs['sortby']);
1233 switch ($column) {
1235 case 'fullname':
1236 // Check the full name display for sortable fields.
1237 $nameformat = $CFG->fullnamedisplay;
1238 if ($nameformat == 'language') {
1239 $nameformat = get_string('fullnamedisplay');
1241 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1243 if (!empty($requirednames)) {
1244 if ($this->is_sortable($column)) {
1245 // Done this way for the possibility of more than two sortable full name display fields.
1246 $this->headers[$index] = '';
1247 foreach ($requirednames as $name) {
1248 $sortname = $this->sort_link(get_string($name),
1249 $name, $primarysortcolumn === $name, $primarysortorder);
1250 $this->headers[$index] .= $sortname . ' / ';
1252 $helpicon = '';
1253 if (isset($this->helpforheaders[$index])) {
1254 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1256 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1259 break;
1261 case 'userpic':
1262 // do nothing, do not display sortable links
1263 break;
1265 default:
1266 if ($this->is_sortable($column)) {
1267 $helpicon = '';
1268 if (isset($this->helpforheaders[$index])) {
1269 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1271 $this->headers[$index] = $this->sort_link($this->headers[$index],
1272 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1276 $attributes = array(
1277 'class' => 'header c' . $index . $this->column_class[$column],
1278 'scope' => 'col',
1280 if ($this->headers[$index] === NULL) {
1281 $content = '&nbsp;';
1282 } else if (!empty($this->prefs['collapse'][$column])) {
1283 $content = $icon_hide;
1284 } else {
1285 if (is_array($this->column_style[$column])) {
1286 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1288 $helpicon = '';
1289 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1290 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1292 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1293 $icon_hide, array('class' => 'commands'));
1295 echo html_writer::tag('th', $content, $attributes);
1298 echo html_writer::end_tag('tr');
1299 echo html_writer::end_tag('thead');
1303 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1304 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1305 * @param int $order SORT_ASC or SORT_DESC
1306 * @return string HTML fragment.
1308 protected function sort_icon($isprimary, $order) {
1309 global $OUTPUT;
1311 if (!$isprimary) {
1312 return '';
1315 if ($order == SORT_ASC) {
1316 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1317 } else {
1318 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1323 * Generate the correct tool tip for changing the sort order. This is a
1324 * helper method used by {@link sort_link()}.
1325 * @param bool $isprimary whether the is column is the current primary sort column.
1326 * @param int $order SORT_ASC or SORT_DESC
1327 * @return string the correct title.
1329 protected function sort_order_name($isprimary, $order) {
1330 if ($isprimary && $order != SORT_ASC) {
1331 return get_string('desc');
1332 } else {
1333 return get_string('asc');
1338 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1339 * @param string $text the text for the link.
1340 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1341 * @param bool $isprimary whether the is column is the current primary sort column.
1342 * @param int $order SORT_ASC or SORT_DESC
1343 * @return string HTML fragment.
1345 protected function sort_link($text, $column, $isprimary, $order) {
1346 return html_writer::link($this->baseurl->out(false,
1347 array($this->request[TABLE_VAR_SORT] => $column)),
1348 $text . get_accesshide(get_string('sortby') . ' ' .
1349 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1350 $this->sort_icon($isprimary, $order);
1354 * This function is not part of the public api.
1356 function start_html() {
1357 global $OUTPUT;
1359 // Render button to allow user to reset table preferences.
1360 echo $this->render_reset_button();
1362 // Do we need to print initial bars?
1363 $this->print_initials_bar();
1365 // Paging bar
1366 if ($this->use_pages) {
1367 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1368 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1369 echo $OUTPUT->render($pagingbar);
1372 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1373 echo $this->download_buttons();
1376 $this->wrap_html_start();
1377 // Start of main data table
1379 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1380 echo html_writer::start_tag('table', $this->attributes);
1385 * This function is not part of the public api.
1386 * @param array $styles CSS-property => value
1387 * @return string values suitably to go in a style="" attribute in HTML.
1389 function make_styles_string($styles) {
1390 if (empty($styles)) {
1391 return null;
1394 $string = '';
1395 foreach($styles as $property => $value) {
1396 $string .= $property . ':' . $value . ';';
1398 return $string;
1402 * Generate the HTML for the table preferences reset button.
1404 * @return string HTML fragment, empty string if no need to reset
1406 protected function render_reset_button() {
1408 if (!$this->can_be_reset()) {
1409 return '';
1412 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1414 $html = html_writer::start_div('resettable mdl-right');
1415 $html .= html_writer::link($url, get_string('resettable'));
1416 $html .= html_writer::end_div();
1418 return $html;
1422 * Are there some table preferences that can be reset?
1424 * If true, then the "reset table preferences" widget should be displayed.
1426 * @return bool
1428 protected function can_be_reset() {
1430 // Loop through preferences and make sure they are empty or set to the default value.
1431 foreach ($this->prefs as $prefname => $prefval) {
1433 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1434 // Check if the actual sorting differs from the default one.
1435 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1436 return true;
1439 } else if ($prefname === 'collapse' and !empty($prefval)) {
1440 // Check if there are some collapsed columns (all are expanded by default).
1441 foreach ($prefval as $columnname => $iscollapsed) {
1442 if ($iscollapsed) {
1443 return true;
1447 } else if (!empty($prefval)) {
1448 // For all other cases, we just check if some preference is set.
1449 return true;
1453 return false;
1459 * @package moodlecore
1460 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1461 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1463 class table_sql extends flexible_table {
1465 public $countsql = NULL;
1466 public $countparams = NULL;
1468 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1470 public $sql = NULL;
1472 * @var array|\Traversable Data fetched from the db.
1474 public $rawdata = NULL;
1477 * @var bool Overriding default for this.
1479 public $is_sortable = true;
1481 * @var bool Overriding default for this.
1483 public $is_collapsible = true;
1486 * @param string $uniqueid a string identifying this table.Used as a key in
1487 * session vars.
1489 function __construct($uniqueid) {
1490 parent::__construct($uniqueid);
1491 // some sensible defaults
1492 $this->set_attribute('cellspacing', '0');
1493 $this->set_attribute('class', 'generaltable generalbox');
1497 * Take the data returned from the db_query and go through all the rows
1498 * processing each col using either col_{columnname} method or other_cols
1499 * method or if other_cols returns NULL then put the data straight into the
1500 * table.
1502 * After calling this function, don't forget to call close_recordset.
1504 public function build_table() {
1506 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1507 return;
1509 if (!$this->rawdata) {
1510 return;
1513 foreach ($this->rawdata as $row) {
1514 $formattedrow = $this->format_row($row);
1515 $this->add_data_keyed($formattedrow,
1516 $this->get_row_class($row));
1521 * Closes recordset (for use after building the table).
1523 public function close_recordset() {
1524 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1525 $this->rawdata instanceof moodle_recordset)) {
1526 $this->rawdata->close();
1527 $this->rawdata = null;
1532 * Get any extra classes names to add to this row in the HTML.
1533 * @param $row array the data for this row.
1534 * @return string added to the class="" attribute of the tr.
1536 function get_row_class($row) {
1537 return '';
1541 * This is only needed if you want to use different sql to count rows.
1542 * Used for example when perhaps all db JOINS are not needed when counting
1543 * records. You don't need to call this function the count_sql
1544 * will be generated automatically.
1546 * We need to count rows returned by the db seperately to the query itself
1547 * as we need to know how many pages of data we have to display.
1549 function set_count_sql($sql, array $params = NULL) {
1550 $this->countsql = $sql;
1551 $this->countparams = $params;
1555 * Set the sql to query the db. Query will be :
1556 * SELECT $fields FROM $from WHERE $where
1557 * Of course you can use sub-queries, JOINS etc. by putting them in the
1558 * appropriate clause of the query.
1560 function set_sql($fields, $from, $where, array $params = array()) {
1561 $this->sql = new stdClass();
1562 $this->sql->fields = $fields;
1563 $this->sql->from = $from;
1564 $this->sql->where = $where;
1565 $this->sql->params = $params;
1569 * Query the db. Store results in the table object for use by build_table.
1571 * @param int $pagesize size of page for paginated displayed table.
1572 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1573 * will only be used if there is a fullname column defined for the table.
1575 function query_db($pagesize, $useinitialsbar=true) {
1576 global $DB;
1577 if (!$this->is_downloading()) {
1578 if ($this->countsql === NULL) {
1579 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1580 $this->countparams = $this->sql->params;
1582 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1583 if ($useinitialsbar && !$this->is_downloading()) {
1584 $this->initialbars($grandtotal > $pagesize);
1587 list($wsql, $wparams) = $this->get_sql_where();
1588 if ($wsql) {
1589 $this->countsql .= ' AND '.$wsql;
1590 $this->countparams = array_merge($this->countparams, $wparams);
1592 $this->sql->where .= ' AND '.$wsql;
1593 $this->sql->params = array_merge($this->sql->params, $wparams);
1595 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1596 } else {
1597 $total = $grandtotal;
1600 $this->pagesize($pagesize, $total);
1603 // Fetch the attempts
1604 $sort = $this->get_sql_sort();
1605 if ($sort) {
1606 $sort = "ORDER BY $sort";
1608 $sql = "SELECT
1609 {$this->sql->fields}
1610 FROM {$this->sql->from}
1611 WHERE {$this->sql->where}
1612 {$sort}";
1614 if (!$this->is_downloading()) {
1615 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1616 } else {
1617 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1622 * Convenience method to call a number of methods for you to display the
1623 * table.
1625 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1626 global $DB;
1627 if (!$this->columns) {
1628 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1629 $this->sql->params, IGNORE_MULTIPLE);
1630 //if columns is not set then define columns as the keys of the rows returned
1631 //from the db.
1632 $this->define_columns(array_keys((array)$onerow));
1633 $this->define_headers(array_keys((array)$onerow));
1635 $this->setup();
1636 $this->query_db($pagesize, $useinitialsbar);
1637 $this->build_table();
1638 $this->close_recordset();
1639 $this->finish_output();
1645 * @package moodlecore
1646 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1649 class table_default_export_format_parent {
1651 * @var flexible_table or child class reference pointing to table class
1652 * object from which to export data.
1654 var $table;
1657 * @var bool output started. Keeps track of whether any output has been
1658 * started yet.
1660 var $documentstarted = false;
1663 * Constructor
1665 * @param flexible_table $table
1667 public function __construct(&$table) {
1668 $this->table =& $table;
1672 * Old syntax of class constructor. Deprecated in PHP7.
1674 * @deprecated since Moodle 3.1
1676 public function table_default_export_format_parent(&$table) {
1677 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1678 self::__construct($table);
1681 function set_table(&$table) {
1682 $this->table =& $table;
1685 function add_data($row) {
1686 return false;
1689 function add_seperator() {
1690 return false;
1693 function document_started() {
1694 return $this->documentstarted;
1697 * Given text in a variety of format codings, this function returns
1698 * the text as safe HTML or as plain text dependent on what is appropriate
1699 * for the download format. The default removes all tags.
1701 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1702 //use some whitespace to indicate where there was some line spacing.
1703 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1704 return strip_tags($text);
1709 * Dataformat exporter
1711 * @package core
1712 * @subpackage tablelib
1713 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1716 class table_dataformat_export_format extends table_default_export_format_parent {
1718 /** @var $dataformat */
1719 protected $dataformat;
1721 /** @var $rownum */
1722 protected $rownum = 0;
1724 /** @var $columns */
1725 protected $columns;
1728 * Constructor
1730 * @param string $table An sql table
1731 * @param string $dataformat type of dataformat for export
1733 public function __construct(&$table, $dataformat) {
1734 parent::__construct($table);
1736 if (ob_get_length()) {
1737 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1740 $classname = 'dataformat_' . $dataformat . '\writer';
1741 if (!class_exists($classname)) {
1742 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1744 $this->dataformat = new $classname;
1746 // The dataformat export time to first byte could take a while to generate...
1747 set_time_limit(0);
1749 // Close the session so that the users other tabs in the same session are not blocked.
1750 \core\session\manager::write_close();
1754 * Start document
1756 * @param string $filename
1757 * @param string $sheettitle
1759 public function start_document($filename, $sheettitle) {
1760 $this->documentstarted = true;
1761 $this->dataformat->set_filename($filename);
1762 $this->dataformat->send_http_headers();
1763 $this->dataformat->set_sheettitle($sheettitle);
1764 $this->dataformat->start_output();
1768 * Start export
1770 * @param string $sheettitle optional spreadsheet worksheet title
1772 public function start_table($sheettitle) {
1773 $this->dataformat->set_sheettitle($sheettitle);
1777 * Output headers
1779 * @param array $headers
1781 public function output_headers($headers) {
1782 $this->columns = $headers;
1783 if (method_exists($this->dataformat, 'write_header')) {
1784 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
1785 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1786 $this->dataformat->write_header($headers);
1787 } else {
1788 $this->dataformat->start_sheet($headers);
1793 * Add a row of data
1795 * @param array $row One record of data
1797 public function add_data($row) {
1798 $this->dataformat->write_record($row, $this->rownum++);
1799 return true;
1803 * Finish export
1805 public function finish_table() {
1806 if (method_exists($this->dataformat, 'write_footer')) {
1807 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
1808 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1809 $this->dataformat->write_footer($this->columns);
1810 } else {
1811 $this->dataformat->close_sheet($this->columns);
1816 * Finish download
1818 public function finish_document() {
1819 $this->dataformat->close_output();
1820 exit();