Merge branch 'MDL-44773-27' of git://github.com/FMCorz/moodle into MOODLE_27_STABLE
[moodle.git] / lib / tablelib.php
blobd2ec1e386422d52f3ca707e04bf4083f8b0e07b0
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 * Be warned that you cannot use this with column aliases. You can only do this
222 * with real columns. See MDL-40481 for an example.
223 * @param string column name
225 function text_sorting($column) {
226 $this->column_textsort[] = $column;
230 * Do not sort using this column
231 * @param string column name
233 function no_sorting($column) {
234 $this->column_nosort[] = $column;
238 * Is the column sortable?
239 * @param string column name, null means table
240 * @return bool
242 function is_sortable($column = null) {
243 if (empty($column)) {
244 return $this->is_sortable;
246 if (!$this->is_sortable) {
247 return false;
249 return !in_array($column, $this->column_nosort);
253 * Sets the is_collapsible variable to the given boolean.
254 * @param bool $bool
255 * @return void
257 function collapsible($bool) {
258 $this->is_collapsible = $bool;
262 * Sets the use_pages variable to the given boolean.
263 * @param bool $bool
264 * @return void
266 function pageable($bool) {
267 $this->use_pages = $bool;
271 * Sets the use_initials variable to the given boolean.
272 * @param bool $bool
273 * @return void
275 function initialbars($bool) {
276 $this->use_initials = $bool;
280 * Sets the pagesize variable to the given integer, the totalrows variable
281 * to the given integer, and the use_pages variable to true.
282 * @param int $perpage
283 * @param int $total
284 * @return void
286 function pagesize($perpage, $total) {
287 $this->pagesize = $perpage;
288 $this->totalrows = $total;
289 $this->use_pages = true;
293 * Assigns each given variable in the array to the corresponding index
294 * in the request class variable.
295 * @param array $variables
296 * @return void
298 function set_control_variables($variables) {
299 foreach ($variables as $what => $variable) {
300 if (isset($this->request[$what])) {
301 $this->request[$what] = $variable;
307 * Gives the given $value to the $attribute index of $this->attributes.
308 * @param string $attribute
309 * @param mixed $value
310 * @return void
312 function set_attribute($attribute, $value) {
313 $this->attributes[$attribute] = $value;
317 * What this method does is set the column so that if the same data appears in
318 * consecutive rows, then it is not repeated.
320 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
321 * that when one student has made multiple attempts, their name is only printed in the row
322 * for their first attempt.
323 * @param int $column the index of a column.
325 function column_suppress($column) {
326 if (isset($this->column_suppress[$column])) {
327 $this->column_suppress[$column] = true;
332 * Sets the given $column index to the given $classname in $this->column_class.
333 * @param int $column
334 * @param string $classname
335 * @return void
337 function column_class($column, $classname) {
338 if (isset($this->column_class[$column])) {
339 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
344 * Sets the given $column index and $property index to the given $value in $this->column_style.
345 * @param int $column
346 * @param string $property
347 * @param mixed $value
348 * @return void
350 function column_style($column, $property, $value) {
351 if (isset($this->column_style[$column])) {
352 $this->column_style[$column][$property] = $value;
357 * Sets all columns' $propertys to the given $value in $this->column_style.
358 * @param int $property
359 * @param string $value
360 * @return void
362 function column_style_all($property, $value) {
363 foreach (array_keys($this->columns) as $column) {
364 $this->column_style[$column][$property] = $value;
369 * Sets $this->baseurl.
370 * @param moodle_url|string $url the url with params needed to call up this page
372 function define_baseurl($url) {
373 $this->baseurl = new moodle_url($url);
377 * @param array $columns an array of identifying names for columns. If
378 * columns are sorted then column names must correspond to a field in sql.
380 function define_columns($columns) {
381 $this->columns = array();
382 $this->column_style = array();
383 $this->column_class = array();
384 $colnum = 0;
386 foreach ($columns as $column) {
387 $this->columns[$column] = $colnum++;
388 $this->column_style[$column] = array();
389 $this->column_class[$column] = '';
390 $this->column_suppress[$column] = false;
395 * @param array $headers numerical keyed array of displayed string titles
396 * for each column.
398 function define_headers($headers) {
399 $this->headers = $headers;
403 * Must be called after table is defined. Use methods above first. Cannot
404 * use functions below till after calling this method.
405 * @return type?
407 function setup() {
408 global $SESSION, $CFG;
410 if (empty($this->columns) || empty($this->uniqueid)) {
411 return false;
414 if (!isset($SESSION->flextable)) {
415 $SESSION->flextable = array();
418 if (!isset($SESSION->flextable[$this->uniqueid])) {
419 $SESSION->flextable[$this->uniqueid] = new stdClass;
420 $SESSION->flextable[$this->uniqueid]->uniqueid = $this->uniqueid;
421 $SESSION->flextable[$this->uniqueid]->collapse = array();
422 $SESSION->flextable[$this->uniqueid]->sortby = array();
423 $SESSION->flextable[$this->uniqueid]->i_first = '';
424 $SESSION->flextable[$this->uniqueid]->i_last = '';
425 $SESSION->flextable[$this->uniqueid]->textsort = $this->column_textsort;
428 $this->sess = &$SESSION->flextable[$this->uniqueid];
430 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
431 isset($this->columns[$showcol])) {
432 $this->sess->collapse[$showcol] = false;
434 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
435 isset($this->columns[$hidecol])) {
436 $this->sess->collapse[$hidecol] = true;
437 if (array_key_exists($hidecol, $this->sess->sortby)) {
438 unset($this->sess->sortby[$hidecol]);
442 // Now, update the column attributes for collapsed columns
443 foreach (array_keys($this->columns) as $column) {
444 if (!empty($this->sess->collapse[$column])) {
445 $this->column_style[$column]['width'] = '10px';
449 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
450 $this->is_sortable($sortcol) && empty($this->sess->collapse[$sortcol]) &&
451 (isset($this->columns[$sortcol]) || in_array($sortcol, array('firstname', 'lastname')) && isset($this->columns['fullname']))) {
453 if (array_key_exists($sortcol, $this->sess->sortby)) {
454 // This key already exists somewhere. Change its sortorder and bring it to the top.
455 $sortorder = $this->sess->sortby[$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
456 unset($this->sess->sortby[$sortcol]);
457 $this->sess->sortby = array_merge(array($sortcol => $sortorder), $this->sess->sortby);
458 } else {
459 // Key doesn't exist, so just add it to the beginning of the array, ascending order
460 $this->sess->sortby = array_merge(array($sortcol => SORT_ASC), $this->sess->sortby);
463 // Finally, make sure that no more than $this->maxsortkeys are present into the array
464 $this->sess->sortby = array_slice($this->sess->sortby, 0, $this->maxsortkeys);
467 // 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.
468 // This prevents results from being returned in a random order if the only order by column contains equal values.
469 if (!empty($this->sort_default_column)) {
470 if (!array_key_exists($this->sort_default_column, $this->sess->sortby)) {
471 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
472 $this->sess->sortby = array_merge($this->sess->sortby, $defaultsort);
476 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
477 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
478 $this->sess->i_last = $ilast;
481 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
482 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
483 $this->sess->i_first = $ifirst;
486 if (empty($this->baseurl)) {
487 debugging('You should set baseurl when using flexible_table.');
488 global $PAGE;
489 $this->baseurl = $PAGE->url;
492 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
493 $this->setup = true;
495 // Always introduce the "flexible" class for the table if not specified
496 if (empty($this->attributes)) {
497 $this->attributes['class'] = 'flexible';
498 } else if (!isset($this->attributes['class'])) {
499 $this->attributes['class'] = 'flexible';
500 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
501 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
506 * Get the order by clause from the session, for the table with id $uniqueid.
507 * @param string $uniqueid the identifier for a table.
508 * @return SQL fragment that can be used in an ORDER BY clause.
510 public static function get_sort_for_table($uniqueid) {
511 global $SESSION;
512 if (empty($SESSION->flextable[$uniqueid])) {
513 return '';
516 $sess = &$SESSION->flextable[$uniqueid];
517 if (empty($sess->sortby)) {
518 return '';
520 if (empty($sess->textsort)) {
521 $sess->textsort = array();
524 return self::construct_order_by($sess->sortby, $sess->textsort);
528 * Prepare an an order by clause from the list of columns to be sorted.
529 * @param array $cols column name => SORT_ASC or SORT_DESC
530 * @return SQL fragment that can be used in an ORDER BY clause.
532 public static function construct_order_by($cols, $textsortcols=array()) {
533 global $DB;
534 $bits = array();
536 foreach ($cols as $column => $order) {
537 if (in_array($column, $textsortcols)) {
538 $column = $DB->sql_order_by_text($column);
540 if ($order == SORT_ASC) {
541 $bits[] = $column . ' ASC';
542 } else {
543 $bits[] = $column . ' DESC';
547 return implode(', ', $bits);
551 * @return SQL fragment that can be used in an ORDER BY clause.
553 public function get_sql_sort() {
554 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
558 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
559 * @return array column name => SORT_... constant.
561 public function get_sort_columns() {
562 if (!$this->setup) {
563 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
566 if (empty($this->sess->sortby)) {
567 return array();
570 foreach ($this->sess->sortby as $column => $notused) {
571 if (isset($this->columns[$column])) {
572 continue; // This column is OK.
574 if (in_array($column, array('firstname', 'lastname')) &&
575 isset($this->columns['fullname'])) {
576 continue; // This column is OK.
578 // This column is not OK.
579 unset($this->sess->sortby[$column]);
582 return $this->sess->sortby;
586 * @return int the offset for LIMIT clause of SQL
588 function get_page_start() {
589 if (!$this->use_pages) {
590 return '';
592 return $this->currpage * $this->pagesize;
596 * @return int the pagesize for LIMIT clause of SQL
598 function get_page_size() {
599 if (!$this->use_pages) {
600 return '';
602 return $this->pagesize;
606 * @return string sql to add to where statement.
608 function get_sql_where() {
609 global $DB;
611 $conditions = array();
612 $params = array();
614 if (isset($this->columns['fullname'])) {
615 static $i = 0;
616 $i++;
618 if (!empty($this->sess->i_first)) {
619 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
620 $params['ifirstc'.$i] = $this->sess->i_first.'%';
622 if (!empty($this->sess->i_last)) {
623 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
624 $params['ilastc'.$i] = $this->sess->i_last.'%';
628 return array(implode(" AND ", $conditions), $params);
632 * Add a row of data to the table. This function takes an array or object with
633 * column names as keys or property names.
635 * It ignores any elements with keys that are not defined as columns. It
636 * puts in empty strings into the row when there is no element in the passed
637 * array corresponding to a column in the table. It puts the row elements in
638 * the proper order (internally row table data is stored by in arrays with
639 * a numerical index corresponding to the column number).
641 * @param object|array $rowwithkeys array keys or object property names are column names,
642 * as defined in call to define_columns.
643 * @param string $classname CSS class name to add to this row's tr tag.
645 function add_data_keyed($rowwithkeys, $classname = '') {
646 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
650 * Add a number of rows to the table at once. And optionally finish output after they have been added.
652 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
653 * object or array is added to table. We expect properties for the row array as would be
654 * passed to add_data_keyed.
655 * @param bool $finish
657 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
658 foreach ($rowstoadd as $row) {
659 if (is_null($row)) {
660 $this->add_separator();
661 } else {
662 $this->add_data_keyed($this->format_row($row));
665 if ($finish) {
666 $this->finish_output(!$this->is_downloading());
671 * Add a seperator line to table.
673 function add_separator() {
674 if (!$this->setup) {
675 return false;
677 $this->add_data(NULL);
681 * This method actually directly echoes the row passed to it now or adds it
682 * to the download. If this is the first row and start_output has not
683 * already been called this method also calls start_output to open the table
684 * or send headers for the downloaded.
685 * Can be used as before. print_html now calls finish_html to close table.
687 * @param array $row a numerically keyed row of data to add to the table.
688 * @param string $classname CSS class name to add to this row's tr tag.
689 * @return bool success.
691 function add_data($row, $classname = '') {
692 if (!$this->setup) {
693 return false;
695 if (!$this->started_output) {
696 $this->start_output();
698 if ($this->exportclass!==null) {
699 if ($row === null) {
700 $this->exportclass->add_seperator();
701 } else {
702 $this->exportclass->add_data($row);
704 } else {
705 $this->print_row($row, $classname);
707 return true;
711 * You should call this to finish outputting the table data after adding
712 * data to the table with add_data or add_data_keyed.
715 function finish_output($closeexportclassdoc = true) {
716 if ($this->exportclass!==null) {
717 $this->exportclass->finish_table();
718 if ($closeexportclassdoc) {
719 $this->exportclass->finish_document();
721 } else {
722 $this->finish_html();
727 * Hook that can be overridden in child classes to wrap a table in a form
728 * for example. Called only when there is data to display and not
729 * downloading.
731 function wrap_html_start() {
735 * Hook that can be overridden in child classes to wrap a table in a form
736 * for example. Called only when there is data to display and not
737 * downloading.
739 function wrap_html_finish() {
743 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
744 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
745 * displaying table as html, adding a div wrap, etc.
747 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
749 * @param array|object $row row of data from db used to make one row of the table.
750 * @return array one row for the table, added using add_data_keyed method.
752 function format_row($row) {
753 if (is_array($row)) {
754 $row = (object)$row;
756 $formattedrow = array();
757 foreach (array_keys($this->columns) as $column) {
758 $colmethodname = 'col_'.$column;
759 if (method_exists($this, $colmethodname)) {
760 $formattedcolumn = $this->$colmethodname($row);
761 } else {
762 $formattedcolumn = $this->other_cols($column, $row);
763 if ($formattedcolumn===NULL) {
764 $formattedcolumn = $row->$column;
767 $formattedrow[$column] = $formattedcolumn;
769 return $formattedrow;
773 * Fullname is treated as a special columname in tablelib and should always
774 * be treated the same as the fullname of a user.
775 * @uses $this->useridfield if the userid field is not expected to be id
776 * then you need to override $this->useridfield to point at the correct
777 * field for the user id.
779 * @param object $row the data from the db containing all fields from the
780 * users table necessary to construct the full name of the user in
781 * current language.
782 * @return string contents of cell in column 'fullname', for this row.
784 function col_fullname($row) {
785 global $COURSE;
787 $name = fullname($row);
788 if ($this->download) {
789 return $name;
792 $userid = $row->{$this->useridfield};
793 if ($COURSE->id == SITEID) {
794 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
795 } else {
796 $profileurl = new moodle_url('/user/view.php',
797 array('id' => $userid, 'course' => $COURSE->id));
799 return html_writer::link($profileurl, $name);
803 * You can override this method in a child class. See the description of
804 * build_table which calls this method.
806 function other_cols($column, $row) {
807 return NULL;
811 * Used from col_* functions when text is to be displayed. Does the
812 * right thing - either converts text to html or strips any html tags
813 * depending on if we are downloading and what is the download type. Params
814 * are the same as format_text function in weblib.php but some default
815 * options are changed.
817 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
818 if (!$this->is_downloading()) {
819 if (is_null($options)) {
820 $options = new stdClass;
822 //some sensible defaults
823 if (!isset($options->para)) {
824 $options->para = false;
826 if (!isset($options->newlines)) {
827 $options->newlines = false;
829 if (!isset($options->smiley)) {
830 $options->smiley = false;
832 if (!isset($options->filter)) {
833 $options->filter = false;
835 return format_text($text, $format, $options);
836 } else {
837 $eci = $this->export_class_instance();
838 return $eci->format_text($text, $format, $options, $courseid);
842 * This method is deprecated although the old api is still supported.
843 * @deprecated 1.9.2 - Jun 2, 2008
845 function print_html() {
846 if (!$this->setup) {
847 return false;
849 $this->finish_html();
853 * This function is not part of the public api.
854 * @return string initial of first name we are currently filtering by
856 function get_initial_first() {
857 if (!$this->use_initials) {
858 return NULL;
861 return $this->sess->i_first;
865 * This function is not part of the public api.
866 * @return string initial of last name we are currently filtering by
868 function get_initial_last() {
869 if (!$this->use_initials) {
870 return NULL;
873 return $this->sess->i_last;
877 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
878 * @param array $alpha of letters in the alphabet.
879 * @param string $current the currently selected letter.
880 * @param string $class class name to add to this initial bar.
881 * @param string $title the name to put in front of this initial bar.
882 * @param string $urlvar URL parameter name for this initial.
884 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
885 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
886 $title . ' : ';
887 if ($current) {
888 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
889 } else {
890 echo html_writer::tag('strong', get_string('all'));
893 foreach ($alpha as $letter) {
894 if ($letter === $current) {
895 echo html_writer::tag('strong', $letter);
896 } else {
897 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
901 echo html_writer::end_tag('div');
905 * This function is not part of the public api.
907 function print_initials_bar() {
908 if ((!empty($this->sess->i_last) || !empty($this->sess->i_first) ||$this->use_initials)
909 && isset($this->columns['fullname'])) {
911 $alpha = explode(',', get_string('alphabet', 'langconfig'));
913 // Bar of first initials
914 if (!empty($this->sess->i_first)) {
915 $ifirst = $this->sess->i_first;
916 } else {
917 $ifirst = '';
919 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
920 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
922 // Bar of last initials
923 if (!empty($this->sess->i_last)) {
924 $ilast = $this->sess->i_last;
925 } else {
926 $ilast = '';
928 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
929 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
934 * This function is not part of the public api.
936 function print_nothing_to_display() {
937 global $OUTPUT;
938 $this->print_initials_bar();
940 echo $OUTPUT->heading(get_string('nothingtodisplay'));
944 * This function is not part of the public api.
946 function get_row_from_keyed($rowwithkeys) {
947 if (is_object($rowwithkeys)) {
948 $rowwithkeys = (array)$rowwithkeys;
950 $row = array();
951 foreach (array_keys($this->columns) as $column) {
952 if (isset($rowwithkeys[$column])) {
953 $row [] = $rowwithkeys[$column];
954 } else {
955 $row[] ='';
958 return $row;
961 * This function is not part of the public api.
963 function get_download_menu() {
964 $allclasses= get_declared_classes();
965 $exportclasses = array();
966 foreach ($allclasses as $class) {
967 $matches = array();
968 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
969 $type = $matches[1];
970 $exportclasses[$type]= get_string("download$type", 'table');
973 return $exportclasses;
977 * This function is not part of the public api.
979 function download_buttons() {
980 if ($this->is_downloadable() && !$this->is_downloading()) {
981 $downloadoptions = $this->get_download_menu();
983 $downloadelements = new stdClass();
984 $downloadelements->formatsmenu = html_writer::select($downloadoptions,
985 'download', $this->defaultdownloadformat, false);
986 $downloadelements->downloadbutton = '<input type="submit" value="'.
987 get_string('download').'"/>';
988 $html = '<form action="'. $this->baseurl .'" method="post">';
989 $html .= '<div class="mdl-align">';
990 $html .= html_writer::tag('label', get_string('downloadas', 'table', $downloadelements));
991 $html .= '</div></form>';
993 return $html;
994 } else {
995 return '';
999 * This function is not part of the public api.
1000 * You don't normally need to call this. It is called automatically when
1001 * needed when you start adding data to the table.
1004 function start_output() {
1005 $this->started_output = true;
1006 if ($this->exportclass!==null) {
1007 $this->exportclass->start_table($this->sheettitle);
1008 $this->exportclass->output_headers($this->headers);
1009 } else {
1010 $this->start_html();
1011 $this->print_headers();
1012 echo html_writer::start_tag('tbody');
1017 * This function is not part of the public api.
1019 * Please do not use .r0/.r1 for css, as they will be removed in Moodle 2.9.
1020 * @todo MDL-43902 , remove r0 and r1 from tr classes.
1022 function print_row($row, $classname = '') {
1023 echo $this->get_row_html($row, $classname);
1027 * Generate html code for the passed row.
1029 * @param array $row Row data.
1030 * @param string $classname classes to add.
1032 * @return string $html html code for the row passed.
1034 public function get_row_html($row, $classname = '') {
1035 static $suppress_lastrow = NULL;
1036 $oddeven = $this->currentrow % 2;
1037 $rowclasses = array('r' . $oddeven);
1039 if ($classname) {
1040 $rowclasses[] = $classname;
1043 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1044 $html = '';
1046 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1048 // If we have a separator, print it
1049 if ($row === NULL) {
1050 $colcount = count($this->columns);
1051 $html .= html_writer::tag('td', html_writer::tag('div', '',
1052 array('class' => 'tabledivider')), array('colspan' => $colcount));
1054 } else {
1055 $colbyindex = array_flip($this->columns);
1056 foreach ($row as $index => $data) {
1057 $column = $colbyindex[$index];
1059 if (empty($this->sess->collapse[$column])) {
1060 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1061 $content = '&nbsp;';
1062 } else {
1063 $content = $data;
1065 } else {
1066 $content = '&nbsp;';
1069 $html .= html_writer::tag('td', $content, array(
1070 'class' => 'cell c' . $index . $this->column_class[$column],
1071 'id' => $rowid . '_c' . $index,
1072 'style' => $this->make_styles_string($this->column_style[$column])));
1076 $html .= html_writer::end_tag('tr');
1078 $suppress_enabled = array_sum($this->column_suppress);
1079 if ($suppress_enabled) {
1080 $suppress_lastrow = $row;
1082 $this->currentrow++;
1083 return $html;
1087 * This function is not part of the public api.
1089 function finish_html() {
1090 global $OUTPUT;
1091 if (!$this->started_output) {
1092 //no data has been added to the table.
1093 $this->print_nothing_to_display();
1095 } else {
1096 // Print empty rows to fill the table to the current pagesize.
1097 // This is done so the header aria-controls attributes do not point to
1098 // non existant elements.
1099 $emptyrow = array_fill(0, count($this->columns), '');
1100 while ($this->currentrow < $this->pagesize) {
1101 $this->print_row($emptyrow, 'emptyrow');
1104 echo html_writer::end_tag('tbody');
1105 echo html_writer::end_tag('table');
1106 echo html_writer::end_tag('div');
1107 $this->wrap_html_finish();
1109 // Paging bar
1110 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1111 echo $this->download_buttons();
1114 if($this->use_pages) {
1115 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1116 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1117 echo $OUTPUT->render($pagingbar);
1123 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1124 * used by {@link print_headers()}.
1125 * @param string $column the column name, index into various names.
1126 * @param int $index numerical index of the column.
1127 * @return string HTML fragment.
1129 protected function show_hide_link($column, $index) {
1130 global $OUTPUT;
1131 // Some headers contain <br /> tags, do not include in title, hence the
1132 // strip tags.
1134 $ariacontrols = '';
1135 for ($i = 0; $i < $this->pagesize; $i++) {
1136 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1139 $ariacontrols = trim($ariacontrols);
1141 if (!empty($this->sess->collapse[$column])) {
1142 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1143 'aria-expanded' => 'false',
1144 'aria-controls' => $ariacontrols);
1145 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1146 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1147 $linkattributes);
1149 } else if ($this->headers[$index] !== NULL) {
1150 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1151 'aria-expanded' => 'true',
1152 'aria-controls' => $ariacontrols);
1153 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1154 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1155 $linkattributes);
1160 * This function is not part of the public api.
1162 function print_headers() {
1163 global $CFG, $OUTPUT;
1165 echo html_writer::start_tag('thead');
1166 echo html_writer::start_tag('tr');
1167 foreach ($this->columns as $column => $index) {
1169 $icon_hide = '';
1170 if ($this->is_collapsible) {
1171 $icon_hide = $this->show_hide_link($column, $index);
1174 $primary_sort_column = '';
1175 $primary_sort_order = '';
1176 if (reset($this->sess->sortby)) {
1177 $primary_sort_column = key($this->sess->sortby);
1178 $primary_sort_order = current($this->sess->sortby);
1181 switch ($column) {
1183 case 'fullname':
1184 // Check the full name display for sortable fields.
1185 $nameformat = $CFG->fullnamedisplay;
1186 if ($nameformat == 'language') {
1187 $nameformat = get_string('fullnamedisplay');
1189 $requirednames = order_in_string(array('firstname', 'lastname'), $nameformat);
1191 if (!empty($requirednames)) {
1192 if ($this->is_sortable($column)) {
1193 // Done this way for the possibility of more than two sortable full name display fields.
1194 $this->headers[$index] = '';
1195 foreach ($requirednames as $name) {
1196 $sortname = $this->sort_link(get_string($name),
1197 $name, $primary_sort_column === $name, $primary_sort_order);
1198 $this->headers[$index] .= $sortname . ' / ';
1200 $this->headers[$index] = substr($this->headers[$index], 0, -3);
1203 break;
1205 case 'userpic':
1206 // do nothing, do not display sortable links
1207 break;
1209 default:
1210 if ($this->is_sortable($column)) {
1211 $this->headers[$index] = $this->sort_link($this->headers[$index],
1212 $column, $primary_sort_column == $column, $primary_sort_order);
1216 $attributes = array(
1217 'class' => 'header c' . $index . $this->column_class[$column],
1218 'scope' => 'col',
1220 if ($this->headers[$index] === NULL) {
1221 $content = '&nbsp;';
1222 } else if (!empty($this->sess->collapse[$column])) {
1223 $content = $icon_hide;
1224 } else {
1225 if (is_array($this->column_style[$column])) {
1226 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1228 $content = $this->headers[$index] . html_writer::tag('div',
1229 $icon_hide, array('class' => 'commands'));
1231 echo html_writer::tag('th', $content, $attributes);
1234 echo html_writer::end_tag('tr');
1235 echo html_writer::end_tag('thead');
1239 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1240 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1241 * @param int $order SORT_ASC or SORT_DESC
1242 * @return string HTML fragment.
1244 protected function sort_icon($isprimary, $order) {
1245 global $OUTPUT;
1247 if (!$isprimary) {
1248 return '';
1251 if ($order == SORT_ASC) {
1252 return html_writer::empty_tag('img',
1253 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1254 } else {
1255 return html_writer::empty_tag('img',
1256 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1261 * Generate the correct tool tip for changing the sort order. This is a
1262 * helper method used by {@link sort_link()}.
1263 * @param bool $isprimary whether the is column is the current primary sort column.
1264 * @param int $order SORT_ASC or SORT_DESC
1265 * @return string the correct title.
1267 protected function sort_order_name($isprimary, $order) {
1268 if ($isprimary && $order != SORT_ASC) {
1269 return get_string('desc');
1270 } else {
1271 return get_string('asc');
1276 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1277 * @param string $text the text for the link.
1278 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1279 * @param bool $isprimary whether the is column is the current primary sort column.
1280 * @param int $order SORT_ASC or SORT_DESC
1281 * @return string HTML fragment.
1283 protected function sort_link($text, $column, $isprimary, $order) {
1284 return html_writer::link($this->baseurl->out(false,
1285 array($this->request[TABLE_VAR_SORT] => $column)),
1286 $text . get_accesshide(get_string('sortby') . ' ' .
1287 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1288 $this->sort_icon($isprimary, $order);
1292 * This function is not part of the public api.
1294 function start_html() {
1295 global $OUTPUT;
1296 // Do we need to print initial bars?
1297 $this->print_initials_bar();
1299 // Paging bar
1300 if ($this->use_pages) {
1301 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1302 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1303 echo $OUTPUT->render($pagingbar);
1306 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1307 echo $this->download_buttons();
1310 $this->wrap_html_start();
1311 // Start of main data table
1313 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1314 echo html_writer::start_tag('table', $this->attributes);
1319 * This function is not part of the public api.
1320 * @param array $styles CSS-property => value
1321 * @return string values suitably to go in a style="" attribute in HTML.
1323 function make_styles_string($styles) {
1324 if (empty($styles)) {
1325 return null;
1328 $string = '';
1329 foreach($styles as $property => $value) {
1330 $string .= $property . ':' . $value . ';';
1332 return $string;
1338 * @package moodlecore
1339 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1340 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1342 class table_sql extends flexible_table {
1344 public $countsql = NULL;
1345 public $countparams = NULL;
1347 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1349 public $sql = NULL;
1351 * @var array Data fetched from the db.
1353 public $rawdata = NULL;
1356 * @var bool Overriding default for this.
1358 public $is_sortable = true;
1360 * @var bool Overriding default for this.
1362 public $is_collapsible = true;
1365 * @param string $uniqueid a string identifying this table.Used as a key in
1366 * session vars.
1368 function __construct($uniqueid) {
1369 parent::__construct($uniqueid);
1370 // some sensible defaults
1371 $this->set_attribute('cellspacing', '0');
1372 $this->set_attribute('class', 'generaltable generalbox');
1376 * Take the data returned from the db_query and go through all the rows
1377 * processing each col using either col_{columnname} method or other_cols
1378 * method or if other_cols returns NULL then put the data straight into the
1379 * table.
1381 function build_table() {
1382 if ($this->rawdata) {
1383 foreach ($this->rawdata as $row) {
1384 $formattedrow = $this->format_row($row);
1385 $this->add_data_keyed($formattedrow,
1386 $this->get_row_class($row));
1392 * Get any extra classes names to add to this row in the HTML.
1393 * @param $row array the data for this row.
1394 * @return string added to the class="" attribute of the tr.
1396 function get_row_class($row) {
1397 return '';
1401 * This is only needed if you want to use different sql to count rows.
1402 * Used for example when perhaps all db JOINS are not needed when counting
1403 * records. You don't need to call this function the count_sql
1404 * will be generated automatically.
1406 * We need to count rows returned by the db seperately to the query itself
1407 * as we need to know how many pages of data we have to display.
1409 function set_count_sql($sql, array $params = NULL) {
1410 $this->countsql = $sql;
1411 $this->countparams = $params;
1415 * Set the sql to query the db. Query will be :
1416 * SELECT $fields FROM $from WHERE $where
1417 * Of course you can use sub-queries, JOINS etc. by putting them in the
1418 * appropriate clause of the query.
1420 function set_sql($fields, $from, $where, array $params = NULL) {
1421 $this->sql = new stdClass();
1422 $this->sql->fields = $fields;
1423 $this->sql->from = $from;
1424 $this->sql->where = $where;
1425 $this->sql->params = $params;
1429 * Query the db. Store results in the table object for use by build_table.
1431 * @param int $pagesize size of page for paginated displayed table.
1432 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1433 * will only be used if there is a fullname column defined for the table.
1435 function query_db($pagesize, $useinitialsbar=true) {
1436 global $DB;
1437 if (!$this->is_downloading()) {
1438 if ($this->countsql === NULL) {
1439 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1440 $this->countparams = $this->sql->params;
1442 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1443 if ($useinitialsbar && !$this->is_downloading()) {
1444 $this->initialbars($grandtotal > $pagesize);
1447 list($wsql, $wparams) = $this->get_sql_where();
1448 if ($wsql) {
1449 $this->countsql .= ' AND '.$wsql;
1450 $this->countparams = array_merge($this->countparams, $wparams);
1452 $this->sql->where .= ' AND '.$wsql;
1453 $this->sql->params = array_merge($this->sql->params, $wparams);
1455 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1456 } else {
1457 $total = $grandtotal;
1460 $this->pagesize($pagesize, $total);
1463 // Fetch the attempts
1464 $sort = $this->get_sql_sort();
1465 if ($sort) {
1466 $sort = "ORDER BY $sort";
1468 $sql = "SELECT
1469 {$this->sql->fields}
1470 FROM {$this->sql->from}
1471 WHERE {$this->sql->where}
1472 {$sort}";
1474 if (!$this->is_downloading()) {
1475 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1476 } else {
1477 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1482 * Convenience method to call a number of methods for you to display the
1483 * table.
1485 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1486 global $DB;
1487 if (!$this->columns) {
1488 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1489 //if columns is not set then define columns as the keys of the rows returned
1490 //from the db.
1491 $this->define_columns(array_keys((array)$onerow));
1492 $this->define_headers(array_keys((array)$onerow));
1494 $this->setup();
1495 $this->query_db($pagesize, $useinitialsbar);
1496 $this->build_table();
1497 $this->finish_output();
1503 * @package moodlecore
1504 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1507 class table_default_export_format_parent {
1509 * @var flexible_table or child class reference pointing to table class
1510 * object from which to export data.
1512 var $table;
1515 * @var bool output started. Keeps track of whether any output has been
1516 * started yet.
1518 var $documentstarted = false;
1519 function table_default_export_format_parent(&$table) {
1520 $this->table =& $table;
1523 function set_table(&$table) {
1524 $this->table =& $table;
1527 function add_data($row) {
1528 return false;
1531 function add_seperator() {
1532 return false;
1535 function document_started() {
1536 return $this->documentstarted;
1539 * Given text in a variety of format codings, this function returns
1540 * the text as safe HTML or as plain text dependent on what is appropriate
1541 * for the download format. The default removes all tags.
1543 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1544 //use some whitespace to indicate where there was some line spacing.
1545 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1546 return strip_tags($text);
1552 * @package moodlecore
1553 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1556 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1557 var $currentrow;
1558 var $workbook;
1559 var $worksheet;
1561 * @var object format object - format for normal table cells
1563 var $formatnormal;
1565 * @var object format object - format for header table cells
1567 var $formatheaders;
1570 * should be overriden in child class.
1572 var $fileextension;
1575 * This method will be overridden in the child class.
1577 function define_workbook() {
1580 function start_document($filename) {
1581 $filename = $filename.'.'.$this->fileextension;
1582 $this->define_workbook();
1583 // format types
1584 $this->formatnormal = $this->workbook->add_format();
1585 $this->formatnormal->set_bold(0);
1586 $this->formatheaders = $this->workbook->add_format();
1587 $this->formatheaders->set_bold(1);
1588 $this->formatheaders->set_align('center');
1589 // Sending HTTP headers
1590 $this->workbook->send($filename);
1591 $this->documentstarted = true;
1594 function start_table($sheettitle) {
1595 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1596 $this->currentrow=0;
1599 function output_headers($headers) {
1600 $colnum = 0;
1601 foreach ($headers as $item) {
1602 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1603 $colnum++;
1605 $this->currentrow++;
1608 function add_data($row) {
1609 $colnum = 0;
1610 foreach ($row as $item) {
1611 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1612 $colnum++;
1614 $this->currentrow++;
1615 return true;
1618 function add_seperator() {
1619 $this->currentrow++;
1620 return true;
1623 function finish_table() {
1626 function finish_document() {
1627 $this->workbook->close();
1628 exit;
1634 * @package moodlecore
1635 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1636 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1638 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1639 var $fileextension = 'xls';
1641 function define_workbook() {
1642 global $CFG;
1643 require_once("$CFG->libdir/excellib.class.php");
1644 // Creating a workbook
1645 $this->workbook = new MoodleExcelWorkbook("-");
1652 * @package moodlecore
1653 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1656 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1657 var $fileextension = 'ods';
1658 function define_workbook() {
1659 global $CFG;
1660 require_once("$CFG->libdir/odslib.class.php");
1661 // Creating a workbook
1662 $this->workbook = new MoodleODSWorkbook("-");
1668 * @package moodlecore
1669 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1672 class table_text_export_format_parent extends table_default_export_format_parent {
1673 protected $seperator = "tab";
1674 protected $mimetype = 'text/tab-separated-values';
1675 protected $ext = '.txt';
1676 protected $myexporter;
1678 public function __construct() {
1679 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1682 public function start_document($filename) {
1683 $this->filename = $filename;
1684 $this->documentstarted = true;
1685 $this->myexporter->set_filename($filename, $this->ext);
1688 public function start_table($sheettitle) {
1689 //nothing to do here
1692 public function output_headers($headers) {
1693 $this->myexporter->add_data($headers);
1696 public function add_data($row) {
1697 $this->myexporter->add_data($row);
1698 return true;
1701 public function finish_table() {
1702 //nothing to do here
1705 public function finish_document() {
1706 $this->myexporter->download_file();
1707 exit;
1711 * Format a row of data.
1712 * @param array $data
1714 protected function format_row($data) {
1715 $escapeddata = array();
1716 foreach ($data as $value) {
1717 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1719 return implode($this->seperator, $escapeddata) . "\n";
1725 * @package moodlecore
1726 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1729 class table_tsv_export_format extends table_text_export_format_parent {
1730 protected $seperator = "tab";
1731 protected $mimetype = 'text/tab-separated-values';
1732 protected $ext = '.txt';
1735 require_once($CFG->libdir . '/csvlib.class.php');
1737 * @package moodlecore
1738 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1741 class table_csv_export_format extends table_text_export_format_parent {
1742 protected $seperator = "comma";
1743 protected $mimetype = 'text/csv';
1744 protected $ext = '.csv';
1748 * @package moodlecore
1749 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1752 class table_xhtml_export_format extends table_default_export_format_parent {
1753 function start_document($filename) {
1754 header("Content-Type: application/download\n");
1755 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1756 header("Expires: 0");
1757 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1758 header("Pragma: public");
1759 //html headers
1760 echo <<<EOF
1761 <?xml version="1.0" encoding="UTF-8"?>
1762 <!DOCTYPE html
1763 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1764 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1766 <html xmlns="http://www.w3.org/1999/xhtml"
1767 xml:lang="en" lang="en">
1768 <head>
1769 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1770 <style type="text/css">/*<![CDATA[*/
1772 .flexible th {
1773 white-space:normal;
1775 th.header, td.header, div.header {
1776 border-color:#DDDDDD;
1777 background-color:lightGrey;
1779 .flexible th {
1780 white-space:nowrap;
1782 th {
1783 font-weight:bold;
1786 .generaltable {
1787 border-style:solid;
1789 .generalbox {
1790 border-style:solid;
1792 body, table, td, th {
1793 font-family:Arial,Verdana,Helvetica,sans-serif;
1794 font-size:100%;
1796 td {
1797 border-style:solid;
1798 border-width:1pt;
1800 table {
1801 border-collapse:collapse;
1802 border-spacing:0pt;
1803 width:80%;
1804 margin:auto;
1807 h1, h2 {
1808 text-align:center;
1810 .bold {
1811 font-weight:bold;
1813 .mdl-align {
1814 text-align:center;
1816 /*]]>*/</style>
1817 <title>$filename</title>
1818 </head>
1819 <body>
1820 EOF;
1821 $this->documentstarted = true;
1824 function start_table($sheettitle) {
1825 $this->table->sortable(false);
1826 $this->table->collapsible(false);
1827 echo "<h2>{$sheettitle}</h2>";
1828 $this->table->start_html();
1831 function output_headers($headers) {
1832 $this->table->print_headers();
1833 echo html_writer::start_tag('tbody');
1836 function add_data($row) {
1837 $this->table->print_row($row);
1838 return true;
1841 function add_seperator() {
1842 $this->table->print_row(NULL);
1843 return true;
1846 function finish_table() {
1847 $this->table->finish_html();
1850 function finish_document() {
1851 echo "</body>\n</html>";
1852 exit;
1855 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1856 if (is_null($options)) {
1857 $options = new stdClass;
1859 //some sensible defaults
1860 if (!isset($options->para)) {
1861 $options->para = false;
1863 if (!isset($options->newlines)) {
1864 $options->newlines = false;
1866 if (!isset($options->smiley)) {
1867 $options->smiley = false;
1869 if (!isset($options->filter)) {
1870 $options->filter = false;
1872 return format_text($text, $format, $options);