3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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();
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);
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);
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 {
57 var $attributes = array();
58 var $headers = array();
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();
72 var $request = array();
75 * @var bool Whether or not to store table properties in the user_preferences table.
77 private $persistent = false;
78 var $is_collapsible = false;
79 var $is_sortable = false;
80 var $use_pages = false;
81 var $use_initials = false;
88 var $sort_default_column = NULL;
89 var $sort_default_order = SORT_ASC;
92 * Array of positions in which to display download controls.
94 var $showdownloadbuttonsat= array(TABLE_P_TOP);
97 * @var string Key of field returned by db query that is the id field of the
98 * user table or equivalent.
100 public $useridfield = 'id';
103 * @var string which download plugin to use. Default '' means none - print
104 * html table with paging. Property set by is_downloading which typically
105 * passes in cleaned data from $
110 * @var bool whether data is downloadable from table. Determines whether
111 * to display download buttons. Set by method downloadable().
113 var $downloadable = false;
116 * @var string which download plugin to use. Default '' means none - print
117 * html table with paging.
119 var $defaultdownloadformat = 'csv';
122 * @var bool Has start output been called yet?
124 var $started_output = false;
126 var $exportclass = null;
129 * @var array For storing user-customised table properties in the user_preferences db table.
131 private $prefs = array();
135 * @param int $uniqueid all tables have to have a unique id, this is used
136 * as a key when storing table properties like sort order in the session.
138 function __construct($uniqueid) {
139 $this->uniqueid = $uniqueid;
140 $this->request = array(
141 TABLE_VAR_SORT => 'tsort',
142 TABLE_VAR_HIDE => 'thide',
143 TABLE_VAR_SHOW => 'tshow',
144 TABLE_VAR_IFIRST => 'tifirst',
145 TABLE_VAR_ILAST => 'tilast',
146 TABLE_VAR_PAGE => 'page',
147 TABLE_VAR_RESET => 'treset'
152 * Call this to pass the download type. Use :
153 * $download = optional_param('download', '', PARAM_ALPHA);
154 * To get the download type. We assume that if you call this function with
155 * params that this table's data is downloadable, so we call is_downloadable
156 * for you (even if the param is '', which means no download this time.
157 * Also you can call this method with no params to get the current set
159 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
160 * @param string $filename filename for downloads without file extension.
161 * @param string $sheettitle title for downloaded data.
162 * @return string download type. One of csv, tsv, xhtml, ods, etc
164 function is_downloading($download = null, $filename='', $sheettitle='') {
165 if ($download!==null) {
166 $this->sheettitle = $sheettitle;
167 $this->is_downloadable(true);
168 $this->download = $download;
169 $this->filename = clean_filename($filename);
170 $this->export_class_instance();
172 return $this->download;
176 * Get, and optionally set, the export class.
177 * @param $exportclass (optional) if passed, set the table to use this export class.
178 * @return table_default_export_format_parent the export class in use (after any set).
180 function export_class_instance($exportclass = null) {
181 if (!is_null($exportclass)) {
182 $this->started_output = true;
183 $this->exportclass = $exportclass;
184 $this->exportclass->table = $this;
185 } else if (is_null($this->exportclass) && !empty($this->download)) {
186 $classname = 'table_'.$this->download.'_export_format';
187 $this->exportclass = new $classname($this);
188 if (!$this->exportclass->document_started()) {
189 $this->exportclass->start_document($this->filename);
192 return $this->exportclass;
196 * Probably don't need to call this directly. Calling is_downloading with a
197 * param automatically sets table as downloadable.
199 * @param bool $downloadable optional param to set whether data from
200 * table is downloadable. If ommitted this function can be used to get
201 * current state of table.
202 * @return bool whether table data is set to be downloadable.
204 function is_downloadable($downloadable = null) {
205 if ($downloadable !== null) {
206 $this->downloadable = $downloadable;
208 return $this->downloadable;
212 * Call with boolean true to store table layout changes in the user_preferences table.
213 * Note: user_preferences.value has a maximum length of 1333 characters.
214 * Call with no parameter to get current state of table persistence.
216 * @param bool $persistent Optional parameter to set table layout persistence.
217 * @return bool Whether or not the table layout preferences will persist.
219 public function is_persistent($persistent = null) {
220 if ($persistent == true) {
221 $this->persistent = true;
223 return $this->persistent;
227 * Where to show download buttons.
228 * @param array $showat array of postions in which to show download buttons.
229 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
231 function show_download_buttons_at($showat) {
232 $this->showdownloadbuttonsat = $showat;
236 * Sets the is_sortable variable to the given boolean, sort_default_column to
237 * the given string, and the sort_default_order to the given integer.
239 * @param string $defaultcolumn
240 * @param int $defaultorder
243 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
244 $this->is_sortable = $bool;
245 $this->sort_default_column = $defaultcolumn;
246 $this->sort_default_order = $defaultorder;
250 * Use text sorting functions for this column (required for text columns with Oracle).
251 * Be warned that you cannot use this with column aliases. You can only do this
252 * with real columns. See MDL-40481 for an example.
253 * @param string column name
255 function text_sorting($column) {
256 $this->column_textsort[] = $column;
260 * Do not sort using this column
261 * @param string column name
263 function no_sorting($column) {
264 $this->column_nosort[] = $column;
268 * Is the column sortable?
269 * @param string column name, null means table
272 function is_sortable($column = null) {
273 if (empty($column)) {
274 return $this->is_sortable;
276 if (!$this->is_sortable) {
279 return !in_array($column, $this->column_nosort);
283 * Sets the is_collapsible variable to the given boolean.
287 function collapsible($bool) {
288 $this->is_collapsible = $bool;
292 * Sets the use_pages variable to the given boolean.
296 function pageable($bool) {
297 $this->use_pages = $bool;
301 * Sets the use_initials variable to the given boolean.
305 function initialbars($bool) {
306 $this->use_initials = $bool;
310 * Sets the pagesize variable to the given integer, the totalrows variable
311 * to the given integer, and the use_pages variable to true.
312 * @param int $perpage
316 function pagesize($perpage, $total) {
317 $this->pagesize = $perpage;
318 $this->totalrows = $total;
319 $this->use_pages = true;
323 * Assigns each given variable in the array to the corresponding index
324 * in the request class variable.
325 * @param array $variables
328 function set_control_variables($variables) {
329 foreach ($variables as $what => $variable) {
330 if (isset($this->request[$what])) {
331 $this->request[$what] = $variable;
337 * Gives the given $value to the $attribute index of $this->attributes.
338 * @param string $attribute
339 * @param mixed $value
342 function set_attribute($attribute, $value) {
343 $this->attributes[$attribute] = $value;
347 * What this method does is set the column so that if the same data appears in
348 * consecutive rows, then it is not repeated.
350 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
351 * that when one student has made multiple attempts, their name is only printed in the row
352 * for their first attempt.
353 * @param int $column the index of a column.
355 function column_suppress($column) {
356 if (isset($this->column_suppress[$column])) {
357 $this->column_suppress[$column] = true;
362 * Sets the given $column index to the given $classname in $this->column_class.
364 * @param string $classname
367 function column_class($column, $classname) {
368 if (isset($this->column_class[$column])) {
369 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
374 * Sets the given $column index and $property index to the given $value in $this->column_style.
376 * @param string $property
377 * @param mixed $value
380 function column_style($column, $property, $value) {
381 if (isset($this->column_style[$column])) {
382 $this->column_style[$column][$property] = $value;
387 * Sets all columns' $propertys to the given $value in $this->column_style.
388 * @param int $property
389 * @param string $value
392 function column_style_all($property, $value) {
393 foreach (array_keys($this->columns) as $column) {
394 $this->column_style[$column][$property] = $value;
399 * Sets $this->baseurl.
400 * @param moodle_url|string $url the url with params needed to call up this page
402 function define_baseurl($url) {
403 $this->baseurl = new moodle_url($url);
407 * @param array $columns an array of identifying names for columns. If
408 * columns are sorted then column names must correspond to a field in sql.
410 function define_columns($columns) {
411 $this->columns = array();
412 $this->column_style = array();
413 $this->column_class = array();
416 foreach ($columns as $column) {
417 $this->columns[$column] = $colnum++;
418 $this->column_style[$column] = array();
419 $this->column_class[$column] = '';
420 $this->column_suppress[$column] = false;
425 * @param array $headers numerical keyed array of displayed string titles
428 function define_headers($headers) {
429 $this->headers = $headers;
433 * Defines a help icon for the header
435 * Always use this function if you need to create header with sorting and help icon.
437 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
439 public function define_help_for_headers($helpicons) {
440 $this->helpforheaders = $helpicons;
444 * Must be called after table is defined. Use methods above first. Cannot
445 * use functions below till after calling this method.
451 if (empty($this->columns) || empty($this->uniqueid)) {
455 // Load any existing user preferences.
456 if ($this->persistent) {
457 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
458 } else if (isset($SESSION->flextable[$this->uniqueid])) {
459 $this->prefs = $SESSION->flextable[$this->uniqueid];
462 $this->prefs = array(
463 'collapse' => array(),
467 'textsort' => $this->column_textsort,
470 $oldprefs = $this->prefs;
472 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
473 isset($this->columns[$showcol])) {
474 $this->prefs['collapse'][$showcol] = false;
476 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
477 isset($this->columns[$hidecol])) {
478 $this->prefs['collapse'][$hidecol] = true;
479 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
480 unset($this->prefs['sortby'][$hidecol]);
484 // Now, update the column attributes for collapsed columns
485 foreach (array_keys($this->columns) as $column) {
486 if (!empty($this->prefs['collapse'][$column])) {
487 $this->column_style[$column]['width'] = '10px';
491 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
492 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
493 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
494 && isset($this->columns['fullname']))) {
496 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
497 // This key already exists somewhere. Change its sortorder and bring it to the top.
498 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
499 unset($this->prefs['sortby'][$sortcol]);
500 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
502 // Key doesn't exist, so just add it to the beginning of the array, ascending order
503 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
506 // Finally, make sure that no more than $this->maxsortkeys are present into the array
507 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
510 // 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.
511 // This prevents results from being returned in a random order if the only order by column contains equal values.
512 if (!empty($this->sort_default_column)) {
513 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
514 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
515 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
519 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
520 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
521 $this->prefs['i_last'] = $ilast;
524 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
525 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
526 $this->prefs['i_first'] = $ifirst;
529 // Allow user to reset table preferences.
530 if (optional_param($this->request[TABLE_VAR_RESET], 0, PARAM_BOOL) === 1) {
531 $this->prefs = array(
532 'collapse' => array(),
536 'textsort' => $this->column_textsort,
540 // Save user preferences if they have changed.
541 if ($this->prefs != $oldprefs) {
542 if ($this->persistent) {
543 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
545 $SESSION->flextable[$this->uniqueid] = $this->prefs;
550 if (empty($this->baseurl)) {
551 debugging('You should set baseurl when using flexible_table.');
553 $this->baseurl = $PAGE->url;
556 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
559 // Always introduce the "flexible" class for the table if not specified
560 if (empty($this->attributes)) {
561 $this->attributes['class'] = 'flexible';
562 } else if (!isset($this->attributes['class'])) {
563 $this->attributes['class'] = 'flexible';
564 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
565 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
570 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
571 * @param string $uniqueid the identifier for a table.
572 * @return SQL fragment that can be used in an ORDER BY clause.
574 public static function get_sort_for_table($uniqueid) {
576 if (isset($SESSION->flextable[$uniqueid])) {
577 $prefs = $SESSION->flextable[$uniqueid];
578 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
582 if (empty($prefs['sortby'])) {
585 if (empty($prefs['textsort'])) {
586 $prefs['textsort'] = array();
589 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
593 * Prepare an an order by clause from the list of columns to be sorted.
594 * @param array $cols column name => SORT_ASC or SORT_DESC
595 * @return SQL fragment that can be used in an ORDER BY clause.
597 public static function construct_order_by($cols, $textsortcols=array()) {
601 foreach ($cols as $column => $order) {
602 if (in_array($column, $textsortcols)) {
603 $column = $DB->sql_order_by_text($column);
605 if ($order == SORT_ASC) {
606 $bits[] = $column . ' ASC';
608 $bits[] = $column . ' DESC';
612 return implode(', ', $bits);
616 * @return SQL fragment that can be used in an ORDER BY clause.
618 public function get_sql_sort() {
619 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
623 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
624 * @return array column name => SORT_... constant.
626 public function get_sort_columns() {
628 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
631 if (empty($this->prefs['sortby'])) {
635 foreach ($this->prefs['sortby'] as $column => $notused) {
636 if (isset($this->columns[$column])) {
637 continue; // This column is OK.
639 if (in_array($column, get_all_user_name_fields()) &&
640 isset($this->columns['fullname'])) {
641 continue; // This column is OK.
643 // This column is not OK.
644 unset($this->prefs['sortby'][$column]);
647 return $this->prefs['sortby'];
651 * @return int the offset for LIMIT clause of SQL
653 function get_page_start() {
654 if (!$this->use_pages) {
657 return $this->currpage * $this->pagesize;
661 * @return int the pagesize for LIMIT clause of SQL
663 function get_page_size() {
664 if (!$this->use_pages) {
667 return $this->pagesize;
671 * @return string sql to add to where statement.
673 function get_sql_where() {
676 $conditions = array();
679 if (isset($this->columns['fullname'])) {
683 if (!empty($this->prefs['i_first'])) {
684 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
685 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
687 if (!empty($this->prefs['i_last'])) {
688 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
689 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
693 return array(implode(" AND ", $conditions), $params);
697 * Add a row of data to the table. This function takes an array or object with
698 * column names as keys or property names.
700 * It ignores any elements with keys that are not defined as columns. It
701 * puts in empty strings into the row when there is no element in the passed
702 * array corresponding to a column in the table. It puts the row elements in
703 * the proper order (internally row table data is stored by in arrays with
704 * a numerical index corresponding to the column number).
706 * @param object|array $rowwithkeys array keys or object property names are column names,
707 * as defined in call to define_columns.
708 * @param string $classname CSS class name to add to this row's tr tag.
710 function add_data_keyed($rowwithkeys, $classname = '') {
711 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
715 * Add a number of rows to the table at once. And optionally finish output after they have been added.
717 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
718 * object or array is added to table. We expect properties for the row array as would be
719 * passed to add_data_keyed.
720 * @param bool $finish
722 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
723 foreach ($rowstoadd as $row) {
725 $this->add_separator();
727 $this->add_data_keyed($this->format_row($row));
731 $this->finish_output(!$this->is_downloading());
736 * Add a seperator line to table.
738 function add_separator() {
742 $this->add_data(NULL);
746 * This method actually directly echoes the row passed to it now or adds it
747 * to the download. If this is the first row and start_output has not
748 * already been called this method also calls start_output to open the table
749 * or send headers for the downloaded.
750 * Can be used as before. print_html now calls finish_html to close table.
752 * @param array $row a numerically keyed row of data to add to the table.
753 * @param string $classname CSS class name to add to this row's tr tag.
754 * @return bool success.
756 function add_data($row, $classname = '') {
760 if (!$this->started_output) {
761 $this->start_output();
763 if ($this->exportclass!==null) {
765 $this->exportclass->add_seperator();
767 $this->exportclass->add_data($row);
770 $this->print_row($row, $classname);
776 * You should call this to finish outputting the table data after adding
777 * data to the table with add_data or add_data_keyed.
780 function finish_output($closeexportclassdoc = true) {
781 if ($this->exportclass!==null) {
782 $this->exportclass->finish_table();
783 if ($closeexportclassdoc) {
784 $this->exportclass->finish_document();
787 $this->finish_html();
792 * Hook that can be overridden in child classes to wrap a table in a form
793 * for example. Called only when there is data to display and not
796 function wrap_html_start() {
800 * Hook that can be overridden in child classes to wrap a table in a form
801 * for example. Called only when there is data to display and not
804 function wrap_html_finish() {
808 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
809 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
810 * displaying table as html, adding a div wrap, etc.
812 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
814 * @param array|object $row row of data from db used to make one row of the table.
815 * @return array one row for the table, added using add_data_keyed method.
817 function format_row($row) {
818 if (is_array($row)) {
821 $formattedrow = array();
822 foreach (array_keys($this->columns) as $column) {
823 $colmethodname = 'col_'.$column;
824 if (method_exists($this, $colmethodname)) {
825 $formattedcolumn = $this->$colmethodname($row);
827 $formattedcolumn = $this->other_cols($column, $row);
828 if ($formattedcolumn===NULL) {
829 $formattedcolumn = $row->$column;
832 $formattedrow[$column] = $formattedcolumn;
834 return $formattedrow;
838 * Fullname is treated as a special columname in tablelib and should always
839 * be treated the same as the fullname of a user.
840 * @uses $this->useridfield if the userid field is not expected to be id
841 * then you need to override $this->useridfield to point at the correct
842 * field for the user id.
844 * @param object $row the data from the db containing all fields from the
845 * users table necessary to construct the full name of the user in
847 * @return string contents of cell in column 'fullname', for this row.
849 function col_fullname($row) {
852 $name = fullname($row);
853 if ($this->download) {
857 $userid = $row->{$this->useridfield};
858 if ($COURSE->id == SITEID) {
859 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
861 $profileurl = new moodle_url('/user/view.php',
862 array('id' => $userid, 'course' => $COURSE->id));
864 return html_writer::link($profileurl, $name);
868 * You can override this method in a child class. See the description of
869 * build_table which calls this method.
871 function other_cols($column, $row) {
876 * Used from col_* functions when text is to be displayed. Does the
877 * right thing - either converts text to html or strips any html tags
878 * depending on if we are downloading and what is the download type. Params
879 * are the same as format_text function in weblib.php but some default
880 * options are changed.
882 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
883 if (!$this->is_downloading()) {
884 if (is_null($options)) {
885 $options = new stdClass;
887 //some sensible defaults
888 if (!isset($options->para)) {
889 $options->para = false;
891 if (!isset($options->newlines)) {
892 $options->newlines = false;
894 if (!isset($options->smiley)) {
895 $options->smiley = false;
897 if (!isset($options->filter)) {
898 $options->filter = false;
900 return format_text($text, $format, $options);
902 $eci = $this->export_class_instance();
903 return $eci->format_text($text, $format, $options, $courseid);
907 * This method is deprecated although the old api is still supported.
908 * @deprecated 1.9.2 - Jun 2, 2008
910 function print_html() {
914 $this->finish_html();
918 * This function is not part of the public api.
919 * @return string initial of first name we are currently filtering by
921 function get_initial_first() {
922 if (!$this->use_initials) {
926 return $this->prefs['i_first'];
930 * This function is not part of the public api.
931 * @return string initial of last name we are currently filtering by
933 function get_initial_last() {
934 if (!$this->use_initials) {
938 return $this->prefs['i_last'];
942 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
943 * @param array $alpha of letters in the alphabet.
944 * @param string $current the currently selected letter.
945 * @param string $class class name to add to this initial bar.
946 * @param string $title the name to put in front of this initial bar.
947 * @param string $urlvar URL parameter name for this initial.
949 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
950 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
953 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
955 echo html_writer::tag('strong', get_string('all'));
958 foreach ($alpha as $letter) {
959 if ($letter === $current) {
960 echo html_writer::tag('strong', $letter);
962 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
966 echo html_writer::end_tag('div');
970 * This function is not part of the public api.
972 function print_initials_bar() {
973 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
974 && isset($this->columns['fullname'])) {
976 $alpha = explode(',', get_string('alphabet', 'langconfig'));
978 // Bar of first initials
979 if (!empty($this->prefs['i_first'])) {
980 $ifirst = $this->prefs['i_first'];
984 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
985 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
987 // Bar of last initials
988 if (!empty($this->prefs['i_last'])) {
989 $ilast = $this->prefs['i_last'];
993 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
994 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
999 * This function is not part of the public api.
1001 function print_nothing_to_display() {
1004 // Render button to allow user to reset table preferences.
1005 echo $this->render_reset_button();
1007 $this->print_initials_bar();
1009 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1013 * This function is not part of the public api.
1015 function get_row_from_keyed($rowwithkeys) {
1016 if (is_object($rowwithkeys)) {
1017 $rowwithkeys = (array)$rowwithkeys;
1020 foreach (array_keys($this->columns) as $column) {
1021 if (isset($rowwithkeys[$column])) {
1022 $row [] = $rowwithkeys[$column];
1030 * This function is not part of the public api.
1032 function get_download_menu() {
1033 $allclasses= get_declared_classes();
1034 $exportclasses = array();
1035 foreach ($allclasses as $class) {
1037 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
1038 $type = $matches[1];
1039 $exportclasses[$type]= get_string("download$type", 'table');
1042 return $exportclasses;
1046 * This function is not part of the public api.
1048 function download_buttons() {
1049 if ($this->is_downloadable() && !$this->is_downloading()) {
1050 $downloadoptions = $this->get_download_menu();
1052 $downloadelements = new stdClass();
1053 $downloadelements->formatsmenu = html_writer::select($downloadoptions,
1054 'download', $this->defaultdownloadformat, false);
1055 $downloadelements->downloadbutton = '<input type="submit" value="'.
1056 get_string('download').'"/>';
1057 $html = '<form action="'. $this->baseurl .'" method="post">';
1058 $html .= '<div class="mdl-align">';
1059 $html .= html_writer::tag('label', get_string('downloadas', 'table', $downloadelements));
1060 $html .= '</div></form>';
1068 * This function is not part of the public api.
1069 * You don't normally need to call this. It is called automatically when
1070 * needed when you start adding data to the table.
1073 function start_output() {
1074 $this->started_output = true;
1075 if ($this->exportclass!==null) {
1076 $this->exportclass->start_table($this->sheettitle);
1077 $this->exportclass->output_headers($this->headers);
1079 $this->start_html();
1080 $this->print_headers();
1081 echo html_writer::start_tag('tbody');
1086 * This function is not part of the public api.
1088 function print_row($row, $classname = '') {
1089 echo $this->get_row_html($row, $classname);
1093 * Generate html code for the passed row.
1095 * @param array $row Row data.
1096 * @param string $classname classes to add.
1098 * @return string $html html code for the row passed.
1100 public function get_row_html($row, $classname = '') {
1101 static $suppress_lastrow = NULL;
1102 $rowclasses = array();
1105 $rowclasses[] = $classname;
1108 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1111 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1113 // If we have a separator, print it
1114 if ($row === NULL) {
1115 $colcount = count($this->columns);
1116 $html .= html_writer::tag('td', html_writer::tag('div', '',
1117 array('class' => 'tabledivider')), array('colspan' => $colcount));
1120 $colbyindex = array_flip($this->columns);
1121 foreach ($row as $index => $data) {
1122 $column = $colbyindex[$index];
1124 if (empty($this->prefs['collapse'][$column])) {
1125 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1126 $content = ' ';
1131 $content = ' ';
1134 $html .= html_writer::tag('td', $content, array(
1135 'class' => 'cell c' . $index . $this->column_class[$column],
1136 'id' => $rowid . '_c' . $index,
1137 'style' => $this->make_styles_string($this->column_style[$column])));
1141 $html .= html_writer::end_tag('tr');
1143 $suppress_enabled = array_sum($this->column_suppress);
1144 if ($suppress_enabled) {
1145 $suppress_lastrow = $row;
1147 $this->currentrow++;
1152 * This function is not part of the public api.
1154 function finish_html() {
1156 if (!$this->started_output) {
1157 //no data has been added to the table.
1158 $this->print_nothing_to_display();
1161 // Print empty rows to fill the table to the current pagesize.
1162 // This is done so the header aria-controls attributes do not point to
1163 // non existant elements.
1164 $emptyrow = array_fill(0, count($this->columns), '');
1165 while ($this->currentrow < $this->pagesize) {
1166 $this->print_row($emptyrow, 'emptyrow');
1169 echo html_writer::end_tag('tbody');
1170 echo html_writer::end_tag('table');
1171 echo html_writer::end_tag('div');
1172 $this->wrap_html_finish();
1175 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1176 echo $this->download_buttons();
1179 if($this->use_pages) {
1180 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1181 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1182 echo $OUTPUT->render($pagingbar);
1188 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1189 * used by {@link print_headers()}.
1190 * @param string $column the column name, index into various names.
1191 * @param int $index numerical index of the column.
1192 * @return string HTML fragment.
1194 protected function show_hide_link($column, $index) {
1196 // Some headers contain <br /> tags, do not include in title, hence the
1200 for ($i = 0; $i < $this->pagesize; $i++) {
1201 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1204 $ariacontrols = trim($ariacontrols);
1206 if (!empty($this->prefs['collapse'][$column])) {
1207 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1208 'aria-expanded' => 'false',
1209 'aria-controls' => $ariacontrols);
1210 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1211 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1214 } else if ($this->headers[$index] !== NULL) {
1215 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1216 'aria-expanded' => 'true',
1217 'aria-controls' => $ariacontrols);
1218 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1219 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1225 * This function is not part of the public api.
1227 function print_headers() {
1228 global $CFG, $OUTPUT;
1230 echo html_writer::start_tag('thead');
1231 echo html_writer::start_tag('tr');
1232 foreach ($this->columns as $column => $index) {
1235 if ($this->is_collapsible) {
1236 $icon_hide = $this->show_hide_link($column, $index);
1239 $primarysortcolumn = '';
1240 $primarysortorder = '';
1241 if (reset($this->prefs['sortby'])) {
1242 $primarysortcolumn = key($this->prefs['sortby']);
1243 $primarysortorder = current($this->prefs['sortby']);
1249 // Check the full name display for sortable fields.
1250 $nameformat = $CFG->fullnamedisplay;
1251 if ($nameformat == 'language') {
1252 $nameformat = get_string('fullnamedisplay');
1254 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1256 if (!empty($requirednames)) {
1257 if ($this->is_sortable($column)) {
1258 // Done this way for the possibility of more than two sortable full name display fields.
1259 $this->headers[$index] = '';
1260 foreach ($requirednames as $name) {
1261 $sortname = $this->sort_link(get_string($name),
1262 $name, $primarysortcolumn === $name, $primarysortorder);
1263 $this->headers[$index] .= $sortname . ' / ';
1266 if (isset($this->helpforheaders[$index])) {
1267 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1269 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1275 // do nothing, do not display sortable links
1279 if ($this->is_sortable($column)) {
1281 if (isset($this->helpforheaders[$index])) {
1282 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1284 $this->headers[$index] = $this->sort_link($this->headers[$index],
1285 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1289 $attributes = array(
1290 'class' => 'header c' . $index . $this->column_class[$column],
1293 if ($this->headers[$index] === NULL) {
1294 $content = ' ';
1295 } else if (!empty($this->prefs['collapse'][$column])) {
1296 $content = $icon_hide;
1298 if (is_array($this->column_style[$column])) {
1299 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1302 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1303 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1305 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1306 $icon_hide, array('class' => 'commands'));
1308 echo html_writer::tag('th', $content, $attributes);
1311 echo html_writer::end_tag('tr');
1312 echo html_writer::end_tag('thead');
1316 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1317 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1318 * @param int $order SORT_ASC or SORT_DESC
1319 * @return string HTML fragment.
1321 protected function sort_icon($isprimary, $order) {
1328 if ($order == SORT_ASC) {
1329 return html_writer::empty_tag('img',
1330 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1332 return html_writer::empty_tag('img',
1333 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1338 * Generate the correct tool tip for changing the sort order. This is a
1339 * helper method used by {@link sort_link()}.
1340 * @param bool $isprimary whether the is column is the current primary sort column.
1341 * @param int $order SORT_ASC or SORT_DESC
1342 * @return string the correct title.
1344 protected function sort_order_name($isprimary, $order) {
1345 if ($isprimary && $order != SORT_ASC) {
1346 return get_string('desc');
1348 return get_string('asc');
1353 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1354 * @param string $text the text for the link.
1355 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1356 * @param bool $isprimary whether the is column is the current primary sort column.
1357 * @param int $order SORT_ASC or SORT_DESC
1358 * @return string HTML fragment.
1360 protected function sort_link($text, $column, $isprimary, $order) {
1361 return html_writer::link($this->baseurl->out(false,
1362 array($this->request[TABLE_VAR_SORT] => $column)),
1363 $text . get_accesshide(get_string('sortby') . ' ' .
1364 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1365 $this->sort_icon($isprimary, $order);
1369 * This function is not part of the public api.
1371 function start_html() {
1374 // Render button to allow user to reset table preferences.
1375 echo $this->render_reset_button();
1377 // Do we need to print initial bars?
1378 $this->print_initials_bar();
1381 if ($this->use_pages) {
1382 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1383 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1384 echo $OUTPUT->render($pagingbar);
1387 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1388 echo $this->download_buttons();
1391 $this->wrap_html_start();
1392 // Start of main data table
1394 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1395 echo html_writer::start_tag('table', $this->attributes);
1400 * This function is not part of the public api.
1401 * @param array $styles CSS-property => value
1402 * @return string values suitably to go in a style="" attribute in HTML.
1404 function make_styles_string($styles) {
1405 if (empty($styles)) {
1410 foreach($styles as $property => $value) {
1411 $string .= $property . ':' . $value . ';';
1417 * Generate the HTML for the table preferences reset button.
1419 * @return string HTML fragment.
1421 private function render_reset_button() {
1423 // Loop through the user table preferences for a setting.
1424 foreach ($this->prefs as $preference) {
1425 if (!empty($preference)) {
1426 // We have a preference.
1428 // We only need one.
1432 // If no table preferences have been set then don't show the reset button.
1437 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1439 $html = html_writer::start_div('mdl-right');
1440 $html .= html_writer::link($url, get_string('resettable'));
1441 $html .= html_writer::end_div();
1449 * @package moodlecore
1450 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1451 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1453 class table_sql extends flexible_table {
1455 public $countsql = NULL;
1456 public $countparams = NULL;
1458 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1462 * @var array|\Traversable Data fetched from the db.
1464 public $rawdata = NULL;
1467 * @var bool Overriding default for this.
1469 public $is_sortable = true;
1471 * @var bool Overriding default for this.
1473 public $is_collapsible = true;
1476 * @param string $uniqueid a string identifying this table.Used as a key in
1479 function __construct($uniqueid) {
1480 parent::__construct($uniqueid);
1481 // some sensible defaults
1482 $this->set_attribute('cellspacing', '0');
1483 $this->set_attribute('class', 'generaltable generalbox');
1487 * Take the data returned from the db_query and go through all the rows
1488 * processing each col using either col_{columnname} method or other_cols
1489 * method or if other_cols returns NULL then put the data straight into the
1494 function build_table() {
1496 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1499 if (!$this->rawdata) {
1503 foreach ($this->rawdata as $row) {
1504 $formattedrow = $this->format_row($row);
1505 $this->add_data_keyed($formattedrow,
1506 $this->get_row_class($row));
1509 if ($this->rawdata instanceof \core\dml\recordset_walk ||
1510 $this->rawdata instanceof moodle_recordset) {
1511 $this->rawdata->close();
1516 * Get any extra classes names to add to this row in the HTML.
1517 * @param $row array the data for this row.
1518 * @return string added to the class="" attribute of the tr.
1520 function get_row_class($row) {
1525 * This is only needed if you want to use different sql to count rows.
1526 * Used for example when perhaps all db JOINS are not needed when counting
1527 * records. You don't need to call this function the count_sql
1528 * will be generated automatically.
1530 * We need to count rows returned by the db seperately to the query itself
1531 * as we need to know how many pages of data we have to display.
1533 function set_count_sql($sql, array $params = NULL) {
1534 $this->countsql = $sql;
1535 $this->countparams = $params;
1539 * Set the sql to query the db. Query will be :
1540 * SELECT $fields FROM $from WHERE $where
1541 * Of course you can use sub-queries, JOINS etc. by putting them in the
1542 * appropriate clause of the query.
1544 function set_sql($fields, $from, $where, array $params = NULL) {
1545 $this->sql = new stdClass();
1546 $this->sql->fields = $fields;
1547 $this->sql->from = $from;
1548 $this->sql->where = $where;
1549 $this->sql->params = $params;
1553 * Query the db. Store results in the table object for use by build_table.
1555 * @param int $pagesize size of page for paginated displayed table.
1556 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1557 * will only be used if there is a fullname column defined for the table.
1559 function query_db($pagesize, $useinitialsbar=true) {
1561 if (!$this->is_downloading()) {
1562 if ($this->countsql === NULL) {
1563 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1564 $this->countparams = $this->sql->params;
1566 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1567 if ($useinitialsbar && !$this->is_downloading()) {
1568 $this->initialbars($grandtotal > $pagesize);
1571 list($wsql, $wparams) = $this->get_sql_where();
1573 $this->countsql .= ' AND '.$wsql;
1574 $this->countparams = array_merge($this->countparams, $wparams);
1576 $this->sql->where .= ' AND '.$wsql;
1577 $this->sql->params = array_merge($this->sql->params, $wparams);
1579 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1581 $total = $grandtotal;
1584 $this->pagesize($pagesize, $total);
1587 // Fetch the attempts
1588 $sort = $this->get_sql_sort();
1590 $sort = "ORDER BY $sort";
1593 {$this->sql->fields}
1594 FROM {$this->sql->from}
1595 WHERE {$this->sql->where}
1598 if (!$this->is_downloading()) {
1599 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1601 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1606 * Convenience method to call a number of methods for you to display the
1609 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1611 if (!$this->columns) {
1612 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1613 //if columns is not set then define columns as the keys of the rows returned
1615 $this->define_columns(array_keys((array)$onerow));
1616 $this->define_headers(array_keys((array)$onerow));
1619 $this->query_db($pagesize, $useinitialsbar);
1620 $this->build_table();
1621 $this->finish_output();
1627 * @package moodlecore
1628 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1631 class table_default_export_format_parent {
1633 * @var flexible_table or child class reference pointing to table class
1634 * object from which to export data.
1639 * @var bool output started. Keeps track of whether any output has been
1642 var $documentstarted = false;
1643 function table_default_export_format_parent(&$table) {
1644 $this->table =& $table;
1647 function set_table(&$table) {
1648 $this->table =& $table;
1651 function add_data($row) {
1655 function add_seperator() {
1659 function document_started() {
1660 return $this->documentstarted;
1663 * Given text in a variety of format codings, this function returns
1664 * the text as safe HTML or as plain text dependent on what is appropriate
1665 * for the download format. The default removes all tags.
1667 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1668 //use some whitespace to indicate where there was some line spacing.
1669 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1670 return strip_tags($text);
1676 * @package moodlecore
1677 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1680 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1685 * @var object format object - format for normal table cells
1689 * @var object format object - format for header table cells
1694 * should be overriden in child class.
1699 * This method will be overridden in the child class.
1701 function define_workbook() {
1704 function start_document($filename) {
1705 $filename = $filename.'.'.$this->fileextension;
1706 $this->define_workbook();
1708 $this->formatnormal = $this->workbook->add_format();
1709 $this->formatnormal->set_bold(0);
1710 $this->formatheaders = $this->workbook->add_format();
1711 $this->formatheaders->set_bold(1);
1712 $this->formatheaders->set_align('center');
1713 // Sending HTTP headers
1714 $this->workbook->send($filename);
1715 $this->documentstarted = true;
1718 function start_table($sheettitle) {
1719 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1720 $this->currentrow=0;
1723 function output_headers($headers) {
1725 foreach ($headers as $item) {
1726 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1729 $this->currentrow++;
1732 function add_data($row) {
1734 foreach ($row as $item) {
1735 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1738 $this->currentrow++;
1742 function add_seperator() {
1743 $this->currentrow++;
1747 function finish_table() {
1750 function finish_document() {
1751 $this->workbook->close();
1758 * @package moodlecore
1759 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1760 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1762 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1763 var $fileextension = 'xls';
1765 function define_workbook() {
1767 require_once("$CFG->libdir/excellib.class.php");
1768 // Creating a workbook
1769 $this->workbook = new MoodleExcelWorkbook("-");
1776 * @package moodlecore
1777 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1780 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1781 var $fileextension = 'ods';
1782 function define_workbook() {
1784 require_once("$CFG->libdir/odslib.class.php");
1785 // Creating a workbook
1786 $this->workbook = new MoodleODSWorkbook("-");
1792 * @package moodlecore
1793 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1796 class table_text_export_format_parent extends table_default_export_format_parent {
1797 protected $seperator = "tab";
1798 protected $mimetype = 'text/tab-separated-values';
1799 protected $ext = '.txt';
1800 protected $myexporter;
1802 public function __construct() {
1803 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1806 public function start_document($filename) {
1807 $this->filename = $filename;
1808 $this->documentstarted = true;
1809 $this->myexporter->set_filename($filename, $this->ext);
1812 public function start_table($sheettitle) {
1813 //nothing to do here
1816 public function output_headers($headers) {
1817 $this->myexporter->add_data($headers);
1820 public function add_data($row) {
1821 $this->myexporter->add_data($row);
1825 public function finish_table() {
1826 //nothing to do here
1829 public function finish_document() {
1830 $this->myexporter->download_file();
1835 * Format a row of data.
1836 * @param array $data
1838 protected function format_row($data) {
1839 $escapeddata = array();
1840 foreach ($data as $value) {
1841 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1843 return implode($this->seperator, $escapeddata) . "\n";
1849 * @package moodlecore
1850 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1851 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1853 class table_tsv_export_format extends table_text_export_format_parent {
1854 protected $seperator = "tab";
1855 protected $mimetype = 'text/tab-separated-values';
1856 protected $ext = '.txt';
1859 require_once($CFG->libdir . '/csvlib.class.php');
1861 * @package moodlecore
1862 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1863 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1865 class table_csv_export_format extends table_text_export_format_parent {
1866 protected $seperator = "comma";
1867 protected $mimetype = 'text/csv';
1868 protected $ext = '.csv';
1872 * @package moodlecore
1873 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1874 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1876 class table_xhtml_export_format extends table_default_export_format_parent {
1877 function start_document($filename) {
1878 header("Content-Type: application/download\n");
1879 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1880 header("Expires: 0");
1881 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1882 header("Pragma: public");
1885 <?xml version="1.0" encoding="UTF-8"?>
1887 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1888 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1890 <html xmlns="http://www.w3.org/1999/xhtml"
1891 xml:lang="en" lang="en">
1893 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1894 <style type="text/css">/*<![CDATA[*/
1899 th.header, td.header, div.header {
1900 border-color:#DDDDDD;
1901 background-color:lightGrey;
1916 body, table, td, th {
1917 font-family:Arial,Verdana,Helvetica,sans-serif;
1925 border-collapse:collapse;
1941 <title>$filename</title>
1945 $this->documentstarted = true;
1948 function start_table($sheettitle) {
1949 $this->table->sortable(false);
1950 $this->table->collapsible(false);
1951 echo "<h2>{$sheettitle}</h2>";
1952 $this->table->start_html();
1955 function output_headers($headers) {
1956 $this->table->print_headers();
1957 echo html_writer::start_tag('tbody');
1960 function add_data($row) {
1961 $this->table->print_row($row);
1965 function add_seperator() {
1966 $this->table->print_row(NULL);
1970 function finish_table() {
1971 $this->table->finish_html();
1974 function finish_document() {
1975 echo "</body>\n</html>";
1979 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1980 if (is_null($options)) {
1981 $options = new stdClass;
1983 //some sensible defaults
1984 if (!isset($options->para)) {
1985 $options->para = false;
1987 if (!isset($options->newlines)) {
1988 $options->newlines = false;
1990 if (!isset($options->smiley)) {
1991 $options->smiley = false;
1993 if (!isset($options->filter)) {
1994 $options->filter = false;
1996 return format_text($text, $format, $options);