MDL-57139 myoverview: fix paging button edge case
[moodle.git] / lib / tablelib.php
blob84d077b5011983476d98f57b310c74a91a43438b
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();
129 * Constructor
130 * @param string $uniqueid all tables have to have a unique id, this is used
131 * as a key when storing table properties like sort order in the session.
133 function __construct($uniqueid) {
134 $this->uniqueid = $uniqueid;
135 $this->request = array(
136 TABLE_VAR_SORT => 'tsort',
137 TABLE_VAR_HIDE => 'thide',
138 TABLE_VAR_SHOW => 'tshow',
139 TABLE_VAR_IFIRST => 'tifirst',
140 TABLE_VAR_ILAST => 'tilast',
141 TABLE_VAR_PAGE => 'page',
142 TABLE_VAR_RESET => 'treset'
147 * Call this to pass the download type. Use :
148 * $download = optional_param('download', '', PARAM_ALPHA);
149 * To get the download type. We assume that if you call this function with
150 * params that this table's data is downloadable, so we call is_downloadable
151 * for you (even if the param is '', which means no download this time.
152 * Also you can call this method with no params to get the current set
153 * download type.
154 * @param string $download dataformat type. One of csv, xhtml, ods, etc
155 * @param string $filename filename for downloads without file extension.
156 * @param string $sheettitle title for downloaded data.
157 * @return string download dataformat type. One of csv, xhtml, ods, etc
159 function is_downloading($download = null, $filename='', $sheettitle='') {
160 if ($download!==null) {
161 $this->sheettitle = $sheettitle;
162 $this->is_downloadable(true);
163 $this->download = $download;
164 $this->filename = clean_filename($filename);
165 $this->export_class_instance();
167 return $this->download;
171 * Get, and optionally set, the export class.
172 * @param $exportclass (optional) if passed, set the table to use this export class.
173 * @return table_default_export_format_parent the export class in use (after any set).
175 function export_class_instance($exportclass = null) {
176 if (!is_null($exportclass)) {
177 $this->started_output = true;
178 $this->exportclass = $exportclass;
179 $this->exportclass->table = $this;
180 } else if (is_null($this->exportclass) && !empty($this->download)) {
181 $this->exportclass = new table_dataformat_export_format($this, $this->download);
182 if (!$this->exportclass->document_started()) {
183 $this->exportclass->start_document($this->filename);
186 return $this->exportclass;
190 * Probably don't need to call this directly. Calling is_downloading with a
191 * param automatically sets table as downloadable.
193 * @param bool $downloadable optional param to set whether data from
194 * table is downloadable. If ommitted this function can be used to get
195 * current state of table.
196 * @return bool whether table data is set to be downloadable.
198 function is_downloadable($downloadable = null) {
199 if ($downloadable !== null) {
200 $this->downloadable = $downloadable;
202 return $this->downloadable;
206 * Call with boolean true to store table layout changes in the user_preferences table.
207 * Note: user_preferences.value has a maximum length of 1333 characters.
208 * Call with no parameter to get current state of table persistence.
210 * @param bool $persistent Optional parameter to set table layout persistence.
211 * @return bool Whether or not the table layout preferences will persist.
213 public function is_persistent($persistent = null) {
214 if ($persistent == true) {
215 $this->persistent = true;
217 return $this->persistent;
221 * Where to show download buttons.
222 * @param array $showat array of postions in which to show download buttons.
223 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
225 function show_download_buttons_at($showat) {
226 $this->showdownloadbuttonsat = $showat;
230 * Sets the is_sortable variable to the given boolean, sort_default_column to
231 * the given string, and the sort_default_order to the given integer.
232 * @param bool $bool
233 * @param string $defaultcolumn
234 * @param int $defaultorder
235 * @return void
237 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
238 $this->is_sortable = $bool;
239 $this->sort_default_column = $defaultcolumn;
240 $this->sort_default_order = $defaultorder;
244 * Use text sorting functions for this column (required for text columns with Oracle).
245 * Be warned that you cannot use this with column aliases. You can only do this
246 * with real columns. See MDL-40481 for an example.
247 * @param string column name
249 function text_sorting($column) {
250 $this->column_textsort[] = $column;
254 * Do not sort using this column
255 * @param string column name
257 function no_sorting($column) {
258 $this->column_nosort[] = $column;
262 * Is the column sortable?
263 * @param string column name, null means table
264 * @return bool
266 function is_sortable($column = null) {
267 if (empty($column)) {
268 return $this->is_sortable;
270 if (!$this->is_sortable) {
271 return false;
273 return !in_array($column, $this->column_nosort);
277 * Sets the is_collapsible variable to the given boolean.
278 * @param bool $bool
279 * @return void
281 function collapsible($bool) {
282 $this->is_collapsible = $bool;
286 * Sets the use_pages variable to the given boolean.
287 * @param bool $bool
288 * @return void
290 function pageable($bool) {
291 $this->use_pages = $bool;
295 * Sets the use_initials variable to the given boolean.
296 * @param bool $bool
297 * @return void
299 function initialbars($bool) {
300 $this->use_initials = $bool;
304 * Sets the pagesize variable to the given integer, the totalrows variable
305 * to the given integer, and the use_pages variable to true.
306 * @param int $perpage
307 * @param int $total
308 * @return void
310 function pagesize($perpage, $total) {
311 $this->pagesize = $perpage;
312 $this->totalrows = $total;
313 $this->use_pages = true;
317 * Assigns each given variable in the array to the corresponding index
318 * in the request class variable.
319 * @param array $variables
320 * @return void
322 function set_control_variables($variables) {
323 foreach ($variables as $what => $variable) {
324 if (isset($this->request[$what])) {
325 $this->request[$what] = $variable;
331 * Gives the given $value to the $attribute index of $this->attributes.
332 * @param string $attribute
333 * @param mixed $value
334 * @return void
336 function set_attribute($attribute, $value) {
337 $this->attributes[$attribute] = $value;
341 * What this method does is set the column so that if the same data appears in
342 * consecutive rows, then it is not repeated.
344 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
345 * that when one student has made multiple attempts, their name is only printed in the row
346 * for their first attempt.
347 * @param int $column the index of a column.
349 function column_suppress($column) {
350 if (isset($this->column_suppress[$column])) {
351 $this->column_suppress[$column] = true;
356 * Sets the given $column index to the given $classname in $this->column_class.
357 * @param int $column
358 * @param string $classname
359 * @return void
361 function column_class($column, $classname) {
362 if (isset($this->column_class[$column])) {
363 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
368 * Sets the given $column index and $property index to the given $value in $this->column_style.
369 * @param int $column
370 * @param string $property
371 * @param mixed $value
372 * @return void
374 function column_style($column, $property, $value) {
375 if (isset($this->column_style[$column])) {
376 $this->column_style[$column][$property] = $value;
381 * Sets all columns' $propertys to the given $value in $this->column_style.
382 * @param int $property
383 * @param string $value
384 * @return void
386 function column_style_all($property, $value) {
387 foreach (array_keys($this->columns) as $column) {
388 $this->column_style[$column][$property] = $value;
393 * Sets $this->baseurl.
394 * @param moodle_url|string $url the url with params needed to call up this page
396 function define_baseurl($url) {
397 $this->baseurl = new moodle_url($url);
401 * @param array $columns an array of identifying names for columns. If
402 * columns are sorted then column names must correspond to a field in sql.
404 function define_columns($columns) {
405 $this->columns = array();
406 $this->column_style = array();
407 $this->column_class = array();
408 $colnum = 0;
410 foreach ($columns as $column) {
411 $this->columns[$column] = $colnum++;
412 $this->column_style[$column] = array();
413 $this->column_class[$column] = '';
414 $this->column_suppress[$column] = false;
419 * @param array $headers numerical keyed array of displayed string titles
420 * for each column.
422 function define_headers($headers) {
423 $this->headers = $headers;
427 * Defines a help icon for the header
429 * Always use this function if you need to create header with sorting and help icon.
431 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
433 public function define_help_for_headers($helpicons) {
434 $this->helpforheaders = $helpicons;
438 * Must be called after table is defined. Use methods above first. Cannot
439 * use functions below till after calling this method.
440 * @return type?
442 function setup() {
443 global $SESSION;
445 if (empty($this->columns) || empty($this->uniqueid)) {
446 return false;
449 // Load any existing user preferences.
450 if ($this->persistent) {
451 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
452 $oldprefs = $this->prefs;
453 } else if (isset($SESSION->flextable[$this->uniqueid])) {
454 $this->prefs = $SESSION->flextable[$this->uniqueid];
455 $oldprefs = $this->prefs;
458 // Set up default preferences if needed.
459 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
460 $this->prefs = array(
461 'collapse' => array(),
462 'sortby' => array(),
463 'i_first' => '',
464 'i_last' => '',
465 'textsort' => $this->column_textsort,
469 if (!isset($oldprefs)) {
470 $oldprefs = $this->prefs;
473 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
474 isset($this->columns[$showcol])) {
475 $this->prefs['collapse'][$showcol] = false;
477 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
478 isset($this->columns[$hidecol])) {
479 $this->prefs['collapse'][$hidecol] = true;
480 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
481 unset($this->prefs['sortby'][$hidecol]);
485 // Now, update the column attributes for collapsed columns
486 foreach (array_keys($this->columns) as $column) {
487 if (!empty($this->prefs['collapse'][$column])) {
488 $this->column_style[$column]['width'] = '10px';
492 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
493 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
494 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
495 && isset($this->columns['fullname']))) {
497 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
498 // This key already exists somewhere. Change its sortorder and bring it to the top.
499 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
500 unset($this->prefs['sortby'][$sortcol]);
501 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
502 } else {
503 // Key doesn't exist, so just add it to the beginning of the array, ascending order
504 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
507 // Finally, make sure that no more than $this->maxsortkeys are present into the array
508 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
511 // 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.
512 // This prevents results from being returned in a random order if the only order by column contains equal values.
513 if (!empty($this->sort_default_column)) {
514 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
515 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
516 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
520 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
521 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
522 $this->prefs['i_last'] = $ilast;
525 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
526 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
527 $this->prefs['i_first'] = $ifirst;
530 // Save user preferences if they have changed.
531 if ($this->prefs != $oldprefs) {
532 if ($this->persistent) {
533 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
534 } else {
535 $SESSION->flextable[$this->uniqueid] = $this->prefs;
538 unset($oldprefs);
540 if (empty($this->baseurl)) {
541 debugging('You should set baseurl when using flexible_table.');
542 global $PAGE;
543 $this->baseurl = $PAGE->url;
546 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
547 $this->setup = true;
549 // Always introduce the "flexible" class for the table if not specified
550 if (empty($this->attributes)) {
551 $this->attributes['class'] = 'flexible';
552 } else if (!isset($this->attributes['class'])) {
553 $this->attributes['class'] = 'flexible';
554 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
555 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
560 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
561 * @param string $uniqueid the identifier for a table.
562 * @return SQL fragment that can be used in an ORDER BY clause.
564 public static function get_sort_for_table($uniqueid) {
565 global $SESSION;
566 if (isset($SESSION->flextable[$uniqueid])) {
567 $prefs = $SESSION->flextable[$uniqueid];
568 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
569 return '';
572 if (empty($prefs['sortby'])) {
573 return '';
575 if (empty($prefs['textsort'])) {
576 $prefs['textsort'] = array();
579 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
583 * Prepare an an order by clause from the list of columns to be sorted.
584 * @param array $cols column name => SORT_ASC or SORT_DESC
585 * @return SQL fragment that can be used in an ORDER BY clause.
587 public static function construct_order_by($cols, $textsortcols=array()) {
588 global $DB;
589 $bits = array();
591 foreach ($cols as $column => $order) {
592 if (in_array($column, $textsortcols)) {
593 $column = $DB->sql_order_by_text($column);
595 if ($order == SORT_ASC) {
596 $bits[] = $column . ' ASC';
597 } else {
598 $bits[] = $column . ' DESC';
602 return implode(', ', $bits);
606 * @return SQL fragment that can be used in an ORDER BY clause.
608 public function get_sql_sort() {
609 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
613 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
614 * @return array column name => SORT_... constant.
616 public function get_sort_columns() {
617 if (!$this->setup) {
618 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
621 if (empty($this->prefs['sortby'])) {
622 return array();
625 foreach ($this->prefs['sortby'] as $column => $notused) {
626 if (isset($this->columns[$column])) {
627 continue; // This column is OK.
629 if (in_array($column, get_all_user_name_fields()) &&
630 isset($this->columns['fullname'])) {
631 continue; // This column is OK.
633 // This column is not OK.
634 unset($this->prefs['sortby'][$column]);
637 return $this->prefs['sortby'];
641 * @return int the offset for LIMIT clause of SQL
643 function get_page_start() {
644 if (!$this->use_pages) {
645 return '';
647 return $this->currpage * $this->pagesize;
651 * @return int the pagesize for LIMIT clause of SQL
653 function get_page_size() {
654 if (!$this->use_pages) {
655 return '';
657 return $this->pagesize;
661 * @return string sql to add to where statement.
663 function get_sql_where() {
664 global $DB;
666 $conditions = array();
667 $params = array();
669 if (isset($this->columns['fullname'])) {
670 static $i = 0;
671 $i++;
673 if (!empty($this->prefs['i_first'])) {
674 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
675 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
677 if (!empty($this->prefs['i_last'])) {
678 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
679 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
683 return array(implode(" AND ", $conditions), $params);
687 * Add a row of data to the table. This function takes an array or object with
688 * column names as keys or property names.
690 * It ignores any elements with keys that are not defined as columns. It
691 * puts in empty strings into the row when there is no element in the passed
692 * array corresponding to a column in the table. It puts the row elements in
693 * the proper order (internally row table data is stored by in arrays with
694 * a numerical index corresponding to the column number).
696 * @param object|array $rowwithkeys array keys or object property names are column names,
697 * as defined in call to define_columns.
698 * @param string $classname CSS class name to add to this row's tr tag.
700 function add_data_keyed($rowwithkeys, $classname = '') {
701 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
705 * Add a number of rows to the table at once. And optionally finish output after they have been added.
707 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
708 * object or array is added to table. We expect properties for the row array as would be
709 * passed to add_data_keyed.
710 * @param bool $finish
712 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
713 foreach ($rowstoadd as $row) {
714 if (is_null($row)) {
715 $this->add_separator();
716 } else {
717 $this->add_data_keyed($this->format_row($row));
720 if ($finish) {
721 $this->finish_output(!$this->is_downloading());
726 * Add a seperator line to table.
728 function add_separator() {
729 if (!$this->setup) {
730 return false;
732 $this->add_data(NULL);
736 * This method actually directly echoes the row passed to it now or adds it
737 * to the download. If this is the first row and start_output has not
738 * already been called this method also calls start_output to open the table
739 * or send headers for the downloaded.
740 * Can be used as before. print_html now calls finish_html to close table.
742 * @param array $row a numerically keyed row of data to add to the table.
743 * @param string $classname CSS class name to add to this row's tr tag.
744 * @return bool success.
746 function add_data($row, $classname = '') {
747 if (!$this->setup) {
748 return false;
750 if (!$this->started_output) {
751 $this->start_output();
753 if ($this->exportclass!==null) {
754 if ($row === null) {
755 $this->exportclass->add_seperator();
756 } else {
757 $this->exportclass->add_data($row);
759 } else {
760 $this->print_row($row, $classname);
762 return true;
766 * You should call this to finish outputting the table data after adding
767 * data to the table with add_data or add_data_keyed.
770 function finish_output($closeexportclassdoc = true) {
771 if ($this->exportclass!==null) {
772 $this->exportclass->finish_table();
773 if ($closeexportclassdoc) {
774 $this->exportclass->finish_document();
776 } else {
777 $this->finish_html();
782 * Hook that can be overridden in child classes to wrap a table in a form
783 * for example. Called only when there is data to display and not
784 * downloading.
786 function wrap_html_start() {
790 * Hook that can be overridden in child classes to wrap a table in a form
791 * for example. Called only when there is data to display and not
792 * downloading.
794 function wrap_html_finish() {
798 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
799 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
800 * displaying table as html, adding a div wrap, etc.
802 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
804 * @param array|object $row row of data from db used to make one row of the table.
805 * @return array one row for the table, added using add_data_keyed method.
807 function format_row($row) {
808 if (is_array($row)) {
809 $row = (object)$row;
811 $formattedrow = array();
812 foreach (array_keys($this->columns) as $column) {
813 $colmethodname = 'col_'.$column;
814 if (method_exists($this, $colmethodname)) {
815 $formattedcolumn = $this->$colmethodname($row);
816 } else {
817 $formattedcolumn = $this->other_cols($column, $row);
818 if ($formattedcolumn===NULL) {
819 $formattedcolumn = $row->$column;
822 $formattedrow[$column] = $formattedcolumn;
824 return $formattedrow;
828 * Fullname is treated as a special columname in tablelib and should always
829 * be treated the same as the fullname of a user.
830 * @uses $this->useridfield if the userid field is not expected to be id
831 * then you need to override $this->useridfield to point at the correct
832 * field for the user id.
834 * @param object $row the data from the db containing all fields from the
835 * users table necessary to construct the full name of the user in
836 * current language.
837 * @return string contents of cell in column 'fullname', for this row.
839 function col_fullname($row) {
840 global $COURSE;
842 $name = fullname($row);
843 if ($this->download) {
844 return $name;
847 $userid = $row->{$this->useridfield};
848 if ($COURSE->id == SITEID) {
849 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
850 } else {
851 $profileurl = new moodle_url('/user/view.php',
852 array('id' => $userid, 'course' => $COURSE->id));
854 return html_writer::link($profileurl, $name);
858 * You can override this method in a child class. See the description of
859 * build_table which calls this method.
861 function other_cols($column, $row) {
862 return NULL;
866 * Used from col_* functions when text is to be displayed. Does the
867 * right thing - either converts text to html or strips any html tags
868 * depending on if we are downloading and what is the download type. Params
869 * are the same as format_text function in weblib.php but some default
870 * options are changed.
872 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
873 if (!$this->is_downloading()) {
874 if (is_null($options)) {
875 $options = new stdClass;
877 //some sensible defaults
878 if (!isset($options->para)) {
879 $options->para = false;
881 if (!isset($options->newlines)) {
882 $options->newlines = false;
884 if (!isset($options->smiley)) {
885 $options->smiley = false;
887 if (!isset($options->filter)) {
888 $options->filter = false;
890 return format_text($text, $format, $options);
891 } else {
892 $eci = $this->export_class_instance();
893 return $eci->format_text($text, $format, $options, $courseid);
897 * This method is deprecated although the old api is still supported.
898 * @deprecated 1.9.2 - Jun 2, 2008
900 function print_html() {
901 if (!$this->setup) {
902 return false;
904 $this->finish_html();
908 * This function is not part of the public api.
909 * @return string initial of first name we are currently filtering by
911 * @deprecated since Moodle 3.3
913 function get_initial_first() {
914 debugging('Method get_initial_first() is no longer used and has been deprecated, ' .
915 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
916 if (!$this->use_initials) {
917 return NULL;
920 return $this->prefs['i_first'];
924 * This function is not part of the public api.
925 * @return string initial of last name we are currently filtering by
927 * @deprecated since Moodle 3.3
929 function get_initial_last() {
930 debugging('Method get_initial_last() is no longer used and has been deprecated, ' .
931 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
932 if (!$this->use_initials) {
933 return NULL;
936 return $this->prefs['i_last'];
940 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
941 * @param array $alpha of letters in the alphabet.
942 * @param string $current the currently selected letter.
943 * @param string $class class name to add to this initial bar.
944 * @param string $title the name to put in front of this initial bar.
945 * @param string $urlvar URL parameter name for this initial.
947 * @deprecated since Moodle 3.3
949 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
951 debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
952 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
954 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
955 $title . ' : ';
956 if ($current) {
957 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
958 } else {
959 echo html_writer::tag('strong', get_string('all'));
962 foreach ($alpha as $letter) {
963 if ($letter === $current) {
964 echo html_writer::tag('strong', $letter);
965 } else {
966 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
970 echo html_writer::end_tag('div');
974 * This function is not part of the public api.
976 function print_initials_bar() {
977 global $OUTPUT;
979 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
980 && isset($this->columns['fullname'])) {
982 if (!empty($this->prefs['i_first'])) {
983 $ifirst = $this->prefs['i_first'];
984 } else {
985 $ifirst = '';
988 if (!empty($this->prefs['i_last'])) {
989 $ilast = $this->prefs['i_last'];
990 } else {
991 $ilast = '';
994 $prefixfirst = $this->request[TABLE_VAR_IFIRST];
995 $prefixlast = $this->request[TABLE_VAR_ILAST];
996 echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
997 echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
1003 * This function is not part of the public api.
1005 function print_nothing_to_display() {
1006 global $OUTPUT;
1008 // Render button to allow user to reset table preferences.
1009 echo $this->render_reset_button();
1011 $this->print_initials_bar();
1013 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1017 * This function is not part of the public api.
1019 function get_row_from_keyed($rowwithkeys) {
1020 if (is_object($rowwithkeys)) {
1021 $rowwithkeys = (array)$rowwithkeys;
1023 $row = array();
1024 foreach (array_keys($this->columns) as $column) {
1025 if (isset($rowwithkeys[$column])) {
1026 $row [] = $rowwithkeys[$column];
1027 } else {
1028 $row[] ='';
1031 return $row;
1035 * Get the html for the download buttons
1037 * Usually only use internally
1039 public function download_buttons() {
1040 global $OUTPUT;
1042 if ($this->is_downloadable() && !$this->is_downloading()) {
1043 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1044 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1045 } else {
1046 return '';
1051 * This function is not part of the public api.
1052 * You don't normally need to call this. It is called automatically when
1053 * needed when you start adding data to the table.
1056 function start_output() {
1057 $this->started_output = true;
1058 if ($this->exportclass!==null) {
1059 $this->exportclass->start_table($this->sheettitle);
1060 $this->exportclass->output_headers($this->headers);
1061 } else {
1062 $this->start_html();
1063 $this->print_headers();
1064 echo html_writer::start_tag('tbody');
1069 * This function is not part of the public api.
1071 function print_row($row, $classname = '') {
1072 echo $this->get_row_html($row, $classname);
1076 * Generate html code for the passed row.
1078 * @param array $row Row data.
1079 * @param string $classname classes to add.
1081 * @return string $html html code for the row passed.
1083 public function get_row_html($row, $classname = '') {
1084 static $suppress_lastrow = NULL;
1085 $rowclasses = array();
1087 if ($classname) {
1088 $rowclasses[] = $classname;
1091 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1092 $html = '';
1094 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1096 // If we have a separator, print it
1097 if ($row === NULL) {
1098 $colcount = count($this->columns);
1099 $html .= html_writer::tag('td', html_writer::tag('div', '',
1100 array('class' => 'tabledivider')), array('colspan' => $colcount));
1102 } else {
1103 $colbyindex = array_flip($this->columns);
1104 foreach ($row as $index => $data) {
1105 $column = $colbyindex[$index];
1107 if (empty($this->prefs['collapse'][$column])) {
1108 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1109 $content = '&nbsp;';
1110 } else {
1111 $content = $data;
1113 } else {
1114 $content = '&nbsp;';
1117 $html .= html_writer::tag('td', $content, array(
1118 'class' => 'cell c' . $index . $this->column_class[$column],
1119 'id' => $rowid . '_c' . $index,
1120 'style' => $this->make_styles_string($this->column_style[$column])));
1124 $html .= html_writer::end_tag('tr');
1126 $suppress_enabled = array_sum($this->column_suppress);
1127 if ($suppress_enabled) {
1128 $suppress_lastrow = $row;
1130 $this->currentrow++;
1131 return $html;
1135 * This function is not part of the public api.
1137 function finish_html() {
1138 global $OUTPUT;
1139 if (!$this->started_output) {
1140 //no data has been added to the table.
1141 $this->print_nothing_to_display();
1143 } else {
1144 // Print empty rows to fill the table to the current pagesize.
1145 // This is done so the header aria-controls attributes do not point to
1146 // non existant elements.
1147 $emptyrow = array_fill(0, count($this->columns), '');
1148 while ($this->currentrow < $this->pagesize) {
1149 $this->print_row($emptyrow, 'emptyrow');
1152 echo html_writer::end_tag('tbody');
1153 echo html_writer::end_tag('table');
1154 echo html_writer::end_tag('div');
1155 $this->wrap_html_finish();
1157 // Paging bar
1158 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1159 echo $this->download_buttons();
1162 if($this->use_pages) {
1163 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1164 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1165 echo $OUTPUT->render($pagingbar);
1171 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1172 * used by {@link print_headers()}.
1173 * @param string $column the column name, index into various names.
1174 * @param int $index numerical index of the column.
1175 * @return string HTML fragment.
1177 protected function show_hide_link($column, $index) {
1178 global $OUTPUT;
1179 // Some headers contain <br /> tags, do not include in title, hence the
1180 // strip tags.
1182 $ariacontrols = '';
1183 for ($i = 0; $i < $this->pagesize; $i++) {
1184 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1187 $ariacontrols = trim($ariacontrols);
1189 if (!empty($this->prefs['collapse'][$column])) {
1190 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1191 'aria-expanded' => 'false',
1192 'aria-controls' => $ariacontrols);
1193 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1194 $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
1196 } else if ($this->headers[$index] !== NULL) {
1197 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1198 'aria-expanded' => 'true',
1199 'aria-controls' => $ariacontrols);
1200 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1201 $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
1206 * This function is not part of the public api.
1208 function print_headers() {
1209 global $CFG, $OUTPUT;
1211 echo html_writer::start_tag('thead');
1212 echo html_writer::start_tag('tr');
1213 foreach ($this->columns as $column => $index) {
1215 $icon_hide = '';
1216 if ($this->is_collapsible) {
1217 $icon_hide = $this->show_hide_link($column, $index);
1220 $primarysortcolumn = '';
1221 $primarysortorder = '';
1222 if (reset($this->prefs['sortby'])) {
1223 $primarysortcolumn = key($this->prefs['sortby']);
1224 $primarysortorder = current($this->prefs['sortby']);
1227 switch ($column) {
1229 case 'fullname':
1230 // Check the full name display for sortable fields.
1231 $nameformat = $CFG->fullnamedisplay;
1232 if ($nameformat == 'language') {
1233 $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 * @return void
1498 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));
1513 if ($this->rawdata instanceof \core\dml\recordset_walk ||
1514 $this->rawdata instanceof moodle_recordset) {
1515 $this->rawdata->close();
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 = NULL) {
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->finish_output();
1632 * @package moodlecore
1633 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1636 class table_default_export_format_parent {
1638 * @var flexible_table or child class reference pointing to table class
1639 * object from which to export data.
1641 var $table;
1644 * @var bool output started. Keeps track of whether any output has been
1645 * started yet.
1647 var $documentstarted = false;
1650 * Constructor
1652 * @param flexible_table $table
1654 public function __construct(&$table) {
1655 $this->table =& $table;
1659 * Old syntax of class constructor. Deprecated in PHP7.
1661 * @deprecated since Moodle 3.1
1663 public function table_default_export_format_parent(&$table) {
1664 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1665 self::__construct($table);
1668 function set_table(&$table) {
1669 $this->table =& $table;
1672 function add_data($row) {
1673 return false;
1676 function add_seperator() {
1677 return false;
1680 function document_started() {
1681 return $this->documentstarted;
1684 * Given text in a variety of format codings, this function returns
1685 * the text as safe HTML or as plain text dependent on what is appropriate
1686 * for the download format. The default removes all tags.
1688 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1689 //use some whitespace to indicate where there was some line spacing.
1690 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1691 return strip_tags($text);
1696 * Dataformat exporter
1698 * @package core
1699 * @subpackage tablelib
1700 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1703 class table_dataformat_export_format extends table_default_export_format_parent {
1705 /** @var $dataformat */
1706 protected $dataformat;
1708 /** @var $rownum */
1709 protected $rownum = 0;
1711 /** @var $columns */
1712 protected $columns;
1715 * Constructor
1717 * @param string $table An sql table
1718 * @param string $dataformat type of dataformat for export
1720 public function __construct(&$table, $dataformat) {
1721 parent::__construct($table);
1723 if (ob_get_length()) {
1724 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1727 $classname = 'dataformat_' . $dataformat . '\writer';
1728 if (!class_exists($classname)) {
1729 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1731 $this->dataformat = new $classname;
1733 // The dataformat export time to first byte could take a while to generate...
1734 set_time_limit(0);
1736 // Close the session so that the users other tabs in the same session are not blocked.
1737 \core\session\manager::write_close();
1741 * Start document
1743 * @param string $filename
1745 public function start_document($filename) {
1746 $this->filename = $filename;
1747 $this->documentstarted = true;
1748 $this->dataformat->set_filename($filename);
1752 * Start export
1754 * @param string $sheettitle optional spreadsheet worksheet title
1756 public function start_table($sheettitle) {
1757 $this->dataformat->set_sheettitle($sheettitle);
1758 $this->dataformat->send_http_headers();
1762 * Output headers
1764 * @param array $headers
1766 public function output_headers($headers) {
1767 $this->columns = $headers;
1768 $this->dataformat->write_header($headers);
1772 * Add a row of data
1774 * @param array $row One record of data
1776 public function add_data($row) {
1777 $this->dataformat->write_record($row, $this->rownum++);
1778 return true;
1782 * Finish export
1784 public function finish_table() {
1785 $this->dataformat->write_footer($this->columns);
1789 * Finish download
1791 public function finish_document() {
1792 exit;