MDL-62388 tool_dataprivacy: Fixing bs4stable table layout
[moodle.git] / lib / tablelib.php
blob8235cbf1c8106d791d211d5780c7c3ac78fa1047
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 function get_initial_first() {
918 if (!$this->use_initials) {
919 return NULL;
922 return $this->prefs['i_first'];
926 * This function is not part of the public api.
927 * @return string initial of last name we are currently filtering by
929 function get_initial_last() {
930 if (!$this->use_initials) {
931 return NULL;
934 return $this->prefs['i_last'];
938 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
939 * @param array $alpha of letters in the alphabet.
940 * @param string $current the currently selected letter.
941 * @param string $class class name to add to this initial bar.
942 * @param string $title the name to put in front of this initial bar.
943 * @param string $urlvar URL parameter name for this initial.
945 * @deprecated since Moodle 3.3
947 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
949 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
950 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
952 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
953 $title . ' : ';
954 if ($current) {
955 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
956 } else {
957 echo html_writer::tag('strong', get_string('all'));
960 foreach ($alpha as $letter) {
961 if ($letter === $current) {
962 echo html_writer::tag('strong', $letter);
963 } else {
964 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
968 echo html_writer::end_tag('div');
972 * This function is not part of the public api.
974 function print_initials_bar() {
975 global $OUTPUT;
977 $ifirst = $this->get_initial_first();
978 $ilast = $this->get_initial_last();
979 if (is_null($ifirst)) {
980 $ifirst = '';
982 if (is_null($ilast)) {
983 $ilast = '';
986 if ((!empty($ifirst) || !empty($ilast) ||$this->use_initials)
987 && isset($this->columns['fullname'])) {
988 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
989 $prefixlast = $this->request[TABLE_VAR_ILAST];
990 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
991 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
997 * This function is not part of the public api.
999 function print_nothing_to_display() {
1000 global $OUTPUT;
1002 // Render button to allow user to reset table preferences.
1003 echo $this->render_reset_button();
1005 $this->print_initials_bar();
1007 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1011 * This function is not part of the public api.
1013 function get_row_from_keyed($rowwithkeys) {
1014 if (is_object($rowwithkeys)) {
1015 $rowwithkeys = (array)$rowwithkeys;
1017 $row = array();
1018 foreach (array_keys($this->columns) as $column) {
1019 if (isset($rowwithkeys[$column])) {
1020 $row [] = $rowwithkeys[$column];
1021 } else {
1022 $row[] ='';
1025 return $row;
1029 * Get the html for the download buttons
1031 * Usually only use internally
1033 public function download_buttons() {
1034 global $OUTPUT;
1036 if ($this->is_downloadable() && !$this->is_downloading()) {
1037 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1038 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1039 } else {
1040 return '';
1045 * This function is not part of the public api.
1046 * You don't normally need to call this. It is called automatically when
1047 * needed when you start adding data to the table.
1050 function start_output() {
1051 $this->started_output = true;
1052 if ($this->exportclass!==null) {
1053 $this->exportclass->start_table($this->sheettitle);
1054 $this->exportclass->output_headers($this->headers);
1055 } else {
1056 $this->start_html();
1057 $this->print_headers();
1058 echo html_writer::start_tag('tbody');
1063 * This function is not part of the public api.
1065 function print_row($row, $classname = '') {
1066 echo $this->get_row_html($row, $classname);
1070 * Generate html code for the passed row.
1072 * @param array $row Row data.
1073 * @param string $classname classes to add.
1075 * @return string $html html code for the row passed.
1077 public function get_row_html($row, $classname = '') {
1078 static $suppress_lastrow = NULL;
1079 $rowclasses = array();
1081 if ($classname) {
1082 $rowclasses[] = $classname;
1085 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1086 $html = '';
1088 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1090 // If we have a separator, print it
1091 if ($row === NULL) {
1092 $colcount = count($this->columns);
1093 $html .= html_writer::tag('td', html_writer::tag('div', '',
1094 array('class' => 'tabledivider')), array('colspan' => $colcount));
1096 } else {
1097 $colbyindex = array_flip($this->columns);
1098 foreach ($row as $index => $data) {
1099 $column = $colbyindex[$index];
1101 if (empty($this->prefs['collapse'][$column])) {
1102 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1103 $content = '&nbsp;';
1104 } else {
1105 $content = $data;
1107 } else {
1108 $content = '&nbsp;';
1111 $html .= html_writer::tag('td', $content, array(
1112 'class' => 'cell c' . $index . $this->column_class[$column],
1113 'id' => $rowid . '_c' . $index,
1114 'style' => $this->make_styles_string($this->column_style[$column])));
1118 $html .= html_writer::end_tag('tr');
1120 $suppress_enabled = array_sum($this->column_suppress);
1121 if ($suppress_enabled) {
1122 $suppress_lastrow = $row;
1124 $this->currentrow++;
1125 return $html;
1129 * This function is not part of the public api.
1131 function finish_html() {
1132 global $OUTPUT;
1133 if (!$this->started_output) {
1134 //no data has been added to the table.
1135 $this->print_nothing_to_display();
1137 } else {
1138 // Print empty rows to fill the table to the current pagesize.
1139 // This is done so the header aria-controls attributes do not point to
1140 // non existant elements.
1141 $emptyrow = array_fill(0, count($this->columns), '');
1142 while ($this->currentrow < $this->pagesize) {
1143 $this->print_row($emptyrow, 'emptyrow');
1146 echo html_writer::end_tag('tbody');
1147 echo html_writer::end_tag('table');
1148 echo html_writer::end_tag('div');
1149 $this->wrap_html_finish();
1151 // Paging bar
1152 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1153 echo $this->download_buttons();
1156 if($this->use_pages) {
1157 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1158 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1159 echo $OUTPUT->render($pagingbar);
1165 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1166 * used by {@link print_headers()}.
1167 * @param string $column the column name, index into various names.
1168 * @param int $index numerical index of the column.
1169 * @return string HTML fragment.
1171 protected function show_hide_link($column, $index) {
1172 global $OUTPUT;
1173 // Some headers contain <br /> tags, do not include in title, hence the
1174 // strip tags.
1176 $ariacontrols = '';
1177 for ($i = 0; $i < $this->pagesize; $i++) {
1178 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1181 $ariacontrols = trim($ariacontrols);
1183 if (!empty($this->prefs['collapse'][$column])) {
1184 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1185 'aria-expanded' => 'false',
1186 'aria-controls' => $ariacontrols);
1187 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1188 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1190 } else if ($this->headers[$index] !== NULL) {
1191 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1192 'aria-expanded' => 'true',
1193 'aria-controls' => $ariacontrols);
1194 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1195 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1200 * This function is not part of the public api.
1202 function print_headers() {
1203 global $CFG, $OUTPUT;
1205 echo html_writer::start_tag('thead');
1206 echo html_writer::start_tag('tr');
1207 foreach ($this->columns as $column => $index) {
1209 $icon_hide = '';
1210 if ($this->is_collapsible) {
1211 $icon_hide = $this->show_hide_link($column, $index);
1214 $primarysortcolumn = '';
1215 $primarysortorder = '';
1216 if (reset($this->prefs['sortby'])) {
1217 $primarysortcolumn = key($this->prefs['sortby']);
1218 $primarysortorder = current($this->prefs['sortby']);
1221 switch ($column) {
1223 case 'fullname':
1224 // Check the full name display for sortable fields.
1225 $nameformat = $CFG->fullnamedisplay;
1226 if ($nameformat == 'language') {
1227 $nameformat = get_string('fullnamedisplay');
1229 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1231 if (!empty($requirednames)) {
1232 if ($this->is_sortable($column)) {
1233 // Done this way for the possibility of more than two sortable full name display fields.
1234 $this->headers[$index] = '';
1235 foreach ($requirednames as $name) {
1236 $sortname = $this->sort_link(get_string($name),
1237 $name, $primarysortcolumn === $name, $primarysortorder);
1238 $this->headers[$index] .= $sortname . ' / ';
1240 $helpicon = '';
1241 if (isset($this->helpforheaders[$index])) {
1242 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1244 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1247 break;
1249 case 'userpic':
1250 // do nothing, do not display sortable links
1251 break;
1253 default:
1254 if ($this->is_sortable($column)) {
1255 $helpicon = '';
1256 if (isset($this->helpforheaders[$index])) {
1257 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1259 $this->headers[$index] = $this->sort_link($this->headers[$index],
1260 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1264 $attributes = array(
1265 'class' => 'header c' . $index . $this->column_class[$column],
1266 'scope' => 'col',
1268 if ($this->headers[$index] === NULL) {
1269 $content = '&nbsp;';
1270 } else if (!empty($this->prefs['collapse'][$column])) {
1271 $content = $icon_hide;
1272 } else {
1273 if (is_array($this->column_style[$column])) {
1274 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1276 $helpicon = '';
1277 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1278 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1280 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1281 $icon_hide, array('class' => 'commands'));
1283 echo html_writer::tag('th', $content, $attributes);
1286 echo html_writer::end_tag('tr');
1287 echo html_writer::end_tag('thead');
1291 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1292 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1293 * @param int $order SORT_ASC or SORT_DESC
1294 * @return string HTML fragment.
1296 protected function sort_icon($isprimary, $order) {
1297 global $OUTPUT;
1299 if (!$isprimary) {
1300 return '';
1303 if ($order == SORT_ASC) {
1304 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1305 } else {
1306 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1311 * Generate the correct tool tip for changing the sort order. This is a
1312 * helper method used by {@link sort_link()}.
1313 * @param bool $isprimary whether the is column is the current primary sort column.
1314 * @param int $order SORT_ASC or SORT_DESC
1315 * @return string the correct title.
1317 protected function sort_order_name($isprimary, $order) {
1318 if ($isprimary && $order != SORT_ASC) {
1319 return get_string('desc');
1320 } else {
1321 return get_string('asc');
1326 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1327 * @param string $text the text for the link.
1328 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1329 * @param bool $isprimary whether the is column is the current primary sort column.
1330 * @param int $order SORT_ASC or SORT_DESC
1331 * @return string HTML fragment.
1333 protected function sort_link($text, $column, $isprimary, $order) {
1334 return html_writer::link($this->baseurl->out(false,
1335 array($this->request[TABLE_VAR_SORT] => $column)),
1336 $text . get_accesshide(get_string('sortby') . ' ' .
1337 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1338 $this->sort_icon($isprimary, $order);
1342 * This function is not part of the public api.
1344 function start_html() {
1345 global $OUTPUT;
1347 // Render button to allow user to reset table preferences.
1348 echo $this->render_reset_button();
1350 // Do we need to print initial bars?
1351 $this->print_initials_bar();
1353 // Paging bar
1354 if ($this->use_pages) {
1355 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1356 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1357 echo $OUTPUT->render($pagingbar);
1360 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1361 echo $this->download_buttons();
1364 $this->wrap_html_start();
1365 // Start of main data table
1367 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1368 echo html_writer::start_tag('table', $this->attributes);
1373 * This function is not part of the public api.
1374 * @param array $styles CSS-property => value
1375 * @return string values suitably to go in a style="" attribute in HTML.
1377 function make_styles_string($styles) {
1378 if (empty($styles)) {
1379 return null;
1382 $string = '';
1383 foreach($styles as $property => $value) {
1384 $string .= $property . ':' . $value . ';';
1386 return $string;
1390 * Generate the HTML for the table preferences reset button.
1392 * @return string HTML fragment, empty string if no need to reset
1394 protected function render_reset_button() {
1396 if (!$this->can_be_reset()) {
1397 return '';
1400 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1402 $html = html_writer::start_div('resettable mdl-right');
1403 $html .= html_writer::link($url, get_string('resettable'));
1404 $html .= html_writer::end_div();
1406 return $html;
1410 * Are there some table preferences that can be reset?
1412 * If true, then the "reset table preferences" widget should be displayed.
1414 * @return bool
1416 protected function can_be_reset() {
1418 // Loop through preferences and make sure they are empty or set to the default value.
1419 foreach ($this->prefs as $prefname => $prefval) {
1421 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1422 // Check if the actual sorting differs from the default one.
1423 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1424 return true;
1427 } else if ($prefname === 'collapse' and !empty($prefval)) {
1428 // Check if there are some collapsed columns (all are expanded by default).
1429 foreach ($prefval as $columnname => $iscollapsed) {
1430 if ($iscollapsed) {
1431 return true;
1435 } else if (!empty($prefval)) {
1436 // For all other cases, we just check if some preference is set.
1437 return true;
1441 return false;
1447 * @package moodlecore
1448 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1451 class table_sql extends flexible_table {
1453 public $countsql = NULL;
1454 public $countparams = NULL;
1456 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1458 public $sql = NULL;
1460 * @var array|\Traversable Data fetched from the db.
1462 public $rawdata = NULL;
1465 * @var bool Overriding default for this.
1467 public $is_sortable = true;
1469 * @var bool Overriding default for this.
1471 public $is_collapsible = true;
1474 * @param string $uniqueid a string identifying this table.Used as a key in
1475 * session vars.
1477 function __construct($uniqueid) {
1478 parent::__construct($uniqueid);
1479 // some sensible defaults
1480 $this->set_attribute('cellspacing', '0');
1481 $this->set_attribute('class', 'generaltable generalbox');
1485 * Take the data returned from the db_query and go through all the rows
1486 * processing each col using either col_{columnname} method or other_cols
1487 * method or if other_cols returns NULL then put the data straight into the
1488 * table.
1490 * After calling this function, don't forget to call close_recordset.
1492 public function build_table() {
1494 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1495 return;
1497 if (!$this->rawdata) {
1498 return;
1501 foreach ($this->rawdata as $row) {
1502 $formattedrow = $this->format_row($row);
1503 $this->add_data_keyed($formattedrow,
1504 $this->get_row_class($row));
1509 * Closes recordset (for use after building the table).
1511 public function close_recordset() {
1512 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1513 $this->rawdata instanceof moodle_recordset)) {
1514 $this->rawdata->close();
1515 $this->rawdata = null;
1520 * Get any extra classes names to add to this row in the HTML.
1521 * @param $row array the data for this row.
1522 * @return string added to the class="" attribute of the tr.
1524 function get_row_class($row) {
1525 return '';
1529 * This is only needed if you want to use different sql to count rows.
1530 * Used for example when perhaps all db JOINS are not needed when counting
1531 * records. You don't need to call this function the count_sql
1532 * will be generated automatically.
1534 * We need to count rows returned by the db seperately to the query itself
1535 * as we need to know how many pages of data we have to display.
1537 function set_count_sql($sql, array $params = NULL) {
1538 $this->countsql = $sql;
1539 $this->countparams = $params;
1543 * Set the sql to query the db. Query will be :
1544 * SELECT $fields FROM $from WHERE $where
1545 * Of course you can use sub-queries, JOINS etc. by putting them in the
1546 * appropriate clause of the query.
1548 function set_sql($fields, $from, $where, array $params = array()) {
1549 $this->sql = new stdClass();
1550 $this->sql->fields = $fields;
1551 $this->sql->from = $from;
1552 $this->sql->where = $where;
1553 $this->sql->params = $params;
1557 * Query the db. Store results in the table object for use by build_table.
1559 * @param int $pagesize size of page for paginated displayed table.
1560 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1561 * will only be used if there is a fullname column defined for the table.
1563 function query_db($pagesize, $useinitialsbar=true) {
1564 global $DB;
1565 if (!$this->is_downloading()) {
1566 if ($this->countsql === NULL) {
1567 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1568 $this->countparams = $this->sql->params;
1570 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1571 if ($useinitialsbar && !$this->is_downloading()) {
1572 $this->initialbars($grandtotal > $pagesize);
1575 list($wsql, $wparams) = $this->get_sql_where();
1576 if ($wsql) {
1577 $this->countsql .= ' AND '.$wsql;
1578 $this->countparams = array_merge($this->countparams, $wparams);
1580 $this->sql->where .= ' AND '.$wsql;
1581 $this->sql->params = array_merge($this->sql->params, $wparams);
1583 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1584 } else {
1585 $total = $grandtotal;
1588 $this->pagesize($pagesize, $total);
1591 // Fetch the attempts
1592 $sort = $this->get_sql_sort();
1593 if ($sort) {
1594 $sort = "ORDER BY $sort";
1596 $sql = "SELECT
1597 {$this->sql->fields}
1598 FROM {$this->sql->from}
1599 WHERE {$this->sql->where}
1600 {$sort}";
1602 if (!$this->is_downloading()) {
1603 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1604 } else {
1605 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1610 * Convenience method to call a number of methods for you to display the
1611 * table.
1613 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1614 global $DB;
1615 if (!$this->columns) {
1616 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1617 $this->sql->params, IGNORE_MULTIPLE);
1618 //if columns is not set then define columns as the keys of the rows returned
1619 //from the db.
1620 $this->define_columns(array_keys((array)$onerow));
1621 $this->define_headers(array_keys((array)$onerow));
1623 $this->setup();
1624 $this->query_db($pagesize, $useinitialsbar);
1625 $this->build_table();
1626 $this->close_recordset();
1627 $this->finish_output();
1633 * @package moodlecore
1634 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1637 class table_default_export_format_parent {
1639 * @var flexible_table or child class reference pointing to table class
1640 * object from which to export data.
1642 var $table;
1645 * @var bool output started. Keeps track of whether any output has been
1646 * started yet.
1648 var $documentstarted = false;
1651 * Constructor
1653 * @param flexible_table $table
1655 public function __construct(&$table) {
1656 $this->table =& $table;
1660 * Old syntax of class constructor. Deprecated in PHP7.
1662 * @deprecated since Moodle 3.1
1664 public function table_default_export_format_parent(&$table) {
1665 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1666 self::__construct($table);
1669 function set_table(&$table) {
1670 $this->table =& $table;
1673 function add_data($row) {
1674 return false;
1677 function add_seperator() {
1678 return false;
1681 function document_started() {
1682 return $this->documentstarted;
1685 * Given text in a variety of format codings, this function returns
1686 * the text as safe HTML or as plain text dependent on what is appropriate
1687 * for the download format. The default removes all tags.
1689 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1690 //use some whitespace to indicate where there was some line spacing.
1691 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1692 return strip_tags($text);
1697 * Dataformat exporter
1699 * @package core
1700 * @subpackage tablelib
1701 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1704 class table_dataformat_export_format extends table_default_export_format_parent {
1706 /** @var $dataformat */
1707 protected $dataformat;
1709 /** @var $rownum */
1710 protected $rownum = 0;
1712 /** @var $columns */
1713 protected $columns;
1716 * Constructor
1718 * @param string $table An sql table
1719 * @param string $dataformat type of dataformat for export
1721 public function __construct(&$table, $dataformat) {
1722 parent::__construct($table);
1724 if (ob_get_length()) {
1725 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1728 $classname = 'dataformat_' . $dataformat . '\writer';
1729 if (!class_exists($classname)) {
1730 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1732 $this->dataformat = new $classname;
1734 // The dataformat export time to first byte could take a while to generate...
1735 set_time_limit(0);
1737 // Close the session so that the users other tabs in the same session are not blocked.
1738 \core\session\manager::write_close();
1742 * Start document
1744 * @param string $filename
1745 * @param string $sheettitle
1747 public function start_document($filename, $sheettitle) {
1748 $this->documentstarted = true;
1749 $this->dataformat->set_filename($filename);
1750 $this->dataformat->send_http_headers();
1751 $this->dataformat->set_sheettitle($sheettitle);
1752 $this->dataformat->start_output();
1756 * Start export
1758 * @param string $sheettitle optional spreadsheet worksheet title
1760 public function start_table($sheettitle) {
1761 $this->dataformat->set_sheettitle($sheettitle);
1765 * Output headers
1767 * @param array $headers
1769 public function output_headers($headers) {
1770 $this->columns = $headers;
1771 if (method_exists($this->dataformat, 'write_header')) {
1772 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
1773 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1774 $this->dataformat->write_header($headers);
1775 } else {
1776 $this->dataformat->start_sheet($headers);
1781 * Add a row of data
1783 * @param array $row One record of data
1785 public function add_data($row) {
1786 $this->dataformat->write_record($row, $this->rownum++);
1787 return true;
1791 * Finish export
1793 public function finish_table() {
1794 if (method_exists($this->dataformat, 'write_footer')) {
1795 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
1796 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1797 $this->dataformat->write_footer($this->columns);
1798 } else {
1799 $this->dataformat->close_sheet($this->columns);
1804 * Finish download
1806 public function finish_document() {
1807 $this->dataformat->close_output();
1808 exit();