Merge branch 'MDL-56057_master' of git://github.com/dmonllao/moodle
[moodle.git] / lib / tablelib.php
blob246916ee3b88bd3ddf7bae298897a97931535cf9
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 } else if (isset($SESSION->flextable[$this->uniqueid])) {
453 $this->prefs = $SESSION->flextable[$this->uniqueid];
456 // Set up default preferences if needed.
457 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
458 $this->prefs = array(
459 'collapse' => array(),
460 'sortby' => array(),
461 'i_first' => '',
462 'i_last' => '',
463 'textsort' => $this->column_textsort,
466 $oldprefs = $this->prefs;
468 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
469 isset($this->columns[$showcol])) {
470 $this->prefs['collapse'][$showcol] = false;
472 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
473 isset($this->columns[$hidecol])) {
474 $this->prefs['collapse'][$hidecol] = true;
475 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
476 unset($this->prefs['sortby'][$hidecol]);
480 // Now, update the column attributes for collapsed columns
481 foreach (array_keys($this->columns) as $column) {
482 if (!empty($this->prefs['collapse'][$column])) {
483 $this->column_style[$column]['width'] = '10px';
487 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
488 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
489 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
490 && isset($this->columns['fullname']))) {
492 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
493 // This key already exists somewhere. Change its sortorder and bring it to the top.
494 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
495 unset($this->prefs['sortby'][$sortcol]);
496 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
497 } else {
498 // Key doesn't exist, so just add it to the beginning of the array, ascending order
499 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
502 // Finally, make sure that no more than $this->maxsortkeys are present into the array
503 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
506 // 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.
507 // This prevents results from being returned in a random order if the only order by column contains equal values.
508 if (!empty($this->sort_default_column)) {
509 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
510 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
511 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
515 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
516 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
517 $this->prefs['i_last'] = $ilast;
520 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
521 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
522 $this->prefs['i_first'] = $ifirst;
525 // Save user preferences if they have changed.
526 if ($this->prefs != $oldprefs) {
527 if ($this->persistent) {
528 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
529 } else {
530 $SESSION->flextable[$this->uniqueid] = $this->prefs;
533 unset($oldprefs);
535 if (empty($this->baseurl)) {
536 debugging('You should set baseurl when using flexible_table.');
537 global $PAGE;
538 $this->baseurl = $PAGE->url;
541 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
542 $this->setup = true;
544 // Always introduce the "flexible" class for the table if not specified
545 if (empty($this->attributes)) {
546 $this->attributes['class'] = 'flexible';
547 } else if (!isset($this->attributes['class'])) {
548 $this->attributes['class'] = 'flexible';
549 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
550 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
555 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
556 * @param string $uniqueid the identifier for a table.
557 * @return SQL fragment that can be used in an ORDER BY clause.
559 public static function get_sort_for_table($uniqueid) {
560 global $SESSION;
561 if (isset($SESSION->flextable[$uniqueid])) {
562 $prefs = $SESSION->flextable[$uniqueid];
563 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
564 return '';
567 if (empty($prefs['sortby'])) {
568 return '';
570 if (empty($prefs['textsort'])) {
571 $prefs['textsort'] = array();
574 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
578 * Prepare an an order by clause from the list of columns to be sorted.
579 * @param array $cols column name => SORT_ASC or SORT_DESC
580 * @return SQL fragment that can be used in an ORDER BY clause.
582 public static function construct_order_by($cols, $textsortcols=array()) {
583 global $DB;
584 $bits = array();
586 foreach ($cols as $column => $order) {
587 if (in_array($column, $textsortcols)) {
588 $column = $DB->sql_order_by_text($column);
590 if ($order == SORT_ASC) {
591 $bits[] = $column . ' ASC';
592 } else {
593 $bits[] = $column . ' DESC';
597 return implode(', ', $bits);
601 * @return SQL fragment that can be used in an ORDER BY clause.
603 public function get_sql_sort() {
604 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
608 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
609 * @return array column name => SORT_... constant.
611 public function get_sort_columns() {
612 if (!$this->setup) {
613 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
616 if (empty($this->prefs['sortby'])) {
617 return array();
620 foreach ($this->prefs['sortby'] as $column => $notused) {
621 if (isset($this->columns[$column])) {
622 continue; // This column is OK.
624 if (in_array($column, get_all_user_name_fields()) &&
625 isset($this->columns['fullname'])) {
626 continue; // This column is OK.
628 // This column is not OK.
629 unset($this->prefs['sortby'][$column]);
632 return $this->prefs['sortby'];
636 * @return int the offset for LIMIT clause of SQL
638 function get_page_start() {
639 if (!$this->use_pages) {
640 return '';
642 return $this->currpage * $this->pagesize;
646 * @return int the pagesize for LIMIT clause of SQL
648 function get_page_size() {
649 if (!$this->use_pages) {
650 return '';
652 return $this->pagesize;
656 * @return string sql to add to where statement.
658 function get_sql_where() {
659 global $DB;
661 $conditions = array();
662 $params = array();
664 if (isset($this->columns['fullname'])) {
665 static $i = 0;
666 $i++;
668 if (!empty($this->prefs['i_first'])) {
669 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
670 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
672 if (!empty($this->prefs['i_last'])) {
673 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
674 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
678 return array(implode(" AND ", $conditions), $params);
682 * Add a row of data to the table. This function takes an array or object with
683 * column names as keys or property names.
685 * It ignores any elements with keys that are not defined as columns. It
686 * puts in empty strings into the row when there is no element in the passed
687 * array corresponding to a column in the table. It puts the row elements in
688 * the proper order (internally row table data is stored by in arrays with
689 * a numerical index corresponding to the column number).
691 * @param object|array $rowwithkeys array keys or object property names are column names,
692 * as defined in call to define_columns.
693 * @param string $classname CSS class name to add to this row's tr tag.
695 function add_data_keyed($rowwithkeys, $classname = '') {
696 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
700 * Add a number of rows to the table at once. And optionally finish output after they have been added.
702 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
703 * object or array is added to table. We expect properties for the row array as would be
704 * passed to add_data_keyed.
705 * @param bool $finish
707 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
708 foreach ($rowstoadd as $row) {
709 if (is_null($row)) {
710 $this->add_separator();
711 } else {
712 $this->add_data_keyed($this->format_row($row));
715 if ($finish) {
716 $this->finish_output(!$this->is_downloading());
721 * Add a seperator line to table.
723 function add_separator() {
724 if (!$this->setup) {
725 return false;
727 $this->add_data(NULL);
731 * This method actually directly echoes the row passed to it now or adds it
732 * to the download. If this is the first row and start_output has not
733 * already been called this method also calls start_output to open the table
734 * or send headers for the downloaded.
735 * Can be used as before. print_html now calls finish_html to close table.
737 * @param array $row a numerically keyed row of data to add to the table.
738 * @param string $classname CSS class name to add to this row's tr tag.
739 * @return bool success.
741 function add_data($row, $classname = '') {
742 if (!$this->setup) {
743 return false;
745 if (!$this->started_output) {
746 $this->start_output();
748 if ($this->exportclass!==null) {
749 if ($row === null) {
750 $this->exportclass->add_seperator();
751 } else {
752 $this->exportclass->add_data($row);
754 } else {
755 $this->print_row($row, $classname);
757 return true;
761 * You should call this to finish outputting the table data after adding
762 * data to the table with add_data or add_data_keyed.
765 function finish_output($closeexportclassdoc = true) {
766 if ($this->exportclass!==null) {
767 $this->exportclass->finish_table();
768 if ($closeexportclassdoc) {
769 $this->exportclass->finish_document();
771 } else {
772 $this->finish_html();
777 * Hook that can be overridden in child classes to wrap a table in a form
778 * for example. Called only when there is data to display and not
779 * downloading.
781 function wrap_html_start() {
785 * Hook that can be overridden in child classes to wrap a table in a form
786 * for example. Called only when there is data to display and not
787 * downloading.
789 function wrap_html_finish() {
793 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
794 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
795 * displaying table as html, adding a div wrap, etc.
797 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
799 * @param array|object $row row of data from db used to make one row of the table.
800 * @return array one row for the table, added using add_data_keyed method.
802 function format_row($row) {
803 if (is_array($row)) {
804 $row = (object)$row;
806 $formattedrow = array();
807 foreach (array_keys($this->columns) as $column) {
808 $colmethodname = 'col_'.$column;
809 if (method_exists($this, $colmethodname)) {
810 $formattedcolumn = $this->$colmethodname($row);
811 } else {
812 $formattedcolumn = $this->other_cols($column, $row);
813 if ($formattedcolumn===NULL) {
814 $formattedcolumn = $row->$column;
817 $formattedrow[$column] = $formattedcolumn;
819 return $formattedrow;
823 * Fullname is treated as a special columname in tablelib and should always
824 * be treated the same as the fullname of a user.
825 * @uses $this->useridfield if the userid field is not expected to be id
826 * then you need to override $this->useridfield to point at the correct
827 * field for the user id.
829 * @param object $row the data from the db containing all fields from the
830 * users table necessary to construct the full name of the user in
831 * current language.
832 * @return string contents of cell in column 'fullname', for this row.
834 function col_fullname($row) {
835 global $COURSE;
837 $name = fullname($row);
838 if ($this->download) {
839 return $name;
842 $userid = $row->{$this->useridfield};
843 if ($COURSE->id == SITEID) {
844 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
845 } else {
846 $profileurl = new moodle_url('/user/view.php',
847 array('id' => $userid, 'course' => $COURSE->id));
849 return html_writer::link($profileurl, $name);
853 * You can override this method in a child class. See the description of
854 * build_table which calls this method.
856 function other_cols($column, $row) {
857 return NULL;
861 * Used from col_* functions when text is to be displayed. Does the
862 * right thing - either converts text to html or strips any html tags
863 * depending on if we are downloading and what is the download type. Params
864 * are the same as format_text function in weblib.php but some default
865 * options are changed.
867 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
868 if (!$this->is_downloading()) {
869 if (is_null($options)) {
870 $options = new stdClass;
872 //some sensible defaults
873 if (!isset($options->para)) {
874 $options->para = false;
876 if (!isset($options->newlines)) {
877 $options->newlines = false;
879 if (!isset($options->smiley)) {
880 $options->smiley = false;
882 if (!isset($options->filter)) {
883 $options->filter = false;
885 return format_text($text, $format, $options);
886 } else {
887 $eci = $this->export_class_instance();
888 return $eci->format_text($text, $format, $options, $courseid);
892 * This method is deprecated although the old api is still supported.
893 * @deprecated 1.9.2 - Jun 2, 2008
895 function print_html() {
896 if (!$this->setup) {
897 return false;
899 $this->finish_html();
903 * This function is not part of the public api.
904 * @return string initial of first name we are currently filtering by
906 function get_initial_first() {
907 if (!$this->use_initials) {
908 return NULL;
911 return $this->prefs['i_first'];
915 * This function is not part of the public api.
916 * @return string initial of last name we are currently filtering by
918 function get_initial_last() {
919 if (!$this->use_initials) {
920 return NULL;
923 return $this->prefs['i_last'];
927 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
928 * @param array $alpha of letters in the alphabet.
929 * @param string $current the currently selected letter.
930 * @param string $class class name to add to this initial bar.
931 * @param string $title the name to put in front of this initial bar.
932 * @param string $urlvar URL parameter name for this initial.
934 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
935 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
936 $title . ' : ';
937 if ($current) {
938 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
939 } else {
940 echo html_writer::tag('strong', get_string('all'));
943 foreach ($alpha as $letter) {
944 if ($letter === $current) {
945 echo html_writer::tag('strong', $letter);
946 } else {
947 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
951 echo html_writer::end_tag('div');
955 * This function is not part of the public api.
957 function print_initials_bar() {
958 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
959 && isset($this->columns['fullname'])) {
961 $alpha = explode(',', get_string('alphabet', 'langconfig'));
963 // Bar of first initials
964 if (!empty($this->prefs['i_first'])) {
965 $ifirst = $this->prefs['i_first'];
966 } else {
967 $ifirst = '';
969 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
970 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
972 // Bar of last initials
973 if (!empty($this->prefs['i_last'])) {
974 $ilast = $this->prefs['i_last'];
975 } else {
976 $ilast = '';
978 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
979 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
984 * This function is not part of the public api.
986 function print_nothing_to_display() {
987 global $OUTPUT;
989 // Render button to allow user to reset table preferences.
990 echo $this->render_reset_button();
992 $this->print_initials_bar();
994 echo $OUTPUT->heading(get_string('nothingtodisplay'));
998 * This function is not part of the public api.
1000 function get_row_from_keyed($rowwithkeys) {
1001 if (is_object($rowwithkeys)) {
1002 $rowwithkeys = (array)$rowwithkeys;
1004 $row = array();
1005 foreach (array_keys($this->columns) as $column) {
1006 if (isset($rowwithkeys[$column])) {
1007 $row [] = $rowwithkeys[$column];
1008 } else {
1009 $row[] ='';
1012 return $row;
1016 * Get the html for the download buttons
1018 * Usually only use internally
1020 public function download_buttons() {
1021 global $OUTPUT;
1023 if ($this->is_downloadable() && !$this->is_downloading()) {
1024 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
1025 $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
1026 } else {
1027 return '';
1032 * This function is not part of the public api.
1033 * You don't normally need to call this. It is called automatically when
1034 * needed when you start adding data to the table.
1037 function start_output() {
1038 $this->started_output = true;
1039 if ($this->exportclass!==null) {
1040 $this->exportclass->start_table($this->sheettitle);
1041 $this->exportclass->output_headers($this->headers);
1042 } else {
1043 $this->start_html();
1044 $this->print_headers();
1045 echo html_writer::start_tag('tbody');
1050 * This function is not part of the public api.
1052 function print_row($row, $classname = '') {
1053 echo $this->get_row_html($row, $classname);
1057 * Generate html code for the passed row.
1059 * @param array $row Row data.
1060 * @param string $classname classes to add.
1062 * @return string $html html code for the row passed.
1064 public function get_row_html($row, $classname = '') {
1065 static $suppress_lastrow = NULL;
1066 $rowclasses = array();
1068 if ($classname) {
1069 $rowclasses[] = $classname;
1072 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1073 $html = '';
1075 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1077 // If we have a separator, print it
1078 if ($row === NULL) {
1079 $colcount = count($this->columns);
1080 $html .= html_writer::tag('td', html_writer::tag('div', '',
1081 array('class' => 'tabledivider')), array('colspan' => $colcount));
1083 } else {
1084 $colbyindex = array_flip($this->columns);
1085 foreach ($row as $index => $data) {
1086 $column = $colbyindex[$index];
1088 if (empty($this->prefs['collapse'][$column])) {
1089 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1090 $content = '&nbsp;';
1091 } else {
1092 $content = $data;
1094 } else {
1095 $content = '&nbsp;';
1098 $html .= html_writer::tag('td', $content, array(
1099 'class' => 'cell c' . $index . $this->column_class[$column],
1100 'id' => $rowid . '_c' . $index,
1101 'style' => $this->make_styles_string($this->column_style[$column])));
1105 $html .= html_writer::end_tag('tr');
1107 $suppress_enabled = array_sum($this->column_suppress);
1108 if ($suppress_enabled) {
1109 $suppress_lastrow = $row;
1111 $this->currentrow++;
1112 return $html;
1116 * This function is not part of the public api.
1118 function finish_html() {
1119 global $OUTPUT;
1120 if (!$this->started_output) {
1121 //no data has been added to the table.
1122 $this->print_nothing_to_display();
1124 } else {
1125 // Print empty rows to fill the table to the current pagesize.
1126 // This is done so the header aria-controls attributes do not point to
1127 // non existant elements.
1128 $emptyrow = array_fill(0, count($this->columns), '');
1129 while ($this->currentrow < $this->pagesize) {
1130 $this->print_row($emptyrow, 'emptyrow');
1133 echo html_writer::end_tag('tbody');
1134 echo html_writer::end_tag('table');
1135 echo html_writer::end_tag('div');
1136 $this->wrap_html_finish();
1138 // Paging bar
1139 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1140 echo $this->download_buttons();
1143 if($this->use_pages) {
1144 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1145 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1146 echo $OUTPUT->render($pagingbar);
1152 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1153 * used by {@link print_headers()}.
1154 * @param string $column the column name, index into various names.
1155 * @param int $index numerical index of the column.
1156 * @return string HTML fragment.
1158 protected function show_hide_link($column, $index) {
1159 global $OUTPUT;
1160 // Some headers contain <br /> tags, do not include in title, hence the
1161 // strip tags.
1163 $ariacontrols = '';
1164 for ($i = 0; $i < $this->pagesize; $i++) {
1165 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1168 $ariacontrols = trim($ariacontrols);
1170 if (!empty($this->prefs['collapse'][$column])) {
1171 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1172 'aria-expanded' => 'false',
1173 'aria-controls' => $ariacontrols);
1174 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1175 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1176 $linkattributes);
1178 } else if ($this->headers[$index] !== NULL) {
1179 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1180 'aria-expanded' => 'true',
1181 'aria-controls' => $ariacontrols);
1182 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1183 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1184 $linkattributes);
1189 * This function is not part of the public api.
1191 function print_headers() {
1192 global $CFG, $OUTPUT;
1194 echo html_writer::start_tag('thead');
1195 echo html_writer::start_tag('tr');
1196 foreach ($this->columns as $column => $index) {
1198 $icon_hide = '';
1199 if ($this->is_collapsible) {
1200 $icon_hide = $this->show_hide_link($column, $index);
1203 $primarysortcolumn = '';
1204 $primarysortorder = '';
1205 if (reset($this->prefs['sortby'])) {
1206 $primarysortcolumn = key($this->prefs['sortby']);
1207 $primarysortorder = current($this->prefs['sortby']);
1210 switch ($column) {
1212 case 'fullname':
1213 // Check the full name display for sortable fields.
1214 $nameformat = $CFG->fullnamedisplay;
1215 if ($nameformat == 'language') {
1216 $nameformat = get_string('fullnamedisplay');
1218 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1220 if (!empty($requirednames)) {
1221 if ($this->is_sortable($column)) {
1222 // Done this way for the possibility of more than two sortable full name display fields.
1223 $this->headers[$index] = '';
1224 foreach ($requirednames as $name) {
1225 $sortname = $this->sort_link(get_string($name),
1226 $name, $primarysortcolumn === $name, $primarysortorder);
1227 $this->headers[$index] .= $sortname . ' / ';
1229 $helpicon = '';
1230 if (isset($this->helpforheaders[$index])) {
1231 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1233 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1236 break;
1238 case 'userpic':
1239 // do nothing, do not display sortable links
1240 break;
1242 default:
1243 if ($this->is_sortable($column)) {
1244 $helpicon = '';
1245 if (isset($this->helpforheaders[$index])) {
1246 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1248 $this->headers[$index] = $this->sort_link($this->headers[$index],
1249 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1253 $attributes = array(
1254 'class' => 'header c' . $index . $this->column_class[$column],
1255 'scope' => 'col',
1257 if ($this->headers[$index] === NULL) {
1258 $content = '&nbsp;';
1259 } else if (!empty($this->prefs['collapse'][$column])) {
1260 $content = $icon_hide;
1261 } else {
1262 if (is_array($this->column_style[$column])) {
1263 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1265 $helpicon = '';
1266 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1267 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1269 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1270 $icon_hide, array('class' => 'commands'));
1272 echo html_writer::tag('th', $content, $attributes);
1275 echo html_writer::end_tag('tr');
1276 echo html_writer::end_tag('thead');
1280 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1281 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1282 * @param int $order SORT_ASC or SORT_DESC
1283 * @return string HTML fragment.
1285 protected function sort_icon($isprimary, $order) {
1286 global $OUTPUT;
1288 if (!$isprimary) {
1289 return '';
1292 if ($order == SORT_ASC) {
1293 return html_writer::empty_tag('img',
1294 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1295 } else {
1296 return html_writer::empty_tag('img',
1297 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1302 * Generate the correct tool tip for changing the sort order. This is a
1303 * helper method used by {@link sort_link()}.
1304 * @param bool $isprimary whether the is column is the current primary sort column.
1305 * @param int $order SORT_ASC or SORT_DESC
1306 * @return string the correct title.
1308 protected function sort_order_name($isprimary, $order) {
1309 if ($isprimary && $order != SORT_ASC) {
1310 return get_string('desc');
1311 } else {
1312 return get_string('asc');
1317 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1318 * @param string $text the text for the link.
1319 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1320 * @param bool $isprimary whether the is column is the current primary sort column.
1321 * @param int $order SORT_ASC or SORT_DESC
1322 * @return string HTML fragment.
1324 protected function sort_link($text, $column, $isprimary, $order) {
1325 return html_writer::link($this->baseurl->out(false,
1326 array($this->request[TABLE_VAR_SORT] => $column)),
1327 $text . get_accesshide(get_string('sortby') . ' ' .
1328 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1329 $this->sort_icon($isprimary, $order);
1333 * This function is not part of the public api.
1335 function start_html() {
1336 global $OUTPUT;
1338 // Render button to allow user to reset table preferences.
1339 echo $this->render_reset_button();
1341 // Do we need to print initial bars?
1342 $this->print_initials_bar();
1344 // Paging bar
1345 if ($this->use_pages) {
1346 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1347 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1348 echo $OUTPUT->render($pagingbar);
1351 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1352 echo $this->download_buttons();
1355 $this->wrap_html_start();
1356 // Start of main data table
1358 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1359 echo html_writer::start_tag('table', $this->attributes);
1364 * This function is not part of the public api.
1365 * @param array $styles CSS-property => value
1366 * @return string values suitably to go in a style="" attribute in HTML.
1368 function make_styles_string($styles) {
1369 if (empty($styles)) {
1370 return null;
1373 $string = '';
1374 foreach($styles as $property => $value) {
1375 $string .= $property . ':' . $value . ';';
1377 return $string;
1381 * Generate the HTML for the table preferences reset button.
1383 * @return string HTML fragment, empty string if no need to reset
1385 protected function render_reset_button() {
1387 if (!$this->can_be_reset()) {
1388 return '';
1391 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1393 $html = html_writer::start_div('resettable mdl-right');
1394 $html .= html_writer::link($url, get_string('resettable'));
1395 $html .= html_writer::end_div();
1397 return $html;
1401 * Are there some table preferences that can be reset?
1403 * If true, then the "reset table preferences" widget should be displayed.
1405 * @return bool
1407 protected function can_be_reset() {
1409 // Loop through preferences and make sure they are empty or set to the default value.
1410 foreach ($this->prefs as $prefname => $prefval) {
1412 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1413 // Check if the actual sorting differs from the default one.
1414 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1415 return true;
1418 } else if ($prefname === 'collapse' and !empty($prefval)) {
1419 // Check if there are some collapsed columns (all are expanded by default).
1420 foreach ($prefval as $columnname => $iscollapsed) {
1421 if ($iscollapsed) {
1422 return true;
1426 } else if (!empty($prefval)) {
1427 // For all other cases, we just check if some preference is set.
1428 return true;
1432 return false;
1438 * @package moodlecore
1439 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1440 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1442 class table_sql extends flexible_table {
1444 public $countsql = NULL;
1445 public $countparams = NULL;
1447 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1449 public $sql = NULL;
1451 * @var array|\Traversable Data fetched from the db.
1453 public $rawdata = NULL;
1456 * @var bool Overriding default for this.
1458 public $is_sortable = true;
1460 * @var bool Overriding default for this.
1462 public $is_collapsible = true;
1465 * @param string $uniqueid a string identifying this table.Used as a key in
1466 * session vars.
1468 function __construct($uniqueid) {
1469 parent::__construct($uniqueid);
1470 // some sensible defaults
1471 $this->set_attribute('cellspacing', '0');
1472 $this->set_attribute('class', 'generaltable generalbox');
1476 * Take the data returned from the db_query and go through all the rows
1477 * processing each col using either col_{columnname} method or other_cols
1478 * method or if other_cols returns NULL then put the data straight into the
1479 * table.
1481 * @return void
1483 function build_table() {
1485 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1486 return;
1488 if (!$this->rawdata) {
1489 return;
1492 foreach ($this->rawdata as $row) {
1493 $formattedrow = $this->format_row($row);
1494 $this->add_data_keyed($formattedrow,
1495 $this->get_row_class($row));
1498 if ($this->rawdata instanceof \core\dml\recordset_walk ||
1499 $this->rawdata instanceof moodle_recordset) {
1500 $this->rawdata->close();
1505 * Get any extra classes names to add to this row in the HTML.
1506 * @param $row array the data for this row.
1507 * @return string added to the class="" attribute of the tr.
1509 function get_row_class($row) {
1510 return '';
1514 * This is only needed if you want to use different sql to count rows.
1515 * Used for example when perhaps all db JOINS are not needed when counting
1516 * records. You don't need to call this function the count_sql
1517 * will be generated automatically.
1519 * We need to count rows returned by the db seperately to the query itself
1520 * as we need to know how many pages of data we have to display.
1522 function set_count_sql($sql, array $params = NULL) {
1523 $this->countsql = $sql;
1524 $this->countparams = $params;
1528 * Set the sql to query the db. Query will be :
1529 * SELECT $fields FROM $from WHERE $where
1530 * Of course you can use sub-queries, JOINS etc. by putting them in the
1531 * appropriate clause of the query.
1533 function set_sql($fields, $from, $where, array $params = NULL) {
1534 $this->sql = new stdClass();
1535 $this->sql->fields = $fields;
1536 $this->sql->from = $from;
1537 $this->sql->where = $where;
1538 $this->sql->params = $params;
1542 * Query the db. Store results in the table object for use by build_table.
1544 * @param int $pagesize size of page for paginated displayed table.
1545 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1546 * will only be used if there is a fullname column defined for the table.
1548 function query_db($pagesize, $useinitialsbar=true) {
1549 global $DB;
1550 if (!$this->is_downloading()) {
1551 if ($this->countsql === NULL) {
1552 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1553 $this->countparams = $this->sql->params;
1555 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1556 if ($useinitialsbar && !$this->is_downloading()) {
1557 $this->initialbars($grandtotal > $pagesize);
1560 list($wsql, $wparams) = $this->get_sql_where();
1561 if ($wsql) {
1562 $this->countsql .= ' AND '.$wsql;
1563 $this->countparams = array_merge($this->countparams, $wparams);
1565 $this->sql->where .= ' AND '.$wsql;
1566 $this->sql->params = array_merge($this->sql->params, $wparams);
1568 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1569 } else {
1570 $total = $grandtotal;
1573 $this->pagesize($pagesize, $total);
1576 // Fetch the attempts
1577 $sort = $this->get_sql_sort();
1578 if ($sort) {
1579 $sort = "ORDER BY $sort";
1581 $sql = "SELECT
1582 {$this->sql->fields}
1583 FROM {$this->sql->from}
1584 WHERE {$this->sql->where}
1585 {$sort}";
1587 if (!$this->is_downloading()) {
1588 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1589 } else {
1590 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1595 * Convenience method to call a number of methods for you to display the
1596 * table.
1598 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1599 global $DB;
1600 if (!$this->columns) {
1601 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}",
1602 $this->sql->params, IGNORE_MULTIPLE);
1603 //if columns is not set then define columns as the keys of the rows returned
1604 //from the db.
1605 $this->define_columns(array_keys((array)$onerow));
1606 $this->define_headers(array_keys((array)$onerow));
1608 $this->setup();
1609 $this->query_db($pagesize, $useinitialsbar);
1610 $this->build_table();
1611 $this->finish_output();
1617 * @package moodlecore
1618 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1621 class table_default_export_format_parent {
1623 * @var flexible_table or child class reference pointing to table class
1624 * object from which to export data.
1626 var $table;
1629 * @var bool output started. Keeps track of whether any output has been
1630 * started yet.
1632 var $documentstarted = false;
1635 * Constructor
1637 * @param flexible_table $table
1639 public function __construct(&$table) {
1640 $this->table =& $table;
1644 * Old syntax of class constructor. Deprecated in PHP7.
1646 * @deprecated since Moodle 3.1
1648 public function table_default_export_format_parent(&$table) {
1649 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1650 self::__construct($table);
1653 function set_table(&$table) {
1654 $this->table =& $table;
1657 function add_data($row) {
1658 return false;
1661 function add_seperator() {
1662 return false;
1665 function document_started() {
1666 return $this->documentstarted;
1669 * Given text in a variety of format codings, this function returns
1670 * the text as safe HTML or as plain text dependent on what is appropriate
1671 * for the download format. The default removes all tags.
1673 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1674 //use some whitespace to indicate where there was some line spacing.
1675 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1676 return strip_tags($text);
1681 * Dataformat exporter
1683 * @package core
1684 * @subpackage tablelib
1685 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
1686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1688 class table_dataformat_export_format extends table_default_export_format_parent {
1690 /** @var $dataformat */
1691 protected $dataformat;
1693 /** @var $rownum */
1694 protected $rownum = 0;
1696 /** @var $columns */
1697 protected $columns;
1700 * Constructor
1702 * @param string $table An sql table
1703 * @param string $dataformat type of dataformat for export
1705 public function __construct(&$table, $dataformat) {
1706 parent::__construct($table);
1708 if (ob_get_length()) {
1709 throw new coding_exception("Output can not be buffered before instantiating table_dataformat_export_format");
1712 $classname = 'dataformat_' . $dataformat . '\writer';
1713 if (!class_exists($classname)) {
1714 throw new coding_exception("Unable to locate dataformat/$dataformat/classes/writer.php");
1716 $this->dataformat = new $classname;
1718 // The dataformat export time to first byte could take a while to generate...
1719 set_time_limit(0);
1721 // Close the session so that the users other tabs in the same session are not blocked.
1722 \core\session\manager::write_close();
1726 * Start document
1728 * @param string $filename
1730 public function start_document($filename) {
1731 $this->filename = $filename;
1732 $this->documentstarted = true;
1733 $this->dataformat->set_filename($filename);
1737 * Start export
1739 * @param string $sheettitle optional spreadsheet worksheet title
1741 public function start_table($sheettitle) {
1742 $this->dataformat->set_sheettitle($sheettitle);
1743 $this->dataformat->send_http_headers();
1747 * Output headers
1749 * @param array $headers
1751 public function output_headers($headers) {
1752 $this->columns = $headers;
1753 $this->dataformat->write_header($headers);
1757 * Add a row of data
1759 * @param array $row One record of data
1761 public function add_data($row) {
1762 $this->dataformat->write_record($row, $this->rownum++);
1763 return true;
1767 * Finish export
1769 public function finish_table() {
1770 $this->dataformat->write_footer($this->columns);
1774 * Finish download
1776 public function finish_document() {
1777 exit;