Merge branch 'MDL-41041-master' of git://github.com/FMCorz/moodle
[moodle.git] / lib / tablelib.php
blob4c1e2fc63bdf04fabf0d3be841c2f027c7d75729
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 /**#@-*/
39 /**#@+
40 * Constants that indicate whether the paging bar for the table
41 * appears above or below the table.
43 define('TABLE_P_TOP', 1);
44 define('TABLE_P_BOTTOM', 2);
45 /**#@-*/
48 /**
49 * @package moodlecore
50 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class flexible_table {
55 var $uniqueid = NULL;
56 var $attributes = array();
57 var $headers = array();
58 var $columns = array();
59 var $column_style = array();
60 var $column_class = array();
61 var $column_suppress = array();
62 var $column_nosort = array('userpic');
63 private $column_textsort = array();
64 var $setup = false;
65 var $sess = NULL;
66 var $baseurl = NULL;
67 var $request = array();
69 var $is_collapsible = false;
70 var $is_sortable = false;
71 var $use_pages = false;
72 var $use_initials = false;
74 var $maxsortkeys = 2;
75 var $pagesize = 30;
76 var $currpage = 0;
77 var $totalrows = 0;
78 var $currentrow = 0;
79 var $sort_default_column = NULL;
80 var $sort_default_order = SORT_ASC;
82 /**
83 * Array of positions in which to display download controls.
85 var $showdownloadbuttonsat= array(TABLE_P_TOP);
87 /**
88 * @var string Key of field returned by db query that is the id field of the
89 * user table or equivalent.
91 public $useridfield = 'id';
93 /**
94 * @var string which download plugin to use. Default '' means none - print
95 * html table with paging. Property set by is_downloading which typically
96 * passes in cleaned data from $
98 var $download = '';
101 * @var bool whether data is downloadable from table. Determines whether
102 * to display download buttons. Set by method downloadable().
104 var $downloadable = false;
107 * @var string which download plugin to use. Default '' means none - print
108 * html table with paging.
110 var $defaultdownloadformat = 'csv';
113 * @var bool Has start output been called yet?
115 var $started_output = false;
117 var $exportclass = null;
120 * Constructor
121 * @param int $uniqueid all tables have to have a unique id, this is used
122 * as a key when storing table properties like sort order in the session.
124 function __construct($uniqueid) {
125 $this->uniqueid = $uniqueid;
126 $this->request = array(
127 TABLE_VAR_SORT => 'tsort',
128 TABLE_VAR_HIDE => 'thide',
129 TABLE_VAR_SHOW => 'tshow',
130 TABLE_VAR_IFIRST => 'tifirst',
131 TABLE_VAR_ILAST => 'tilast',
132 TABLE_VAR_PAGE => 'page',
137 * Call this to pass the download type. Use :
138 * $download = optional_param('download', '', PARAM_ALPHA);
139 * To get the download type. We assume that if you call this function with
140 * params that this table's data is downloadable, so we call is_downloadable
141 * for you (even if the param is '', which means no download this time.
142 * Also you can call this method with no params to get the current set
143 * download type.
144 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
145 * @param string $filename filename for downloads without file extension.
146 * @param string $sheettitle title for downloaded data.
147 * @return string download type. One of csv, tsv, xhtml, ods, etc
149 function is_downloading($download = null, $filename='', $sheettitle='') {
150 if ($download!==null) {
151 $this->sheettitle = $sheettitle;
152 $this->is_downloadable(true);
153 $this->download = $download;
154 $this->filename = clean_filename($filename);
155 $this->export_class_instance();
157 return $this->download;
161 * Get, and optionally set, the export class.
162 * @param $exportclass (optional) if passed, set the table to use this export class.
163 * @return table_default_export_format_parent the export class in use (after any set).
165 function export_class_instance($exportclass = null) {
166 if (!is_null($exportclass)) {
167 $this->started_output = true;
168 $this->exportclass = $exportclass;
169 $this->exportclass->table = $this;
170 } else if (is_null($this->exportclass) && !empty($this->download)) {
171 $classname = 'table_'.$this->download.'_export_format';
172 $this->exportclass = new $classname($this);
173 if (!$this->exportclass->document_started()) {
174 $this->exportclass->start_document($this->filename);
177 return $this->exportclass;
181 * Probably don't need to call this directly. Calling is_downloading with a
182 * param automatically sets table as downloadable.
184 * @param bool $downloadable optional param to set whether data from
185 * table is downloadable. If ommitted this function can be used to get
186 * current state of table.
187 * @return bool whether table data is set to be downloadable.
189 function is_downloadable($downloadable = null) {
190 if ($downloadable !== null) {
191 $this->downloadable = $downloadable;
193 return $this->downloadable;
197 * Where to show download buttons.
198 * @param array $showat array of postions in which to show download buttons.
199 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
201 function show_download_buttons_at($showat) {
202 $this->showdownloadbuttonsat = $showat;
206 * Sets the is_sortable variable to the given boolean, sort_default_column to
207 * the given string, and the sort_default_order to the given integer.
208 * @param bool $bool
209 * @param string $defaultcolumn
210 * @param int $defaultorder
211 * @return void
213 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
214 $this->is_sortable = $bool;
215 $this->sort_default_column = $defaultcolumn;
216 $this->sort_default_order = $defaultorder;
220 * Use text sorting functions for this column (required for text columns with Oracle).
221 * @param string column name
223 function text_sorting($column) {
224 $this->column_textsort[] = $column;
228 * Do not sort using this column
229 * @param string column name
231 function no_sorting($column) {
232 $this->column_nosort[] = $column;
236 * Is the column sortable?
237 * @param string column name, null means table
238 * @return bool
240 function is_sortable($column = null) {
241 if (empty($column)) {
242 return $this->is_sortable;
244 if (!$this->is_sortable) {
245 return false;
247 return !in_array($column, $this->column_nosort);
251 * Sets the is_collapsible variable to the given boolean.
252 * @param bool $bool
253 * @return void
255 function collapsible($bool) {
256 $this->is_collapsible = $bool;
260 * Sets the use_pages variable to the given boolean.
261 * @param bool $bool
262 * @return void
264 function pageable($bool) {
265 $this->use_pages = $bool;
269 * Sets the use_initials variable to the given boolean.
270 * @param bool $bool
271 * @return void
273 function initialbars($bool) {
274 $this->use_initials = $bool;
278 * Sets the pagesize variable to the given integer, the totalrows variable
279 * to the given integer, and the use_pages variable to true.
280 * @param int $perpage
281 * @param int $total
282 * @return void
284 function pagesize($perpage, $total) {
285 $this->pagesize = $perpage;
286 $this->totalrows = $total;
287 $this->use_pages = true;
291 * Assigns each given variable in the array to the corresponding index
292 * in the request class variable.
293 * @param array $variables
294 * @return void
296 function set_control_variables($variables) {
297 foreach ($variables as $what => $variable) {
298 if (isset($this->request[$what])) {
299 $this->request[$what] = $variable;
305 * Gives the given $value to the $attribute index of $this->attributes.
306 * @param string $attribute
307 * @param mixed $value
308 * @return void
310 function set_attribute($attribute, $value) {
311 $this->attributes[$attribute] = $value;
315 * What this method does is set the column so that if the same data appears in
316 * consecutive rows, then it is not repeated.
318 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
319 * that when one student has made multiple attempts, their name is only printed in the row
320 * for their first attempt.
321 * @param int $column the index of a column.
323 function column_suppress($column) {
324 if (isset($this->column_suppress[$column])) {
325 $this->column_suppress[$column] = true;
330 * Sets the given $column index to the given $classname in $this->column_class.
331 * @param int $column
332 * @param string $classname
333 * @return void
335 function column_class($column, $classname) {
336 if (isset($this->column_class[$column])) {
337 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
342 * Sets the given $column index and $property index to the given $value in $this->column_style.
343 * @param int $column
344 * @param string $property
345 * @param mixed $value
346 * @return void
348 function column_style($column, $property, $value) {
349 if (isset($this->column_style[$column])) {
350 $this->column_style[$column][$property] = $value;
355 * Sets all columns' $propertys to the given $value in $this->column_style.
356 * @param int $property
357 * @param string $value
358 * @return void
360 function column_style_all($property, $value) {
361 foreach (array_keys($this->columns) as $column) {
362 $this->column_style[$column][$property] = $value;
367 * Sets $this->baseurl.
368 * @param moodle_url|string $url the url with params needed to call up this page
370 function define_baseurl($url) {
371 $this->baseurl = new moodle_url($url);
375 * @param array $columns an array of identifying names for columns. If
376 * columns are sorted then column names must correspond to a field in sql.
378 function define_columns($columns) {
379 $this->columns = array();
380 $this->column_style = array();
381 $this->column_class = array();
382 $colnum = 0;
384 foreach ($columns as $column) {
385 $this->columns[$column] = $colnum++;
386 $this->column_style[$column] = array();
387 $this->column_class[$column] = '';
388 $this->column_suppress[$column] = false;
393 * @param array $headers numerical keyed array of displayed string titles
394 * for each column.
396 function define_headers($headers) {
397 $this->headers = $headers;
401 * Must be called after table is defined. Use methods above first. Cannot
402 * use functions below till after calling this method.
403 * @return type?
405 function setup() {
406 global $SESSION, $CFG;
408 if (empty($this->columns) || empty($this->uniqueid)) {
409 return false;
412 if (!isset($SESSION->flextable)) {
413 $SESSION->flextable = array();
416 if (!isset($SESSION->flextable[$this->uniqueid])) {
417 $SESSION->flextable[$this->uniqueid] = new stdClass;
418 $SESSION->flextable[$this->uniqueid]->uniqueid = $this->uniqueid;
419 $SESSION->flextable[$this->uniqueid]->collapse = array();
420 $SESSION->flextable[$this->uniqueid]->sortby = array();
421 $SESSION->flextable[$this->uniqueid]->i_first = '';
422 $SESSION->flextable[$this->uniqueid]->i_last = '';
423 $SESSION->flextable[$this->uniqueid]->textsort = $this->column_textsort;
426 $this->sess = &$SESSION->flextable[$this->uniqueid];
428 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
429 isset($this->columns[$showcol])) {
430 $this->sess->collapse[$showcol] = false;
432 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
433 isset($this->columns[$hidecol])) {
434 $this->sess->collapse[$hidecol] = true;
435 if (array_key_exists($hidecol, $this->sess->sortby)) {
436 unset($this->sess->sortby[$hidecol]);
440 // Now, update the column attributes for collapsed columns
441 foreach (array_keys($this->columns) as $column) {
442 if (!empty($this->sess->collapse[$column])) {
443 $this->column_style[$column]['width'] = '10px';
447 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
448 $this->is_sortable($sortcol) && empty($this->sess->collapse[$sortcol]) &&
449 (isset($this->columns[$sortcol]) || in_array($sortcol, array('firstname', 'lastname')) && isset($this->columns['fullname']))) {
451 if (array_key_exists($sortcol, $this->sess->sortby)) {
452 // This key already exists somewhere. Change its sortorder and bring it to the top.
453 $sortorder = $this->sess->sortby[$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
454 unset($this->sess->sortby[$sortcol]);
455 $this->sess->sortby = array_merge(array($sortcol => $sortorder), $this->sess->sortby);
456 } else {
457 // Key doesn't exist, so just add it to the beginning of the array, ascending order
458 $this->sess->sortby = array_merge(array($sortcol => SORT_ASC), $this->sess->sortby);
461 // Finally, make sure that no more than $this->maxsortkeys are present into the array
462 $this->sess->sortby = array_slice($this->sess->sortby, 0, $this->maxsortkeys);
465 // 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.
466 // This prevents results from being returned in a random order if the only order by column contains equal values.
467 if (!empty($this->sort_default_column)) {
468 if (!array_key_exists($this->sort_default_column, $this->sess->sortby)) {
469 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
470 $this->sess->sortby = array_merge($this->sess->sortby, $defaultsort);
474 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
475 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
476 $this->sess->i_last = $ilast;
479 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
480 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
481 $this->sess->i_first = $ifirst;
484 if (empty($this->baseurl)) {
485 debugging('You should set baseurl when using flexible_table.');
486 global $PAGE;
487 $this->baseurl = $PAGE->url;
490 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
491 $this->setup = true;
493 // Always introduce the "flexible" class for the table if not specified
494 if (empty($this->attributes)) {
495 $this->attributes['class'] = 'flexible';
496 } else if (!isset($this->attributes['class'])) {
497 $this->attributes['class'] = 'flexible';
498 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
499 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
504 * Get the order by clause from the session, for the table with id $uniqueid.
505 * @param string $uniqueid the identifier for a table.
506 * @return SQL fragment that can be used in an ORDER BY clause.
508 public static function get_sort_for_table($uniqueid) {
509 global $SESSION;
510 if (empty($SESSION->flextable[$uniqueid])) {
511 return '';
514 $sess = &$SESSION->flextable[$uniqueid];
515 if (empty($sess->sortby)) {
516 return '';
518 if (empty($sess->textsort)) {
519 $sess->textsort = array();
522 return self::construct_order_by($sess->sortby, $sess->textsort);
526 * Prepare an an order by clause from the list of columns to be sorted.
527 * @param array $cols column name => SORT_ASC or SORT_DESC
528 * @return SQL fragment that can be used in an ORDER BY clause.
530 public static function construct_order_by($cols, $textsortcols=array()) {
531 global $DB;
532 $bits = array();
534 foreach ($cols as $column => $order) {
535 if (in_array($column, $textsortcols)) {
536 $column = $DB->sql_order_by_text($column);
538 if ($order == SORT_ASC) {
539 $bits[] = $column . ' ASC';
540 } else {
541 $bits[] = $column . ' DESC';
545 return implode(', ', $bits);
549 * @return SQL fragment that can be used in an ORDER BY clause.
551 public function get_sql_sort() {
552 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
556 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
557 * @return array column name => SORT_... constant.
559 public function get_sort_columns() {
560 if (!$this->setup) {
561 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
564 if (empty($this->sess->sortby)) {
565 return array();
568 foreach ($this->sess->sortby as $column => $notused) {
569 if (isset($this->columns[$column])) {
570 continue; // This column is OK.
572 if (in_array($column, array('firstname', 'lastname')) &&
573 isset($this->columns['fullname'])) {
574 continue; // This column is OK.
576 // This column is not OK.
577 unset($this->sess->sortby[$column]);
580 return $this->sess->sortby;
584 * @return int the offset for LIMIT clause of SQL
586 function get_page_start() {
587 if (!$this->use_pages) {
588 return '';
590 return $this->currpage * $this->pagesize;
594 * @return int the pagesize for LIMIT clause of SQL
596 function get_page_size() {
597 if (!$this->use_pages) {
598 return '';
600 return $this->pagesize;
604 * @return string sql to add to where statement.
606 function get_sql_where() {
607 global $DB;
609 $conditions = array();
610 $params = array();
612 if (isset($this->columns['fullname'])) {
613 static $i = 0;
614 $i++;
616 if (!empty($this->sess->i_first)) {
617 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
618 $params['ifirstc'.$i] = $this->sess->i_first.'%';
620 if (!empty($this->sess->i_last)) {
621 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
622 $params['ilastc'.$i] = $this->sess->i_last.'%';
626 return array(implode(" AND ", $conditions), $params);
630 * Add a row of data to the table. This function takes an array with
631 * column names as keys.
632 * It ignores any elements with keys that are not defined as columns. It
633 * puts in empty strings into the row when there is no element in the passed
634 * array corresponding to a column in the table. It puts the row elements in
635 * the proper order.
636 * @param $rowwithkeys array
637 * @param string $classname CSS class name to add to this row's tr tag.
639 function add_data_keyed($rowwithkeys, $classname = '') {
640 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
644 * Add a seperator line to table.
646 function add_separator() {
647 if (!$this->setup) {
648 return false;
650 $this->add_data(NULL);
654 * This method actually directly echoes the row passed to it now or adds it
655 * to the download. If this is the first row and start_output has not
656 * already been called this method also calls start_output to open the table
657 * or send headers for the downloaded.
658 * Can be used as before. print_html now calls finish_html to close table.
660 * @param array $row a numerically keyed row of data to add to the table.
661 * @param string $classname CSS class name to add to this row's tr tag.
662 * @return bool success.
664 function add_data($row, $classname = '') {
665 if (!$this->setup) {
666 return false;
668 if (!$this->started_output) {
669 $this->start_output();
671 if ($this->exportclass!==null) {
672 if ($row === null) {
673 $this->exportclass->add_seperator();
674 } else {
675 $this->exportclass->add_data($row);
677 } else {
678 $this->print_row($row, $classname);
680 return true;
684 * You should call this to finish outputting the table data after adding
685 * data to the table with add_data or add_data_keyed.
688 function finish_output($closeexportclassdoc = true) {
689 if ($this->exportclass!==null) {
690 $this->exportclass->finish_table();
691 if ($closeexportclassdoc) {
692 $this->exportclass->finish_document();
694 } else {
695 $this->finish_html();
700 * Hook that can be overridden in child classes to wrap a table in a form
701 * for example. Called only when there is data to display and not
702 * downloading.
704 function wrap_html_start() {
708 * Hook that can be overridden in child classes to wrap a table in a form
709 * for example. Called only when there is data to display and not
710 * downloading.
712 function wrap_html_finish() {
717 * @param array $row row of data from db used to make one row of the table.
718 * @return array one row for the table, added using add_data_keyed method.
720 function format_row($row) {
721 $formattedrow = array();
722 foreach (array_keys($this->columns) as $column) {
723 $colmethodname = 'col_'.$column;
724 if (method_exists($this, $colmethodname)) {
725 $formattedcolumn = $this->$colmethodname($row);
726 } else {
727 $formattedcolumn = $this->other_cols($column, $row);
728 if ($formattedcolumn===NULL) {
729 $formattedcolumn = $row->$column;
732 $formattedrow[$column] = $formattedcolumn;
734 return $formattedrow;
738 * Fullname is treated as a special columname in tablelib and should always
739 * be treated the same as the fullname of a user.
740 * @uses $this->useridfield if the userid field is not expected to be id
741 * then you need to override $this->useridfield to point at the correct
742 * field for the user id.
745 function col_fullname($row) {
746 global $COURSE, $CFG;
748 $name = fullname($row);
749 if ($this->download) {
750 return $name;
753 $userid = $row->{$this->useridfield};
754 if ($COURSE->id == SITEID) {
755 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
756 } else {
757 $profileurl = new moodle_url('/user/view.php',
758 array('id' => $userid, 'course' => $COURSE->id));
760 return html_writer::link($profileurl, $name);
764 * You can override this method in a child class. See the description of
765 * build_table which calls this method.
767 function other_cols($column, $row) {
768 return NULL;
772 * Used from col_* functions when text is to be displayed. Does the
773 * right thing - either converts text to html or strips any html tags
774 * depending on if we are downloading and what is the download type. Params
775 * are the same as format_text function in weblib.php but some default
776 * options are changed.
778 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
779 if (!$this->is_downloading()) {
780 if (is_null($options)) {
781 $options = new stdClass;
783 //some sensible defaults
784 if (!isset($options->para)) {
785 $options->para = false;
787 if (!isset($options->newlines)) {
788 $options->newlines = false;
790 if (!isset($options->smiley)) {
791 $options->smiley = false;
793 if (!isset($options->filter)) {
794 $options->filter = false;
796 return format_text($text, $format, $options);
797 } else {
798 $eci =& $this->export_class_instance();
799 return $eci->format_text($text, $format, $options, $courseid);
803 * This method is deprecated although the old api is still supported.
804 * @deprecated 1.9.2 - Jun 2, 2008
806 function print_html() {
807 if (!$this->setup) {
808 return false;
810 $this->finish_html();
814 * This function is not part of the public api.
815 * @return string initial of first name we are currently filtering by
817 function get_initial_first() {
818 if (!$this->use_initials) {
819 return NULL;
822 return $this->sess->i_first;
826 * This function is not part of the public api.
827 * @return string initial of last name we are currently filtering by
829 function get_initial_last() {
830 if (!$this->use_initials) {
831 return NULL;
834 return $this->sess->i_last;
838 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
839 * @param array $alpha of letters in the alphabet.
840 * @param string $current the currently selected letter.
841 * @param string $class class name to add to this initial bar.
842 * @param string $title the name to put in front of this initial bar.
843 * @param string $urlvar URL parameter name for this initial.
845 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
846 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
847 $title . ' : ';
848 if ($current) {
849 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
850 } else {
851 echo html_writer::tag('strong', get_string('all'));
854 foreach ($alpha as $letter) {
855 if ($letter === $current) {
856 echo html_writer::tag('strong', $letter);
857 } else {
858 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
862 echo html_writer::end_tag('div');
866 * This function is not part of the public api.
868 function print_initials_bar() {
869 if ((!empty($this->sess->i_last) || !empty($this->sess->i_first) ||$this->use_initials)
870 && isset($this->columns['fullname'])) {
872 $alpha = explode(',', get_string('alphabet', 'langconfig'));
874 // Bar of first initials
875 if (!empty($this->sess->i_first)) {
876 $ifirst = $this->sess->i_first;
877 } else {
878 $ifirst = '';
880 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
881 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
883 // Bar of last initials
884 if (!empty($this->sess->i_last)) {
885 $ilast = $this->sess->i_last;
886 } else {
887 $ilast = '';
889 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
890 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
895 * This function is not part of the public api.
897 function print_nothing_to_display() {
898 global $OUTPUT;
899 $this->print_initials_bar();
901 echo $OUTPUT->heading(get_string('nothingtodisplay'));
905 * This function is not part of the public api.
907 function get_row_from_keyed($rowwithkeys) {
908 if (is_object($rowwithkeys)) {
909 $rowwithkeys = (array)$rowwithkeys;
911 $row = array();
912 foreach (array_keys($this->columns) as $column) {
913 if (isset($rowwithkeys[$column])) {
914 $row [] = $rowwithkeys[$column];
915 } else {
916 $row[] ='';
919 return $row;
922 * This function is not part of the public api.
924 function get_download_menu() {
925 $allclasses= get_declared_classes();
926 $exportclasses = array();
927 foreach ($allclasses as $class) {
928 $matches = array();
929 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
930 $type = $matches[1];
931 $exportclasses[$type]= get_string("download$type", 'table');
934 return $exportclasses;
938 * This function is not part of the public api.
940 function download_buttons() {
941 if ($this->is_downloadable() && !$this->is_downloading()) {
942 $downloadoptions = $this->get_download_menu();
944 $downloadelements = new stdClass();
945 $downloadelements->formatsmenu = html_writer::select($downloadoptions,
946 'download', $this->defaultdownloadformat, false);
947 $downloadelements->downloadbutton = '<input type="submit" value="'.
948 get_string('download').'"/>';
949 $html = '<form action="'. $this->baseurl .'" method="post">';
950 $html .= '<div class="mdl-align">';
951 $html .= html_writer::tag('label', get_string('downloadas', 'table', $downloadelements));
952 $html .= '</div></form>';
954 return $html;
955 } else {
956 return '';
960 * This function is not part of the public api.
961 * You don't normally need to call this. It is called automatically when
962 * needed when you start adding data to the table.
965 function start_output() {
966 $this->started_output = true;
967 if ($this->exportclass!==null) {
968 $this->exportclass->start_table($this->sheettitle);
969 $this->exportclass->output_headers($this->headers);
970 } else {
971 $this->start_html();
972 $this->print_headers();
973 echo html_writer::start_tag('tbody');
978 * This function is not part of the public api.
980 function print_row($row, $classname = '') {
981 static $suppress_lastrow = NULL;
982 $oddeven = $this->currentrow % 2;
983 $rowclasses = array('r' . $oddeven);
985 if ($classname) {
986 $rowclasses[] = $classname;
989 $rowid = $this->uniqueid . '_r' . $this->currentrow;
991 echo html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
993 // If we have a separator, print it
994 if ($row === NULL) {
995 $colcount = count($this->columns);
996 echo html_writer::tag('td', html_writer::tag('div', '',
997 array('class' => 'tabledivider')), array('colspan' => $colcount));
999 } else {
1000 $colbyindex = array_flip($this->columns);
1001 foreach ($row as $index => $data) {
1002 $column = $colbyindex[$index];
1004 if (empty($this->sess->collapse[$column])) {
1005 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1006 $content = '&nbsp;';
1007 } else {
1008 $content = $data;
1010 } else {
1011 $content = '&nbsp;';
1014 echo html_writer::tag('td', $content, array(
1015 'class' => 'cell c' . $index . $this->column_class[$column],
1016 'id' => $rowid . '_c' . $index,
1017 'style' => $this->make_styles_string($this->column_style[$column])));
1021 echo html_writer::end_tag('tr');
1023 $suppress_enabled = array_sum($this->column_suppress);
1024 if ($suppress_enabled) {
1025 $suppress_lastrow = $row;
1027 $this->currentrow++;
1031 * This function is not part of the public api.
1033 function finish_html() {
1034 global $OUTPUT;
1035 if (!$this->started_output) {
1036 //no data has been added to the table.
1037 $this->print_nothing_to_display();
1039 } else {
1040 // Print empty rows to fill the table to the current pagesize.
1041 // This is done so the header aria-controls attributes do not point to
1042 // non existant elements.
1043 $emptyrow = array_fill(0, count($this->columns), '');
1044 while ($this->currentrow < $this->pagesize) {
1045 $this->print_row($emptyrow, 'emptyrow');
1048 echo html_writer::end_tag('tbody');
1049 echo html_writer::end_tag('table');
1050 echo html_writer::end_tag('div');
1051 $this->wrap_html_finish();
1053 // Paging bar
1054 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1055 echo $this->download_buttons();
1058 if($this->use_pages) {
1059 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1060 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1061 echo $OUTPUT->render($pagingbar);
1067 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1068 * used by {@link print_headers()}.
1069 * @param string $column the column name, index into various names.
1070 * @param int $index numerical index of the column.
1071 * @return string HTML fragment.
1073 protected function show_hide_link($column, $index) {
1074 global $OUTPUT;
1075 // Some headers contain <br /> tags, do not include in title, hence the
1076 // strip tags.
1078 $ariacontrols = '';
1079 for ($i = 0; $i < $this->pagesize; $i++) {
1080 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1083 $ariacontrols = trim($ariacontrols);
1085 if (!empty($this->sess->collapse[$column])) {
1086 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1087 'aria-expanded' => 'false',
1088 'aria-controls' => $ariacontrols);
1089 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1090 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1091 $linkattributes);
1093 } else if ($this->headers[$index] !== NULL) {
1094 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1095 'aria-expanded' => 'true',
1096 'aria-controls' => $ariacontrols);
1097 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1098 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1099 $linkattributes);
1104 * This function is not part of the public api.
1106 function print_headers() {
1107 global $CFG, $OUTPUT;
1109 echo html_writer::start_tag('thead');
1110 echo html_writer::start_tag('tr');
1111 foreach ($this->columns as $column => $index) {
1113 $icon_hide = '';
1114 if ($this->is_collapsible) {
1115 $icon_hide = $this->show_hide_link($column, $index);
1118 $primary_sort_column = '';
1119 $primary_sort_order = '';
1120 if (reset($this->sess->sortby)) {
1121 $primary_sort_column = key($this->sess->sortby);
1122 $primary_sort_order = current($this->sess->sortby);
1125 switch ($column) {
1127 case 'fullname':
1128 // Check the full name display for sortable fields.
1129 $nameformat = $CFG->fullnamedisplay;
1130 if ($nameformat == 'language') {
1131 $nameformat = get_string('fullnamedisplay');
1133 $requirednames = order_in_string(array('firstname', 'lastname'), $nameformat);
1135 if (!empty($requirednames)) {
1136 if ($this->is_sortable($column)) {
1137 // Done this way for the possibility of more than two sortable full name display fields.
1138 $this->headers[$index] = '';
1139 foreach ($requirednames as $name) {
1140 $sortname = $this->sort_link(get_string($name),
1141 $name, $primary_sort_column === $name, $primary_sort_order);
1142 $this->headers[$index] .= $sortname . ' / ';
1144 $this->headers[$index] = substr($this->headers[$index], 0, -3);
1147 break;
1149 case 'userpic':
1150 // do nothing, do not display sortable links
1151 break;
1153 default:
1154 if ($this->is_sortable($column)) {
1155 $this->headers[$index] = $this->sort_link($this->headers[$index],
1156 $column, $primary_sort_column == $column, $primary_sort_order);
1160 $attributes = array(
1161 'class' => 'header c' . $index . $this->column_class[$column],
1162 'scope' => 'col',
1164 if ($this->headers[$index] === NULL) {
1165 $content = '&nbsp;';
1166 } else if (!empty($this->sess->collapse[$column])) {
1167 $content = $icon_hide;
1168 } else {
1169 if (is_array($this->column_style[$column])) {
1170 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1172 $content = $this->headers[$index] . html_writer::tag('div',
1173 $icon_hide, array('class' => 'commands'));
1175 echo html_writer::tag('th', $content, $attributes);
1178 echo html_writer::end_tag('tr');
1179 echo html_writer::end_tag('thead');
1183 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1184 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1185 * @param int $order SORT_ASC or SORT_DESC
1186 * @return string HTML fragment.
1188 protected function sort_icon($isprimary, $order) {
1189 global $OUTPUT;
1191 if (!$isprimary) {
1192 return '';
1195 if ($order == SORT_ASC) {
1196 return html_writer::empty_tag('img',
1197 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1198 } else {
1199 return html_writer::empty_tag('img',
1200 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1205 * Generate the correct tool tip for changing the sort order. This is a
1206 * helper method used by {@link sort_link()}.
1207 * @param bool $isprimary whether the is column is the current primary sort column.
1208 * @param int $order SORT_ASC or SORT_DESC
1209 * @return string the correct title.
1211 protected function sort_order_name($isprimary, $order) {
1212 if ($isprimary && $order != SORT_ASC) {
1213 return get_string('desc');
1214 } else {
1215 return get_string('asc');
1220 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1221 * @param string $text the text for the link.
1222 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1223 * @param bool $isprimary whether the is column is the current primary sort column.
1224 * @param int $order SORT_ASC or SORT_DESC
1225 * @return string HTML fragment.
1227 protected function sort_link($text, $column, $isprimary, $order) {
1228 return html_writer::link($this->baseurl->out(false,
1229 array($this->request[TABLE_VAR_SORT] => $column)),
1230 $text . get_accesshide(get_string('sortby') . ' ' .
1231 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1232 $this->sort_icon($isprimary, $order);
1236 * This function is not part of the public api.
1238 function start_html() {
1239 global $OUTPUT;
1240 // Do we need to print initial bars?
1241 $this->print_initials_bar();
1243 // Paging bar
1244 if ($this->use_pages) {
1245 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1246 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1247 echo $OUTPUT->render($pagingbar);
1250 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1251 echo $this->download_buttons();
1254 $this->wrap_html_start();
1255 // Start of main data table
1257 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1258 echo html_writer::start_tag('table', $this->attributes);
1263 * This function is not part of the public api.
1264 * @param array $styles CSS-property => value
1265 * @return string values suitably to go in a style="" attribute in HTML.
1267 function make_styles_string($styles) {
1268 if (empty($styles)) {
1269 return null;
1272 $string = '';
1273 foreach($styles as $property => $value) {
1274 $string .= $property . ':' . $value . ';';
1276 return $string;
1282 * @package moodlecore
1283 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1284 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1286 class table_sql extends flexible_table {
1288 public $countsql = NULL;
1289 public $countparams = NULL;
1291 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1293 public $sql = NULL;
1295 * @var array Data fetched from the db.
1297 public $rawdata = NULL;
1300 * @var bool Overriding default for this.
1302 public $is_sortable = true;
1304 * @var bool Overriding default for this.
1306 public $is_collapsible = true;
1309 * @param string $uniqueid a string identifying this table.Used as a key in
1310 * session vars.
1312 function __construct($uniqueid) {
1313 parent::__construct($uniqueid);
1314 // some sensible defaults
1315 $this->set_attribute('cellspacing', '0');
1316 $this->set_attribute('class', 'generaltable generalbox');
1320 * Take the data returned from the db_query and go through all the rows
1321 * processing each col using either col_{columnname} method or other_cols
1322 * method or if other_cols returns NULL then put the data straight into the
1323 * table.
1325 function build_table() {
1326 if ($this->rawdata) {
1327 foreach ($this->rawdata as $row) {
1328 $formattedrow = $this->format_row($row);
1329 $this->add_data_keyed($formattedrow,
1330 $this->get_row_class($row));
1336 * Get any extra classes names to add to this row in the HTML.
1337 * @param $row array the data for this row.
1338 * @return string added to the class="" attribute of the tr.
1340 function get_row_class($row) {
1341 return '';
1345 * This is only needed if you want to use different sql to count rows.
1346 * Used for example when perhaps all db JOINS are not needed when counting
1347 * records. You don't need to call this function the count_sql
1348 * will be generated automatically.
1350 * We need to count rows returned by the db seperately to the query itself
1351 * as we need to know how many pages of data we have to display.
1353 function set_count_sql($sql, array $params = NULL) {
1354 $this->countsql = $sql;
1355 $this->countparams = $params;
1359 * Set the sql to query the db. Query will be :
1360 * SELECT $fields FROM $from WHERE $where
1361 * Of course you can use sub-queries, JOINS etc. by putting them in the
1362 * appropriate clause of the query.
1364 function set_sql($fields, $from, $where, array $params = NULL) {
1365 $this->sql = new stdClass();
1366 $this->sql->fields = $fields;
1367 $this->sql->from = $from;
1368 $this->sql->where = $where;
1369 $this->sql->params = $params;
1373 * Query the db. Store results in the table object for use by build_table.
1375 * @param int $pagesize size of page for paginated displayed table.
1376 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1377 * will only be used if there is a fullname column defined for the table.
1379 function query_db($pagesize, $useinitialsbar=true) {
1380 global $DB;
1381 if (!$this->is_downloading()) {
1382 if ($this->countsql === NULL) {
1383 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1384 $this->countparams = $this->sql->params;
1386 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1387 if ($useinitialsbar && !$this->is_downloading()) {
1388 $this->initialbars($grandtotal > $pagesize);
1391 list($wsql, $wparams) = $this->get_sql_where();
1392 if ($wsql) {
1393 $this->countsql .= ' AND '.$wsql;
1394 $this->countparams = array_merge($this->countparams, $wparams);
1396 $this->sql->where .= ' AND '.$wsql;
1397 $this->sql->params = array_merge($this->sql->params, $wparams);
1399 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1400 } else {
1401 $total = $grandtotal;
1404 $this->pagesize($pagesize, $total);
1407 // Fetch the attempts
1408 $sort = $this->get_sql_sort();
1409 if ($sort) {
1410 $sort = "ORDER BY $sort";
1412 $sql = "SELECT
1413 {$this->sql->fields}
1414 FROM {$this->sql->from}
1415 WHERE {$this->sql->where}
1416 {$sort}";
1418 if (!$this->is_downloading()) {
1419 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1420 } else {
1421 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1426 * Convenience method to call a number of methods for you to display the
1427 * table.
1429 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1430 global $DB;
1431 if (!$this->columns) {
1432 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1433 //if columns is not set then define columns as the keys of the rows returned
1434 //from the db.
1435 $this->define_columns(array_keys((array)$onerow));
1436 $this->define_headers(array_keys((array)$onerow));
1438 $this->setup();
1439 $this->query_db($pagesize, $useinitialsbar);
1440 $this->build_table();
1441 $this->finish_output();
1447 * @package moodlecore
1448 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1451 class table_default_export_format_parent {
1453 * @var flexible_table or child class reference pointing to table class
1454 * object from which to export data.
1456 var $table;
1459 * @var bool output started. Keeps track of whether any output has been
1460 * started yet.
1462 var $documentstarted = false;
1463 function table_default_export_format_parent(&$table) {
1464 $this->table =& $table;
1467 function set_table(&$table) {
1468 $this->table =& $table;
1471 function add_data($row) {
1472 return false;
1475 function add_seperator() {
1476 return false;
1479 function document_started() {
1480 return $this->documentstarted;
1483 * Given text in a variety of format codings, this function returns
1484 * the text as safe HTML or as plain text dependent on what is appropriate
1485 * for the download format. The default removes all tags.
1487 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1488 //use some whitespace to indicate where there was some line spacing.
1489 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1490 return strip_tags($text);
1496 * @package moodlecore
1497 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1500 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1501 var $currentrow;
1502 var $workbook;
1503 var $worksheet;
1505 * @var object format object - format for normal table cells
1507 var $formatnormal;
1509 * @var object format object - format for header table cells
1511 var $formatheaders;
1514 * should be overriden in child class.
1516 var $fileextension;
1519 * This method will be overridden in the child class.
1521 function define_workbook() {
1524 function start_document($filename) {
1525 $filename = $filename.'.'.$this->fileextension;
1526 $this->define_workbook();
1527 // format types
1528 $this->formatnormal =& $this->workbook->add_format();
1529 $this->formatnormal->set_bold(0);
1530 $this->formatheaders =& $this->workbook->add_format();
1531 $this->formatheaders->set_bold(1);
1532 $this->formatheaders->set_align('center');
1533 // Sending HTTP headers
1534 $this->workbook->send($filename);
1535 $this->documentstarted = true;
1538 function start_table($sheettitle) {
1539 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1540 $this->currentrow=0;
1543 function output_headers($headers) {
1544 $colnum = 0;
1545 foreach ($headers as $item) {
1546 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1547 $colnum++;
1549 $this->currentrow++;
1552 function add_data($row) {
1553 $colnum = 0;
1554 foreach ($row as $item) {
1555 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1556 $colnum++;
1558 $this->currentrow++;
1559 return true;
1562 function add_seperator() {
1563 $this->currentrow++;
1564 return true;
1567 function finish_table() {
1570 function finish_document() {
1571 $this->workbook->close();
1572 exit;
1578 * @package moodlecore
1579 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1582 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1583 var $fileextension = 'xls';
1585 function define_workbook() {
1586 global $CFG;
1587 require_once("$CFG->libdir/excellib.class.php");
1588 // Creating a workbook
1589 $this->workbook = new MoodleExcelWorkbook("-");
1596 * @package moodlecore
1597 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1600 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1601 var $fileextension = 'ods';
1602 function define_workbook() {
1603 global $CFG;
1604 require_once("$CFG->libdir/odslib.class.php");
1605 // Creating a workbook
1606 $this->workbook = new MoodleODSWorkbook("-");
1612 * @package moodlecore
1613 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1616 class table_text_export_format_parent extends table_default_export_format_parent {
1617 protected $seperator = "tab";
1618 protected $mimetype = 'text/tab-separated-values';
1619 protected $ext = '.txt';
1620 protected $myexporter;
1622 public function __construct() {
1623 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1626 public function start_document($filename) {
1627 $this->filename = $filename;
1628 $this->documentstarted = true;
1629 $this->myexporter->set_filename($filename, $this->ext);
1632 public function start_table($sheettitle) {
1633 //nothing to do here
1636 public function output_headers($headers) {
1637 $this->myexporter->add_data($headers);
1640 public function add_data($row) {
1641 $this->myexporter->add_data($row);
1642 return true;
1645 public function finish_table() {
1646 //nothing to do here
1649 public function finish_document() {
1650 $this->myexporter->download_file();
1651 exit;
1655 * Format a row of data.
1656 * @param array $data
1658 protected function format_row($data) {
1659 $escapeddata = array();
1660 foreach ($data as $value) {
1661 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1663 return implode($this->seperator, $escapeddata) . "\n";
1669 * @package moodlecore
1670 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1671 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1673 class table_tsv_export_format extends table_text_export_format_parent {
1674 protected $seperator = "tab";
1675 protected $mimetype = 'text/tab-separated-values';
1676 protected $ext = '.txt';
1679 require_once($CFG->libdir . '/csvlib.class.php');
1681 * @package moodlecore
1682 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1685 class table_csv_export_format extends table_text_export_format_parent {
1686 protected $seperator = "comma";
1687 protected $mimetype = 'text/csv';
1688 protected $ext = '.csv';
1692 * @package moodlecore
1693 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1696 class table_xhtml_export_format extends table_default_export_format_parent {
1697 function start_document($filename) {
1698 header("Content-Type: application/download\n");
1699 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1700 header("Expires: 0");
1701 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1702 header("Pragma: public");
1703 //html headers
1704 echo <<<EOF
1705 <?xml version="1.0" encoding="UTF-8"?>
1706 <!DOCTYPE html
1707 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1708 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1710 <html xmlns="http://www.w3.org/1999/xhtml"
1711 xml:lang="en" lang="en">
1712 <head>
1713 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1714 <style type="text/css">/*<![CDATA[*/
1716 .flexible th {
1717 white-space:normal;
1719 th.header, td.header, div.header {
1720 border-color:#DDDDDD;
1721 background-color:lightGrey;
1723 .flexible th {
1724 white-space:nowrap;
1726 th {
1727 font-weight:bold;
1730 .generaltable {
1731 border-style:solid;
1733 .generalbox {
1734 border-style:solid;
1736 body, table, td, th {
1737 font-family:Arial,Verdana,Helvetica,sans-serif;
1738 font-size:100%;
1740 td {
1741 border-style:solid;
1742 border-width:1pt;
1744 table {
1745 border-collapse:collapse;
1746 border-spacing:0pt;
1747 width:80%;
1748 margin:auto;
1751 h1, h2 {
1752 text-align:center;
1754 .bold {
1755 font-weight:bold;
1757 .mdl-align {
1758 text-align:center;
1760 /*]]>*/</style>
1761 <title>$filename</title>
1762 </head>
1763 <body>
1764 EOF;
1765 $this->documentstarted = true;
1768 function start_table($sheettitle) {
1769 $this->table->sortable(false);
1770 $this->table->collapsible(false);
1771 echo "<h2>{$sheettitle}</h2>";
1772 $this->table->start_html();
1775 function output_headers($headers) {
1776 $this->table->print_headers();
1777 echo html_writer::start_tag('tbody');
1780 function add_data($row) {
1781 $this->table->print_row($row);
1782 return true;
1785 function add_seperator() {
1786 $this->table->print_row(NULL);
1787 return true;
1790 function finish_table() {
1791 $this->table->finish_html();
1794 function finish_document() {
1795 echo "</body>\n</html>";
1796 exit;
1799 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1800 if (is_null($options)) {
1801 $options = new stdClass;
1803 //some sensible defaults
1804 if (!isset($options->para)) {
1805 $options->para = false;
1807 if (!isset($options->newlines)) {
1808 $options->newlines = false;
1810 if (!isset($options->smiley)) {
1811 $options->smiley = false;
1813 if (!isset($options->filter)) {
1814 $options->filter = false;
1816 return format_text($text, $format, $options);