MDL-63050 cachestore_redis: Update hExists to check empty
[moodle.git] / lib / tablelib.php
bloba35a49a290eb0022016c3a75c76541333ed5e714
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 if (has_capability('moodle/site:viewfullnames', context_system::instance())) {
1226 $nameformat = $CFG->alternativefullnameformat;
1227 } else {
1228 $nameformat = $CFG->fullnamedisplay;
1231 if ($nameformat == 'language') {
1232 $nameformat = get_string('fullnamedisplay');
1235 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1237 if (!empty($requirednames)) {
1238 if ($this->is_sortable($column)) {
1239 // Done this way for the possibility of more than two sortable full name display fields.
1240 $this->headers[$index] = '';
1241 foreach ($requirednames as $name) {
1242 $sortname = $this->sort_link(get_string($name),
1243 $name, $primarysortcolumn === $name, $primarysortorder);
1244 $this->headers[$index] .= $sortname . ' / ';
1246 $helpicon = '';
1247 if (isset($this->helpforheaders[$index])) {
1248 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1250 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1253 break;
1255 case 'userpic':
1256 // do nothing, do not display sortable links
1257 break;
1259 default:
1260 if ($this->is_sortable($column)) {
1261 $helpicon = '';
1262 if (isset($this->helpforheaders[$index])) {
1263 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1265 $this->headers[$index] = $this->sort_link($this->headers[$index],
1266 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1270 $attributes = array(
1271 'class' => 'header c' . $index . $this->column_class[$column],
1272 'scope' => 'col',
1274 if ($this->headers[$index] === NULL) {
1275 $content = '&nbsp;';
1276 } else if (!empty($this->prefs['collapse'][$column])) {
1277 $content = $icon_hide;
1278 } else {
1279 if (is_array($this->column_style[$column])) {
1280 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1282 $helpicon = '';
1283 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1284 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1286 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1287 $icon_hide, array('class' => 'commands'));
1289 echo html_writer::tag('th', $content, $attributes);
1292 echo html_writer::end_tag('tr');
1293 echo html_writer::end_tag('thead');
1297 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1298 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1299 * @param int $order SORT_ASC or SORT_DESC
1300 * @return string HTML fragment.
1302 protected function sort_icon($isprimary, $order) {
1303 global $OUTPUT;
1305 if (!$isprimary) {
1306 return '';
1309 if ($order == SORT_ASC) {
1310 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'));
1311 } else {
1312 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'));
1317 * Generate the correct tool tip for changing the sort order. This is a
1318 * helper method used by {@link sort_link()}.
1319 * @param bool $isprimary whether the is column is the current primary sort column.
1320 * @param int $order SORT_ASC or SORT_DESC
1321 * @return string the correct title.
1323 protected function sort_order_name($isprimary, $order) {
1324 if ($isprimary && $order != SORT_ASC) {
1325 return get_string('desc');
1326 } else {
1327 return get_string('asc');
1332 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1333 * @param string $text the text for the link.
1334 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1335 * @param bool $isprimary whether the is column is the current primary sort column.
1336 * @param int $order SORT_ASC or SORT_DESC
1337 * @return string HTML fragment.
1339 protected function sort_link($text, $column, $isprimary, $order) {
1340 return html_writer::link($this->baseurl->out(false,
1341 array($this->request[TABLE_VAR_SORT] => $column)),
1342 $text . get_accesshide(get_string('sortby') . ' ' .
1343 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1344 $this->sort_icon($isprimary, $order);
1348 * This function is not part of the public api.
1350 function start_html() {
1351 global $OUTPUT;
1353 // Render button to allow user to reset table preferences.
1354 echo $this->render_reset_button();
1356 // Do we need to print initial bars?
1357 $this->print_initials_bar();
1359 // Paging bar
1360 if ($this->use_pages) {
1361 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1362 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1363 echo $OUTPUT->render($pagingbar);
1366 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1367 echo $this->download_buttons();
1370 $this->wrap_html_start();
1371 // Start of main data table
1373 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1374 echo html_writer::start_tag('table', $this->attributes);
1379 * This function is not part of the public api.
1380 * @param array $styles CSS-property => value
1381 * @return string values suitably to go in a style="" attribute in HTML.
1383 function make_styles_string($styles) {
1384 if (empty($styles)) {
1385 return null;
1388 $string = '';
1389 foreach($styles as $property => $value) {
1390 $string .= $property . ':' . $value . ';';
1392 return $string;
1396 * Generate the HTML for the table preferences reset button.
1398 * @return string HTML fragment, empty string if no need to reset
1400 protected function render_reset_button() {
1402 if (!$this->can_be_reset()) {
1403 return '';
1406 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1408 $html = html_writer::start_div('resettable mdl-right');
1409 $html .= html_writer::link($url, get_string('resettable'));
1410 $html .= html_writer::end_div();
1412 return $html;
1416 * Are there some table preferences that can be reset?
1418 * If true, then the "reset table preferences" widget should be displayed.
1420 * @return bool
1422 protected function can_be_reset() {
1424 // Loop through preferences and make sure they are empty or set to the default value.
1425 foreach ($this->prefs as $prefname => $prefval) {
1427 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1428 // Check if the actual sorting differs from the default one.
1429 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1430 return true;
1433 } else if ($prefname === 'collapse' and !empty($prefval)) {
1434 // Check if there are some collapsed columns (all are expanded by default).
1435 foreach ($prefval as $columnname => $iscollapsed) {
1436 if ($iscollapsed) {
1437 return true;
1441 } else if (!empty($prefval)) {
1442 // For all other cases, we just check if some preference is set.
1443 return true;
1447 return false;
1453 * @package moodlecore
1454 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1457 class table_sql extends flexible_table {
1459 public $countsql = NULL;
1460 public $countparams = NULL;
1462 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1464 public $sql = NULL;
1466 * @var array|\Traversable Data fetched from the db.
1468 public $rawdata = NULL;
1471 * @var bool Overriding default for this.
1473 public $is_sortable = true;
1475 * @var bool Overriding default for this.
1477 public $is_collapsible = true;
1480 * @param string $uniqueid a string identifying this table.Used as a key in
1481 * session vars.
1483 function __construct($uniqueid) {
1484 parent::__construct($uniqueid);
1485 // some sensible defaults
1486 $this->set_attribute('cellspacing', '0');
1487 $this->set_attribute('class', 'generaltable generalbox');
1491 * Take the data returned from the db_query and go through all the rows
1492 * processing each col using either col_{columnname} method or other_cols
1493 * method or if other_cols returns NULL then put the data straight into the
1494 * table.
1496 * After calling this function, don't forget to call close_recordset.
1498 public function build_table() {
1500 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1501 return;
1503 if (!$this->rawdata) {
1504 return;
1507 foreach ($this->rawdata as $row) {
1508 $formattedrow = $this->format_row($row);
1509 $this->add_data_keyed($formattedrow,
1510 $this->get_row_class($row));
1515 * Closes recordset (for use after building the table).
1517 public function close_recordset() {
1518 if ($this->rawdata && ($this->rawdata instanceof \core\dml\recordset_walk ||
1519 $this->rawdata instanceof moodle_recordset)) {
1520 $this->rawdata->close();
1521 $this->rawdata = null;
1526 * Get any extra classes names to add to this row in the HTML.
1527 * @param $row array the data for this row.
1528 * @return string added to the class="" attribute of the tr.
1530 function get_row_class($row) {
1531 return '';
1535 * This is only needed if you want to use different sql to count rows.
1536 * Used for example when perhaps all db JOINS are not needed when counting
1537 * records. You don't need to call this function the count_sql
1538 * will be generated automatically.
1540 * We need to count rows returned by the db seperately to the query itself
1541 * as we need to know how many pages of data we have to display.
1543 function set_count_sql($sql, array $params = NULL) {
1544 $this->countsql = $sql;
1545 $this->countparams = $params;
1549 * Set the sql to query the db. Query will be :
1550 * SELECT $fields FROM $from WHERE $where
1551 * Of course you can use sub-queries, JOINS etc. by putting them in the
1552 * appropriate clause of the query.
1554 function set_sql($fields, $from, $where, array $params = array()) {
1555 $this->sql = new stdClass();
1556 $this->sql->fields = $fields;
1557 $this->sql->from = $from;
1558 $this->sql->where = $where;
1559 $this->sql->params = $params;
1563 * Query the db. Store results in the table object for use by build_table.
1565 * @param int $pagesize size of page for paginated displayed table.
1566 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1567 * will only be used if there is a fullname column defined for the table.
1569 function query_db($pagesize, $useinitialsbar=true) {
1570 global $DB;
1571 if (!$this->is_downloading()) {
1572 if ($this->countsql === NULL) {
1573 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1574 $this->countparams = $this->sql->params;
1576 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1577 if ($useinitialsbar && !$this->is_downloading()) {
1578 $this->initialbars($grandtotal > $pagesize);
1581 list($wsql, $wparams) = $this->get_sql_where();
1582 if ($wsql) {
1583 $this->countsql .= ' AND '.$wsql;
1584 $this->countparams = array_merge($this->countparams, $wparams);
1586 $this->sql->where .= ' AND '.$wsql;
1587 $this->sql->params = array_merge($this->sql->params, $wparams);
1589 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1590 } else {
1591 $total = $grandtotal;
1594 $this->pagesize($pagesize, $total);
1597 // Fetch the attempts
1598 $sort = $this->get_sql_sort();
1599 if ($sort) {
1600 $sort = "ORDER BY $sort";
1602 $sql = "SELECT
1603 {$this->sql->fields}
1604 FROM {$this->sql->from}
1605 WHERE {$this->sql->where}
1606 {$sort}";
1608 if (!$this->is_downloading()) {
1609 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1610 } else {
1611 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1616 * Convenience method to call a number of methods for you to display the
1617 * table.
1619 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1620 global $DB;
1621 if (!$this->columns) {
1622 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1623 $this->sql->params, IGNORE_MULTIPLE);
1624 //if columns is not set then define columns as the keys of the rows returned
1625 //from the db.
1626 $this->define_columns(array_keys((array)$onerow));
1627 $this->define_headers(array_keys((array)$onerow));
1629 $this->setup();
1630 $this->query_db($pagesize, $useinitialsbar);
1631 $this->build_table();
1632 $this->close_recordset();
1633 $this->finish_output();
1639 * @package moodlecore
1640 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1641 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1643 class table_default_export_format_parent {
1645 * @var flexible_table or child class reference pointing to table class
1646 * object from which to export data.
1648 var $table;
1651 * @var bool output started. Keeps track of whether any output has been
1652 * started yet.
1654 var $documentstarted = false;
1657 * Constructor
1659 * @param flexible_table $table
1661 public function __construct(&$table) {
1662 $this->table =& $table;
1666 * Old syntax of class constructor. Deprecated in PHP7.
1668 * @deprecated since Moodle 3.1
1670 public function table_default_export_format_parent(&$table) {
1671 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1672 self::__construct($table);
1675 function set_table(&$table) {
1676 $this->table =& $table;
1679 function add_data($row) {
1680 return false;
1683 function add_seperator() {
1684 return false;
1687 function document_started() {
1688 return $this->documentstarted;
1691 * Given text in a variety of format codings, this function returns
1692 * the text as safe HTML or as plain text dependent on what is appropriate
1693 * for the download format. The default removes all tags.
1695 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1696 //use some whitespace to indicate where there was some line spacing.
1697 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1698 return strip_tags($text);
1703 * Dataformat exporter
1705 * @package core
1706 * @subpackage tablelib
1707 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1710 class table_dataformat_export_format extends table_default_export_format_parent {
1712 /** @var $dataformat */
1713 protected $dataformat;
1715 /** @var $rownum */
1716 protected $rownum = 0;
1718 /** @var $columns */
1719 protected $columns;
1722 * Constructor
1724 * @param string $table An sql table
1725 * @param string $dataformat type of dataformat for export
1727 public function __construct(&$table, $dataformat) {
1728 parent::__construct($table);
1730 if (ob_get_length()) {
1731 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1734 $classname = 'dataformat_' . $dataformat . '\writer';
1735 if (!class_exists($classname)) {
1736 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1738 $this->dataformat = new $classname;
1740 // The dataformat export time to first byte could take a while to generate...
1741 set_time_limit(0);
1743 // Close the session so that the users other tabs in the same session are not blocked.
1744 \core\session\manager::write_close();
1748 * Start document
1750 * @param string $filename
1751 * @param string $sheettitle
1753 public function start_document($filename, $sheettitle) {
1754 $this->documentstarted = true;
1755 $this->dataformat->set_filename($filename);
1756 $this->dataformat->send_http_headers();
1757 $this->dataformat->set_sheettitle($sheettitle);
1758 $this->dataformat->start_output();
1762 * Start export
1764 * @param string $sheettitle optional spreadsheet worksheet title
1766 public function start_table($sheettitle) {
1767 $this->dataformat->set_sheettitle($sheettitle);
1771 * Output headers
1773 * @param array $headers
1775 public function output_headers($headers) {
1776 $this->columns = $headers;
1777 if (method_exists($this->dataformat, 'write_header')) {
1778 error_log('The function write_header() does not support multiple sheets. In order to support multiple sheets you ' .
1779 'must implement start_output() and start_sheet() and remove write_header() in your dataformat.');
1780 $this->dataformat->write_header($headers);
1781 } else {
1782 $this->dataformat->start_sheet($headers);
1787 * Add a row of data
1789 * @param array $row One record of data
1791 public function add_data($row) {
1792 $this->dataformat->write_record($row, $this->rownum++);
1793 return true;
1797 * Finish export
1799 public function finish_table() {
1800 if (method_exists($this->dataformat, 'write_footer')) {
1801 error_log('The function write_footer() does not support multiple sheets. In order to support multiple sheets you ' .
1802 'must implement close_sheet() and close_output() and remove write_footer() in your dataformat.');
1803 $this->dataformat->write_footer($this->columns);
1804 } else {
1805 $this->dataformat->close_sheet($this->columns);
1810 * Finish download
1812 public function finish_document() {
1813 $this->dataformat->close_output();
1814 exit();