Merge branch 'wip-mdl-41843-m25' of git://github.com/rajeshtaneja/moodle into MOODLE_...
[moodle.git] / lib / tablelib.php
blob43724ac7d6f50067d97ece52e81f6f57132865a6
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) - 1, '');
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 if ($this->is_sortable($column)) {
1129 $firstnamesortlink = $this->sort_link(get_string('firstname'),
1130 'firstname', $primary_sort_column === 'firstname', $primary_sort_order);
1132 $lastnamesortlink = $this->sort_link(get_string('lastname'),
1133 'lastname', $primary_sort_column === 'lastname', $primary_sort_order);
1135 $override = new stdClass();
1136 $override->firstname = 'firstname';
1137 $override->lastname = 'lastname';
1138 $fullnamelanguage = get_string('fullnamedisplay', '', $override);
1140 if (($CFG->fullnamedisplay == 'firstname lastname') or
1141 ($CFG->fullnamedisplay == 'firstname') or
1142 ($CFG->fullnamedisplay == 'language' and $fullnamelanguage == 'firstname lastname' )) {
1143 $this->headers[$index] = $firstnamesortlink . ' / ' . $lastnamesortlink;
1144 } else {
1145 $this->headers[$index] = $lastnamesortlink . ' / ' . $firstnamesortlink;
1148 break;
1150 case 'userpic':
1151 // do nothing, do not display sortable links
1152 break;
1154 default:
1155 if ($this->is_sortable($column)) {
1156 $this->headers[$index] = $this->sort_link($this->headers[$index],
1157 $column, $primary_sort_column == $column, $primary_sort_order);
1161 $attributes = array(
1162 'class' => 'header c' . $index . $this->column_class[$column],
1163 'scope' => 'col',
1165 if ($this->headers[$index] === NULL) {
1166 $content = '&nbsp;';
1167 } else if (!empty($this->sess->collapse[$column])) {
1168 $content = $icon_hide;
1169 } else {
1170 if (is_array($this->column_style[$column])) {
1171 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1173 $content = $this->headers[$index] . html_writer::tag('div',
1174 $icon_hide, array('class' => 'commands'));
1176 echo html_writer::tag('th', $content, $attributes);
1179 echo html_writer::end_tag('tr');
1180 echo html_writer::end_tag('thead');
1184 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1185 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1186 * @param int $order SORT_ASC or SORT_DESC
1187 * @return string HTML fragment.
1189 protected function sort_icon($isprimary, $order) {
1190 global $OUTPUT;
1192 if (!$isprimary) {
1193 return '';
1196 if ($order == SORT_ASC) {
1197 return html_writer::empty_tag('img',
1198 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1199 } else {
1200 return html_writer::empty_tag('img',
1201 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1206 * Generate the correct tool tip for changing the sort order. This is a
1207 * helper method used by {@link sort_link()}.
1208 * @param bool $isprimary whether the is column is the current primary sort column.
1209 * @param int $order SORT_ASC or SORT_DESC
1210 * @return string the correct title.
1212 protected function sort_order_name($isprimary, $order) {
1213 if ($isprimary && $order != SORT_ASC) {
1214 return get_string('desc');
1215 } else {
1216 return get_string('asc');
1221 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1222 * @param string $text the text for the link.
1223 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1224 * @param bool $isprimary whether the is column is the current primary sort column.
1225 * @param int $order SORT_ASC or SORT_DESC
1226 * @return string HTML fragment.
1228 protected function sort_link($text, $column, $isprimary, $order) {
1229 return html_writer::link($this->baseurl->out(false,
1230 array($this->request[TABLE_VAR_SORT] => $column)),
1231 $text . get_accesshide(get_string('sortby') . ' ' .
1232 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1233 $this->sort_icon($isprimary, $order);
1237 * This function is not part of the public api.
1239 function start_html() {
1240 global $OUTPUT;
1241 // Do we need to print initial bars?
1242 $this->print_initials_bar();
1244 // Paging bar
1245 if ($this->use_pages) {
1246 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1247 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1248 echo $OUTPUT->render($pagingbar);
1251 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1252 echo $this->download_buttons();
1255 $this->wrap_html_start();
1256 // Start of main data table
1258 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1259 echo html_writer::start_tag('table', $this->attributes);
1264 * This function is not part of the public api.
1265 * @param array $styles CSS-property => value
1266 * @return string values suitably to go in a style="" attribute in HTML.
1268 function make_styles_string($styles) {
1269 if (empty($styles)) {
1270 return null;
1273 $string = '';
1274 foreach($styles as $property => $value) {
1275 $string .= $property . ':' . $value . ';';
1277 return $string;
1283 * @package moodlecore
1284 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1287 class table_sql extends flexible_table {
1289 public $countsql = NULL;
1290 public $countparams = NULL;
1292 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1294 public $sql = NULL;
1296 * @var array Data fetched from the db.
1298 public $rawdata = NULL;
1301 * @var bool Overriding default for this.
1303 public $is_sortable = true;
1305 * @var bool Overriding default for this.
1307 public $is_collapsible = true;
1310 * @param string $uniqueid a string identifying this table.Used as a key in
1311 * session vars.
1313 function __construct($uniqueid) {
1314 parent::__construct($uniqueid);
1315 // some sensible defaults
1316 $this->set_attribute('cellspacing', '0');
1317 $this->set_attribute('class', 'generaltable generalbox');
1321 * Take the data returned from the db_query and go through all the rows
1322 * processing each col using either col_{columnname} method or other_cols
1323 * method or if other_cols returns NULL then put the data straight into the
1324 * table.
1326 function build_table() {
1327 if ($this->rawdata) {
1328 foreach ($this->rawdata as $row) {
1329 $formattedrow = $this->format_row($row);
1330 $this->add_data_keyed($formattedrow,
1331 $this->get_row_class($row));
1337 * Get any extra classes names to add to this row in the HTML.
1338 * @param $row array the data for this row.
1339 * @return string added to the class="" attribute of the tr.
1341 function get_row_class($row) {
1342 return '';
1346 * This is only needed if you want to use different sql to count rows.
1347 * Used for example when perhaps all db JOINS are not needed when counting
1348 * records. You don't need to call this function the count_sql
1349 * will be generated automatically.
1351 * We need to count rows returned by the db seperately to the query itself
1352 * as we need to know how many pages of data we have to display.
1354 function set_count_sql($sql, array $params = NULL) {
1355 $this->countsql = $sql;
1356 $this->countparams = $params;
1360 * Set the sql to query the db. Query will be :
1361 * SELECT $fields FROM $from WHERE $where
1362 * Of course you can use sub-queries, JOINS etc. by putting them in the
1363 * appropriate clause of the query.
1365 function set_sql($fields, $from, $where, array $params = NULL) {
1366 $this->sql = new stdClass();
1367 $this->sql->fields = $fields;
1368 $this->sql->from = $from;
1369 $this->sql->where = $where;
1370 $this->sql->params = $params;
1374 * Query the db. Store results in the table object for use by build_table.
1376 * @param int $pagesize size of page for paginated displayed table.
1377 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1378 * will only be used if there is a fullname column defined for the table.
1380 function query_db($pagesize, $useinitialsbar=true) {
1381 global $DB;
1382 if (!$this->is_downloading()) {
1383 if ($this->countsql === NULL) {
1384 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1385 $this->countparams = $this->sql->params;
1387 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1388 if ($useinitialsbar && !$this->is_downloading()) {
1389 $this->initialbars($grandtotal > $pagesize);
1392 list($wsql, $wparams) = $this->get_sql_where();
1393 if ($wsql) {
1394 $this->countsql .= ' AND '.$wsql;
1395 $this->countparams = array_merge($this->countparams, $wparams);
1397 $this->sql->where .= ' AND '.$wsql;
1398 $this->sql->params = array_merge($this->sql->params, $wparams);
1400 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1401 } else {
1402 $total = $grandtotal;
1405 $this->pagesize($pagesize, $total);
1408 // Fetch the attempts
1409 $sort = $this->get_sql_sort();
1410 if ($sort) {
1411 $sort = "ORDER BY $sort";
1413 $sql = "SELECT
1414 {$this->sql->fields}
1415 FROM {$this->sql->from}
1416 WHERE {$this->sql->where}
1417 {$sort}";
1419 if (!$this->is_downloading()) {
1420 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1421 } else {
1422 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1427 * Convenience method to call a number of methods for you to display the
1428 * table.
1430 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1431 global $DB;
1432 if (!$this->columns) {
1433 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1434 //if columns is not set then define columns as the keys of the rows returned
1435 //from the db.
1436 $this->define_columns(array_keys((array)$onerow));
1437 $this->define_headers(array_keys((array)$onerow));
1439 $this->setup();
1440 $this->query_db($pagesize, $useinitialsbar);
1441 $this->build_table();
1442 $this->finish_output();
1448 * @package moodlecore
1449 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1452 class table_default_export_format_parent {
1454 * @var flexible_table or child class reference pointing to table class
1455 * object from which to export data.
1457 var $table;
1460 * @var bool output started. Keeps track of whether any output has been
1461 * started yet.
1463 var $documentstarted = false;
1464 function table_default_export_format_parent(&$table) {
1465 $this->table =& $table;
1468 function set_table(&$table) {
1469 $this->table =& $table;
1472 function add_data($row) {
1473 return false;
1476 function add_seperator() {
1477 return false;
1480 function document_started() {
1481 return $this->documentstarted;
1484 * Given text in a variety of format codings, this function returns
1485 * the text as safe HTML or as plain text dependent on what is appropriate
1486 * for the download format. The default removes all tags.
1488 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1489 //use some whitespace to indicate where there was some line spacing.
1490 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1491 return strip_tags($text);
1497 * @package moodlecore
1498 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1501 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1502 var $currentrow;
1503 var $workbook;
1504 var $worksheet;
1506 * @var object format object - format for normal table cells
1508 var $formatnormal;
1510 * @var object format object - format for header table cells
1512 var $formatheaders;
1515 * should be overriden in child class.
1517 var $fileextension;
1520 * This method will be overridden in the child class.
1522 function define_workbook() {
1525 function start_document($filename) {
1526 $filename = $filename.'.'.$this->fileextension;
1527 $this->define_workbook();
1528 // format types
1529 $this->formatnormal =& $this->workbook->add_format();
1530 $this->formatnormal->set_bold(0);
1531 $this->formatheaders =& $this->workbook->add_format();
1532 $this->formatheaders->set_bold(1);
1533 $this->formatheaders->set_align('center');
1534 // Sending HTTP headers
1535 $this->workbook->send($filename);
1536 $this->documentstarted = true;
1539 function start_table($sheettitle) {
1540 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1541 $this->currentrow=0;
1544 function output_headers($headers) {
1545 $colnum = 0;
1546 foreach ($headers as $item) {
1547 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1548 $colnum++;
1550 $this->currentrow++;
1553 function add_data($row) {
1554 $colnum = 0;
1555 foreach ($row as $item) {
1556 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1557 $colnum++;
1559 $this->currentrow++;
1560 return true;
1563 function add_seperator() {
1564 $this->currentrow++;
1565 return true;
1568 function finish_table() {
1571 function finish_document() {
1572 $this->workbook->close();
1573 exit;
1579 * @package moodlecore
1580 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1583 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1584 var $fileextension = 'xls';
1586 function define_workbook() {
1587 global $CFG;
1588 require_once("$CFG->libdir/excellib.class.php");
1589 // Creating a workbook
1590 $this->workbook = new MoodleExcelWorkbook("-");
1597 * @package moodlecore
1598 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1601 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1602 var $fileextension = 'ods';
1603 function define_workbook() {
1604 global $CFG;
1605 require_once("$CFG->libdir/odslib.class.php");
1606 // Creating a workbook
1607 $this->workbook = new MoodleODSWorkbook("-");
1613 * @package moodlecore
1614 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1615 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1617 class table_text_export_format_parent extends table_default_export_format_parent {
1618 protected $seperator = "tab";
1619 protected $mimetype = 'text/tab-separated-values';
1620 protected $ext = '.txt';
1621 protected $myexporter;
1623 public function __construct() {
1624 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1627 public function start_document($filename) {
1628 $this->filename = $filename;
1629 $this->documentstarted = true;
1630 $this->myexporter->set_filename($filename, $this->ext);
1633 public function start_table($sheettitle) {
1634 //nothing to do here
1637 public function output_headers($headers) {
1638 $this->myexporter->add_data($headers);
1641 public function add_data($row) {
1642 $this->myexporter->add_data($row);
1643 return true;
1646 public function finish_table() {
1647 //nothing to do here
1650 public function finish_document() {
1651 $this->myexporter->download_file();
1652 exit;
1656 * Format a row of data.
1657 * @param array $data
1659 protected function format_row($data) {
1660 $escapeddata = array();
1661 foreach ($data as $value) {
1662 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1664 return implode($this->seperator, $escapeddata) . "\n";
1670 * @package moodlecore
1671 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1674 class table_tsv_export_format extends table_text_export_format_parent {
1675 protected $seperator = "tab";
1676 protected $mimetype = 'text/tab-separated-values';
1677 protected $ext = '.txt';
1680 require_once($CFG->libdir . '/csvlib.class.php');
1682 * @package moodlecore
1683 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1684 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1686 class table_csv_export_format extends table_text_export_format_parent {
1687 protected $seperator = "comma";
1688 protected $mimetype = 'text/csv';
1689 protected $ext = '.csv';
1693 * @package moodlecore
1694 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1697 class table_xhtml_export_format extends table_default_export_format_parent {
1698 function start_document($filename) {
1699 header("Content-Type: application/download\n");
1700 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1701 header("Expires: 0");
1702 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1703 header("Pragma: public");
1704 //html headers
1705 echo <<<EOF
1706 <?xml version="1.0" encoding="UTF-8"?>
1707 <!DOCTYPE html
1708 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1709 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1711 <html xmlns="http://www.w3.org/1999/xhtml"
1712 xml:lang="en" lang="en">
1713 <head>
1714 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1715 <style type="text/css">/*<![CDATA[*/
1717 .flexible th {
1718 white-space:normal;
1720 th.header, td.header, div.header {
1721 border-color:#DDDDDD;
1722 background-color:lightGrey;
1724 .flexible th {
1725 white-space:nowrap;
1727 th {
1728 font-weight:bold;
1731 .generaltable {
1732 border-style:solid;
1734 .generalbox {
1735 border-style:solid;
1737 body, table, td, th {
1738 font-family:Arial,Verdana,Helvetica,sans-serif;
1739 font-size:100%;
1741 td {
1742 border-style:solid;
1743 border-width:1pt;
1745 table {
1746 border-collapse:collapse;
1747 border-spacing:0pt;
1748 width:80%;
1749 margin:auto;
1752 h1, h2 {
1753 text-align:center;
1755 .bold {
1756 font-weight:bold;
1758 .mdl-align {
1759 text-align:center;
1761 /*]]>*/</style>
1762 <title>$filename</title>
1763 </head>
1764 <body>
1765 EOF;
1766 $this->documentstarted = true;
1769 function start_table($sheettitle) {
1770 $this->table->sortable(false);
1771 $this->table->collapsible(false);
1772 echo "<h2>{$sheettitle}</h2>";
1773 $this->table->start_html();
1776 function output_headers($headers) {
1777 $this->table->print_headers();
1778 echo html_writer::start_tag('tbody');
1781 function add_data($row) {
1782 $this->table->print_row($row);
1783 return true;
1786 function add_seperator() {
1787 $this->table->print_row(NULL);
1788 return true;
1791 function finish_table() {
1792 $this->table->finish_html();
1795 function finish_document() {
1796 echo "</body>\n</html>";
1797 exit;
1800 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1801 if (is_null($options)) {
1802 $options = new stdClass;
1804 //some sensible defaults
1805 if (!isset($options->para)) {
1806 $options->para = false;
1808 if (!isset($options->newlines)) {
1809 $options->newlines = false;
1811 if (!isset($options->smiley)) {
1812 $options->smiley = false;
1814 if (!isset($options->filter)) {
1815 $options->filter = false;
1817 return format_text($text, $format, $options);