3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 * These constants relate to the table's handling of URL parameters.
31 define('TABLE_VAR_SORT', 1);
32 define('TABLE_VAR_HIDE', 2);
33 define('TABLE_VAR_SHOW', 3);
34 define('TABLE_VAR_IFIRST', 4);
35 define('TABLE_VAR_ILAST', 5);
36 define('TABLE_VAR_PAGE', 6);
37 define('TABLE_VAR_RESET', 7);
41 * Constants that indicate whether the paging bar for the table
42 * appears above or below the table.
44 define('TABLE_P_TOP', 1);
45 define('TABLE_P_BOTTOM', 2);
51 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 class flexible_table
{
57 var $attributes = array();
58 var $headers = array();
61 * @var string For create header with help icon.
63 private $helpforheaders = array();
64 var $columns = array();
65 var $column_style = array();
66 var $column_class = array();
67 var $column_suppress = array();
68 var $column_nosort = array('userpic');
69 private $column_textsort = array();
70 /** @var boolean Stores if setup has already been called on this flixible table. */
73 var $request = array();
76 * @var bool Whether or not to store table properties in the user_preferences table.
78 private $persistent = false;
79 var $is_collapsible = false;
80 var $is_sortable = false;
81 var $use_pages = false;
82 var $use_initials = false;
89 var $sort_default_column = NULL;
90 var $sort_default_order = SORT_ASC
;
93 * Array of positions in which to display download controls.
95 var $showdownloadbuttonsat= array(TABLE_P_TOP
);
98 * @var string Key of field returned by db query that is the id field of the
99 * user table or equivalent.
101 public $useridfield = 'id';
104 * @var string which download plugin to use. Default '' means none - print
105 * html table with paging. Property set by is_downloading which typically
106 * passes in cleaned data from $
111 * @var bool whether data is downloadable from table. Determines whether
112 * to display download buttons. Set by method downloadable().
114 var $downloadable = false;
117 * @var string which download plugin to use. Default '' means none - print
118 * html table with paging.
120 var $defaultdownloadformat = 'csv';
123 * @var bool Has start output been called yet?
125 var $started_output = false;
127 var $exportclass = null;
130 * @var array For storing user-customised table properties in the user_preferences db table.
132 private $prefs = array();
136 * @param int $uniqueid all tables have to have a unique id, this is used
137 * as a key when storing table properties like sort order in the session.
139 function __construct($uniqueid) {
140 $this->uniqueid
= $uniqueid;
141 $this->request
= array(
142 TABLE_VAR_SORT
=> 'tsort',
143 TABLE_VAR_HIDE
=> 'thide',
144 TABLE_VAR_SHOW
=> 'tshow',
145 TABLE_VAR_IFIRST
=> 'tifirst',
146 TABLE_VAR_ILAST
=> 'tilast',
147 TABLE_VAR_PAGE
=> 'page',
148 TABLE_VAR_RESET
=> 'treset'
153 * Call this to pass the download type. Use :
154 * $download = optional_param('download', '', PARAM_ALPHA);
155 * To get the download type. We assume that if you call this function with
156 * params that this table's data is downloadable, so we call is_downloadable
157 * for you (even if the param is '', which means no download this time.
158 * Also you can call this method with no params to get the current set
160 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
161 * @param string $filename filename for downloads without file extension.
162 * @param string $sheettitle title for downloaded data.
163 * @return string download type. One of csv, tsv, xhtml, ods, etc
165 function is_downloading($download = null, $filename='', $sheettitle='') {
166 if ($download!==null) {
167 $this->sheettitle
= $sheettitle;
168 $this->is_downloadable(true);
169 $this->download
= $download;
170 $this->filename
= clean_filename($filename);
171 $this->export_class_instance();
173 return $this->download
;
177 * Get, and optionally set, the export class.
178 * @param $exportclass (optional) if passed, set the table to use this export class.
179 * @return table_default_export_format_parent the export class in use (after any set).
181 function export_class_instance($exportclass = null) {
182 if (!is_null($exportclass)) {
183 $this->started_output
= true;
184 $this->exportclass
= $exportclass;
185 $this->exportclass
->table
= $this;
186 } else if (is_null($this->exportclass
) && !empty($this->download
)) {
187 $classname = 'table_'.$this->download
.'_export_format';
188 $this->exportclass
= new $classname($this);
189 if (!$this->exportclass
->document_started()) {
190 $this->exportclass
->start_document($this->filename
);
193 return $this->exportclass
;
197 * Probably don't need to call this directly. Calling is_downloading with a
198 * param automatically sets table as downloadable.
200 * @param bool $downloadable optional param to set whether data from
201 * table is downloadable. If ommitted this function can be used to get
202 * current state of table.
203 * @return bool whether table data is set to be downloadable.
205 function is_downloadable($downloadable = null) {
206 if ($downloadable !== null) {
207 $this->downloadable
= $downloadable;
209 return $this->downloadable
;
213 * Call with boolean true to store table layout changes in the user_preferences table.
214 * Note: user_preferences.value has a maximum length of 1333 characters.
215 * Call with no parameter to get current state of table persistence.
217 * @param bool $persistent Optional parameter to set table layout persistence.
218 * @return bool Whether or not the table layout preferences will persist.
220 public function is_persistent($persistent = null) {
221 if ($persistent == true) {
222 $this->persistent
= true;
224 return $this->persistent
;
228 * Where to show download buttons.
229 * @param array $showat array of postions in which to show download buttons.
230 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
232 function show_download_buttons_at($showat) {
233 $this->showdownloadbuttonsat
= $showat;
237 * Sets the is_sortable variable to the given boolean, sort_default_column to
238 * the given string, and the sort_default_order to the given integer.
240 * @param string $defaultcolumn
241 * @param int $defaultorder
244 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC
) {
245 $this->is_sortable
= $bool;
246 $this->sort_default_column
= $defaultcolumn;
247 $this->sort_default_order
= $defaultorder;
251 * Use text sorting functions for this column (required for text columns with Oracle).
252 * Be warned that you cannot use this with column aliases. You can only do this
253 * with real columns. See MDL-40481 for an example.
254 * @param string column name
256 function text_sorting($column) {
257 $this->column_textsort
[] = $column;
261 * Do not sort using this column
262 * @param string column name
264 function no_sorting($column) {
265 $this->column_nosort
[] = $column;
269 * Is the column sortable?
270 * @param string column name, null means table
273 function is_sortable($column = null) {
274 if (empty($column)) {
275 return $this->is_sortable
;
277 if (!$this->is_sortable
) {
280 return !in_array($column, $this->column_nosort
);
284 * Sets the is_collapsible variable to the given boolean.
288 function collapsible($bool) {
289 $this->is_collapsible
= $bool;
293 * Sets the use_pages variable to the given boolean.
297 function pageable($bool) {
298 $this->use_pages
= $bool;
302 * Sets the use_initials variable to the given boolean.
306 function initialbars($bool) {
307 $this->use_initials
= $bool;
311 * Sets the pagesize variable to the given integer, the totalrows variable
312 * to the given integer, and the use_pages variable to true.
313 * @param int $perpage
317 function pagesize($perpage, $total) {
318 $this->pagesize
= $perpage;
319 $this->totalrows
= $total;
320 $this->use_pages
= true;
324 * Assigns each given variable in the array to the corresponding index
325 * in the request class variable.
326 * @param array $variables
329 function set_control_variables($variables) {
330 foreach ($variables as $what => $variable) {
331 if (isset($this->request
[$what])) {
332 $this->request
[$what] = $variable;
338 * Gives the given $value to the $attribute index of $this->attributes.
339 * @param string $attribute
340 * @param mixed $value
343 function set_attribute($attribute, $value) {
344 $this->attributes
[$attribute] = $value;
348 * What this method does is set the column so that if the same data appears in
349 * consecutive rows, then it is not repeated.
351 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
352 * that when one student has made multiple attempts, their name is only printed in the row
353 * for their first attempt.
354 * @param int $column the index of a column.
356 function column_suppress($column) {
357 if (isset($this->column_suppress
[$column])) {
358 $this->column_suppress
[$column] = true;
363 * Sets the given $column index to the given $classname in $this->column_class.
365 * @param string $classname
368 function column_class($column, $classname) {
369 if (isset($this->column_class
[$column])) {
370 $this->column_class
[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
375 * Sets the given $column index and $property index to the given $value in $this->column_style.
377 * @param string $property
378 * @param mixed $value
381 function column_style($column, $property, $value) {
382 if (isset($this->column_style
[$column])) {
383 $this->column_style
[$column][$property] = $value;
388 * Sets all columns' $propertys to the given $value in $this->column_style.
389 * @param int $property
390 * @param string $value
393 function column_style_all($property, $value) {
394 foreach (array_keys($this->columns
) as $column) {
395 $this->column_style
[$column][$property] = $value;
400 * Sets $this->baseurl.
401 * @param moodle_url|string $url the url with params needed to call up this page
403 function define_baseurl($url) {
404 $this->baseurl
= new moodle_url($url);
408 * @param array $columns an array of identifying names for columns. If
409 * columns are sorted then column names must correspond to a field in sql.
411 function define_columns($columns) {
412 $this->columns
= array();
413 $this->column_style
= array();
414 $this->column_class
= array();
417 foreach ($columns as $column) {
418 $this->columns
[$column] = $colnum++
;
419 $this->column_style
[$column] = array();
420 $this->column_class
[$column] = '';
421 $this->column_suppress
[$column] = false;
426 * @param array $headers numerical keyed array of displayed string titles
429 function define_headers($headers) {
430 $this->headers
= $headers;
434 * Defines a help icon for the header
436 * Always use this function if you need to create header with sorting and help icon.
438 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
440 public function define_help_for_headers($helpicons) {
441 $this->helpforheaders
= $helpicons;
445 * Must be called after table is defined. Use methods above first. Cannot
446 * use functions below till after calling this method.
452 if (empty($this->columns
) ||
empty($this->uniqueid
)) {
456 // Load any existing user preferences.
457 if ($this->persistent
) {
458 $this->prefs
= json_decode(get_user_preferences('flextable_' . $this->uniqueid
), true);
459 } else if (isset($SESSION->flextable
[$this->uniqueid
])) {
460 $this->prefs
= $SESSION->flextable
[$this->uniqueid
];
463 // Set up default preferences if needed.
464 if (!$this->prefs
or optional_param($this->request
[TABLE_VAR_RESET
], false, PARAM_BOOL
)) {
465 $this->prefs
= array(
466 'collapse' => array(),
470 'textsort' => $this->column_textsort
,
473 $oldprefs = $this->prefs
;
475 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
476 isset($this->columns
[$showcol])) {
477 $this->prefs
['collapse'][$showcol] = false;
479 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
480 isset($this->columns
[$hidecol])) {
481 $this->prefs
['collapse'][$hidecol] = true;
482 if (array_key_exists($hidecol, $this->prefs
['sortby'])) {
483 unset($this->prefs
['sortby'][$hidecol]);
487 // Now, update the column attributes for collapsed columns
488 foreach (array_keys($this->columns
) as $column) {
489 if (!empty($this->prefs
['collapse'][$column])) {
490 $this->column_style
[$column]['width'] = '10px';
494 if (($sortcol = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
)) &&
495 $this->is_sortable($sortcol) && empty($this->prefs
['collapse'][$sortcol]) &&
496 (isset($this->columns
[$sortcol]) ||
in_array($sortcol, get_all_user_name_fields())
497 && isset($this->columns
['fullname']))) {
499 if (array_key_exists($sortcol, $this->prefs
['sortby'])) {
500 // This key already exists somewhere. Change its sortorder and bring it to the top.
501 $sortorder = $this->prefs
['sortby'][$sortcol] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
502 unset($this->prefs
['sortby'][$sortcol]);
503 $this->prefs
['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs
['sortby']);
505 // Key doesn't exist, so just add it to the beginning of the array, ascending order
506 $this->prefs
['sortby'] = array_merge(array($sortcol => SORT_ASC
), $this->prefs
['sortby']);
509 // Finally, make sure that no more than $this->maxsortkeys are present into the array
510 $this->prefs
['sortby'] = array_slice($this->prefs
['sortby'], 0, $this->maxsortkeys
);
513 // 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.
514 // This prevents results from being returned in a random order if the only order by column contains equal values.
515 if (!empty($this->sort_default_column
)) {
516 if (!array_key_exists($this->sort_default_column
, $this->prefs
['sortby'])) {
517 $defaultsort = array($this->sort_default_column
=> $this->sort_default_order
);
518 $this->prefs
['sortby'] = array_merge($this->prefs
['sortby'], $defaultsort);
522 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
523 if (!is_null($ilast) && ($ilast ==='' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
524 $this->prefs
['i_last'] = $ilast;
527 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
528 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
529 $this->prefs
['i_first'] = $ifirst;
532 // Save user preferences if they have changed.
533 if ($this->prefs
!= $oldprefs) {
534 if ($this->persistent
) {
535 set_user_preference('flextable_' . $this->uniqueid
, json_encode($this->prefs
));
537 $SESSION->flextable
[$this->uniqueid
] = $this->prefs
;
542 if (empty($this->baseurl
)) {
543 debugging('You should set baseurl when using flexible_table.');
545 $this->baseurl
= $PAGE->url
;
548 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
551 // Always introduce the "flexible" class for the table if not specified
552 if (empty($this->attributes
)) {
553 $this->attributes
['class'] = 'flexible';
554 } else if (!isset($this->attributes
['class'])) {
555 $this->attributes
['class'] = 'flexible';
556 } else if (!in_array('flexible', explode(' ', $this->attributes
['class']))) {
557 $this->attributes
['class'] = trim('flexible ' . $this->attributes
['class']);
562 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
563 * @param string $uniqueid the identifier for a table.
564 * @return SQL fragment that can be used in an ORDER BY clause.
566 public static function get_sort_for_table($uniqueid) {
568 if (isset($SESSION->flextable
[$uniqueid])) {
569 $prefs = $SESSION->flextable
[$uniqueid];
570 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
574 if (empty($prefs['sortby'])) {
577 if (empty($prefs['textsort'])) {
578 $prefs['textsort'] = array();
581 return self
::construct_order_by($prefs['sortby'], $prefs['textsort']);
585 * Prepare an an order by clause from the list of columns to be sorted.
586 * @param array $cols column name => SORT_ASC or SORT_DESC
587 * @return SQL fragment that can be used in an ORDER BY clause.
589 public static function construct_order_by($cols, $textsortcols=array()) {
593 foreach ($cols as $column => $order) {
594 if (in_array($column, $textsortcols)) {
595 $column = $DB->sql_order_by_text($column);
597 if ($order == SORT_ASC
) {
598 $bits[] = $column . ' ASC';
600 $bits[] = $column . ' DESC';
604 return implode(', ', $bits);
608 * @return SQL fragment that can be used in an ORDER BY clause.
610 public function get_sql_sort() {
611 return self
::construct_order_by($this->get_sort_columns(), $this->column_textsort
);
615 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
616 * @return array column name => SORT_... constant.
618 public function get_sort_columns() {
620 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
623 if (empty($this->prefs
['sortby'])) {
627 foreach ($this->prefs
['sortby'] as $column => $notused) {
628 if (isset($this->columns
[$column])) {
629 continue; // This column is OK.
631 if (in_array($column, get_all_user_name_fields()) &&
632 isset($this->columns
['fullname'])) {
633 continue; // This column is OK.
635 // This column is not OK.
636 unset($this->prefs
['sortby'][$column]);
639 return $this->prefs
['sortby'];
643 * @return int the offset for LIMIT clause of SQL
645 function get_page_start() {
646 if (!$this->use_pages
) {
649 return $this->currpage
* $this->pagesize
;
653 * @return int the pagesize for LIMIT clause of SQL
655 function get_page_size() {
656 if (!$this->use_pages
) {
659 return $this->pagesize
;
663 * @return string sql to add to where statement.
665 function get_sql_where() {
668 $conditions = array();
671 if (isset($this->columns
['fullname'])) {
675 if (!empty($this->prefs
['i_first'])) {
676 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
677 $params['ifirstc'.$i] = $this->prefs
['i_first'].'%';
679 if (!empty($this->prefs
['i_last'])) {
680 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
681 $params['ilastc'.$i] = $this->prefs
['i_last'].'%';
685 return array(implode(" AND ", $conditions), $params);
689 * Add a row of data to the table. This function takes an array or object with
690 * column names as keys or property names.
692 * It ignores any elements with keys that are not defined as columns. It
693 * puts in empty strings into the row when there is no element in the passed
694 * array corresponding to a column in the table. It puts the row elements in
695 * the proper order (internally row table data is stored by in arrays with
696 * a numerical index corresponding to the column number).
698 * @param object|array $rowwithkeys array keys or object property names are column names,
699 * as defined in call to define_columns.
700 * @param string $classname CSS class name to add to this row's tr tag.
702 function add_data_keyed($rowwithkeys, $classname = '') {
703 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
707 * Add a number of rows to the table at once. And optionally finish output after they have been added.
709 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
710 * object or array is added to table. We expect properties for the row array as would be
711 * passed to add_data_keyed.
712 * @param bool $finish
714 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
715 foreach ($rowstoadd as $row) {
717 $this->add_separator();
719 $this->add_data_keyed($this->format_row($row));
723 $this->finish_output(!$this->is_downloading());
728 * Add a seperator line to table.
730 function add_separator() {
734 $this->add_data(NULL);
738 * This method actually directly echoes the row passed to it now or adds it
739 * to the download. If this is the first row and start_output has not
740 * already been called this method also calls start_output to open the table
741 * or send headers for the downloaded.
742 * Can be used as before. print_html now calls finish_html to close table.
744 * @param array $row a numerically keyed row of data to add to the table.
745 * @param string $classname CSS class name to add to this row's tr tag.
746 * @return bool success.
748 function add_data($row, $classname = '') {
752 if (!$this->started_output
) {
753 $this->start_output();
755 if ($this->exportclass
!==null) {
757 $this->exportclass
->add_seperator();
759 $this->exportclass
->add_data($row);
762 $this->print_row($row, $classname);
768 * You should call this to finish outputting the table data after adding
769 * data to the table with add_data or add_data_keyed.
772 function finish_output($closeexportclassdoc = true) {
773 if ($this->exportclass
!==null) {
774 $this->exportclass
->finish_table();
775 if ($closeexportclassdoc) {
776 $this->exportclass
->finish_document();
779 $this->finish_html();
784 * Hook that can be overridden in child classes to wrap a table in a form
785 * for example. Called only when there is data to display and not
788 function wrap_html_start() {
792 * Hook that can be overridden in child classes to wrap a table in a form
793 * for example. Called only when there is data to display and not
796 function wrap_html_finish() {
800 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
801 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
802 * displaying table as html, adding a div wrap, etc.
804 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
806 * @param array|object $row row of data from db used to make one row of the table.
807 * @return array one row for the table, added using add_data_keyed method.
809 function format_row($row) {
810 if (is_array($row)) {
813 $formattedrow = array();
814 foreach (array_keys($this->columns
) as $column) {
815 $colmethodname = 'col_'.$column;
816 if (method_exists($this, $colmethodname)) {
817 $formattedcolumn = $this->$colmethodname($row);
819 $formattedcolumn = $this->other_cols($column, $row);
820 if ($formattedcolumn===NULL) {
821 $formattedcolumn = $row->$column;
824 $formattedrow[$column] = $formattedcolumn;
826 return $formattedrow;
830 * Fullname is treated as a special columname in tablelib and should always
831 * be treated the same as the fullname of a user.
832 * @uses $this->useridfield if the userid field is not expected to be id
833 * then you need to override $this->useridfield to point at the correct
834 * field for the user id.
836 * @param object $row the data from the db containing all fields from the
837 * users table necessary to construct the full name of the user in
839 * @return string contents of cell in column 'fullname', for this row.
841 function col_fullname($row) {
844 $name = fullname($row);
845 if ($this->download
) {
849 $userid = $row->{$this->useridfield
};
850 if ($COURSE->id
== SITEID
) {
851 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
853 $profileurl = new moodle_url('/user/view.php',
854 array('id' => $userid, 'course' => $COURSE->id
));
856 return html_writer
::link($profileurl, $name);
860 * You can override this method in a child class. See the description of
861 * build_table which calls this method.
863 function other_cols($column, $row) {
868 * Used from col_* functions when text is to be displayed. Does the
869 * right thing - either converts text to html or strips any html tags
870 * depending on if we are downloading and what is the download type. Params
871 * are the same as format_text function in weblib.php but some default
872 * options are changed.
874 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
875 if (!$this->is_downloading()) {
876 if (is_null($options)) {
877 $options = new stdClass
;
879 //some sensible defaults
880 if (!isset($options->para
)) {
881 $options->para
= false;
883 if (!isset($options->newlines
)) {
884 $options->newlines
= false;
886 if (!isset($options->smiley
)) {
887 $options->smiley
= false;
889 if (!isset($options->filter
)) {
890 $options->filter
= false;
892 return format_text($text, $format, $options);
894 $eci = $this->export_class_instance();
895 return $eci->format_text($text, $format, $options, $courseid);
899 * This method is deprecated although the old api is still supported.
900 * @deprecated 1.9.2 - Jun 2, 2008
902 function print_html() {
906 $this->finish_html();
910 * This function is not part of the public api.
911 * @return string initial of first name we are currently filtering by
913 function get_initial_first() {
914 if (!$this->use_initials
) {
918 return $this->prefs
['i_first'];
922 * This function is not part of the public api.
923 * @return string initial of last name we are currently filtering by
925 function get_initial_last() {
926 if (!$this->use_initials
) {
930 return $this->prefs
['i_last'];
934 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
935 * @param array $alpha of letters in the alphabet.
936 * @param string $current the currently selected letter.
937 * @param string $class class name to add to this initial bar.
938 * @param string $title the name to put in front of this initial bar.
939 * @param string $urlvar URL parameter name for this initial.
941 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
942 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
945 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
947 echo html_writer
::tag('strong', get_string('all'));
950 foreach ($alpha as $letter) {
951 if ($letter === $current) {
952 echo html_writer
::tag('strong', $letter);
954 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
958 echo html_writer
::end_tag('div');
962 * This function is not part of the public api.
964 function print_initials_bar() {
965 if ((!empty($this->prefs
['i_last']) ||
!empty($this->prefs
['i_first']) ||
$this->use_initials
)
966 && isset($this->columns
['fullname'])) {
968 $alpha = explode(',', get_string('alphabet', 'langconfig'));
970 // Bar of first initials
971 if (!empty($this->prefs
['i_first'])) {
972 $ifirst = $this->prefs
['i_first'];
976 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
977 get_string('firstname'), $this->request
[TABLE_VAR_IFIRST
]);
979 // Bar of last initials
980 if (!empty($this->prefs
['i_last'])) {
981 $ilast = $this->prefs
['i_last'];
985 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
986 get_string('lastname'), $this->request
[TABLE_VAR_ILAST
]);
991 * This function is not part of the public api.
993 function print_nothing_to_display() {
996 // Render button to allow user to reset table preferences.
997 echo $this->render_reset_button();
999 $this->print_initials_bar();
1001 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1005 * This function is not part of the public api.
1007 function get_row_from_keyed($rowwithkeys) {
1008 if (is_object($rowwithkeys)) {
1009 $rowwithkeys = (array)$rowwithkeys;
1012 foreach (array_keys($this->columns
) as $column) {
1013 if (isset($rowwithkeys[$column])) {
1014 $row [] = $rowwithkeys[$column];
1022 * This function is not part of the public api.
1024 function get_download_menu() {
1025 $allclasses= get_declared_classes();
1026 $exportclasses = array();
1027 foreach ($allclasses as $class) {
1029 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
1030 $type = $matches[1];
1031 $exportclasses[$type]= get_string("download$type", 'table');
1034 return $exportclasses;
1038 * This function is not part of the public api.
1040 function download_buttons() {
1041 if ($this->is_downloadable() && !$this->is_downloading()) {
1042 $downloadoptions = $this->get_download_menu();
1044 $downloadelements = new stdClass();
1045 $downloadelements->formatsmenu
= html_writer
::select($downloadoptions,
1046 'download', $this->defaultdownloadformat
, false);
1047 $downloadelements->downloadbutton
= '<input type="submit" value="'.
1048 get_string('download').'"/>';
1049 $html = '<form action="'. $this->baseurl
.'" method="post">';
1050 $html .= '<div class="mdl-align">';
1051 $html .= html_writer
::tag('label', get_string('downloadas', 'table', $downloadelements));
1052 $html .= '</div></form>';
1060 * This function is not part of the public api.
1061 * You don't normally need to call this. It is called automatically when
1062 * needed when you start adding data to the table.
1065 function start_output() {
1066 $this->started_output
= true;
1067 if ($this->exportclass
!==null) {
1068 $this->exportclass
->start_table($this->sheettitle
);
1069 $this->exportclass
->output_headers($this->headers
);
1071 $this->start_html();
1072 $this->print_headers();
1073 echo html_writer
::start_tag('tbody');
1078 * This function is not part of the public api.
1080 function print_row($row, $classname = '') {
1081 echo $this->get_row_html($row, $classname);
1085 * Generate html code for the passed row.
1087 * @param array $row Row data.
1088 * @param string $classname classes to add.
1090 * @return string $html html code for the row passed.
1092 public function get_row_html($row, $classname = '') {
1093 static $suppress_lastrow = NULL;
1094 $rowclasses = array();
1097 $rowclasses[] = $classname;
1100 $rowid = $this->uniqueid
. '_r' . $this->currentrow
;
1103 $html .= html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1105 // If we have a separator, print it
1106 if ($row === NULL) {
1107 $colcount = count($this->columns
);
1108 $html .= html_writer
::tag('td', html_writer
::tag('div', '',
1109 array('class' => 'tabledivider')), array('colspan' => $colcount));
1112 $colbyindex = array_flip($this->columns
);
1113 foreach ($row as $index => $data) {
1114 $column = $colbyindex[$index];
1116 if (empty($this->prefs
['collapse'][$column])) {
1117 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1118 $content = ' ';
1123 $content = ' ';
1126 $html .= html_writer
::tag('td', $content, array(
1127 'class' => 'cell c' . $index . $this->column_class
[$column],
1128 'id' => $rowid . '_c' . $index,
1129 'style' => $this->make_styles_string($this->column_style
[$column])));
1133 $html .= html_writer
::end_tag('tr');
1135 $suppress_enabled = array_sum($this->column_suppress
);
1136 if ($suppress_enabled) {
1137 $suppress_lastrow = $row;
1139 $this->currentrow++
;
1144 * This function is not part of the public api.
1146 function finish_html() {
1148 if (!$this->started_output
) {
1149 //no data has been added to the table.
1150 $this->print_nothing_to_display();
1153 // Print empty rows to fill the table to the current pagesize.
1154 // This is done so the header aria-controls attributes do not point to
1155 // non existant elements.
1156 $emptyrow = array_fill(0, count($this->columns
), '');
1157 while ($this->currentrow
< $this->pagesize
) {
1158 $this->print_row($emptyrow, 'emptyrow');
1161 echo html_writer
::end_tag('tbody');
1162 echo html_writer
::end_tag('table');
1163 echo html_writer
::end_tag('div');
1164 $this->wrap_html_finish();
1167 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1168 echo $this->download_buttons();
1171 if($this->use_pages
) {
1172 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1173 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1174 echo $OUTPUT->render($pagingbar);
1180 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1181 * used by {@link print_headers()}.
1182 * @param string $column the column name, index into various names.
1183 * @param int $index numerical index of the column.
1184 * @return string HTML fragment.
1186 protected function show_hide_link($column, $index) {
1188 // Some headers contain <br /> tags, do not include in title, hence the
1192 for ($i = 0; $i < $this->pagesize
; $i++
) {
1193 $ariacontrols .= $this->uniqueid
. '_r' . $i . '_c' . $index . ' ';
1196 $ariacontrols = trim($ariacontrols);
1198 if (!empty($this->prefs
['collapse'][$column])) {
1199 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index]),
1200 'aria-expanded' => 'false',
1201 'aria-controls' => $ariacontrols);
1202 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1203 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1206 } else if ($this->headers
[$index] !== NULL) {
1207 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index]),
1208 'aria-expanded' => 'true',
1209 'aria-controls' => $ariacontrols);
1210 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1211 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1217 * This function is not part of the public api.
1219 function print_headers() {
1220 global $CFG, $OUTPUT;
1222 echo html_writer
::start_tag('thead');
1223 echo html_writer
::start_tag('tr');
1224 foreach ($this->columns
as $column => $index) {
1227 if ($this->is_collapsible
) {
1228 $icon_hide = $this->show_hide_link($column, $index);
1231 $primarysortcolumn = '';
1232 $primarysortorder = '';
1233 if (reset($this->prefs
['sortby'])) {
1234 $primarysortcolumn = key($this->prefs
['sortby']);
1235 $primarysortorder = current($this->prefs
['sortby']);
1241 // Check the full name display for sortable fields.
1242 $nameformat = $CFG->fullnamedisplay
;
1243 if ($nameformat == 'language') {
1244 $nameformat = get_string('fullnamedisplay');
1246 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1248 if (!empty($requirednames)) {
1249 if ($this->is_sortable($column)) {
1250 // Done this way for the possibility of more than two sortable full name display fields.
1251 $this->headers
[$index] = '';
1252 foreach ($requirednames as $name) {
1253 $sortname = $this->sort_link(get_string($name),
1254 $name, $primarysortcolumn === $name, $primarysortorder);
1255 $this->headers
[$index] .= $sortname . ' / ';
1258 if (isset($this->helpforheaders
[$index])) {
1259 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1261 $this->headers
[$index] = substr($this->headers
[$index], 0, -3). $helpicon;
1267 // do nothing, do not display sortable links
1271 if ($this->is_sortable($column)) {
1273 if (isset($this->helpforheaders
[$index])) {
1274 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1276 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1277 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1281 $attributes = array(
1282 'class' => 'header c' . $index . $this->column_class
[$column],
1285 if ($this->headers
[$index] === NULL) {
1286 $content = ' ';
1287 } else if (!empty($this->prefs
['collapse'][$column])) {
1288 $content = $icon_hide;
1290 if (is_array($this->column_style
[$column])) {
1291 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1294 if (isset($this->helpforheaders
[$index]) && !$this->is_sortable($column)) {
1295 $helpicon = $OUTPUT->render($this->helpforheaders
[$index]);
1297 $content = $this->headers
[$index] . $helpicon . html_writer
::tag('div',
1298 $icon_hide, array('class' => 'commands'));
1300 echo html_writer
::tag('th', $content, $attributes);
1303 echo html_writer
::end_tag('tr');
1304 echo html_writer
::end_tag('thead');
1308 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1309 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1310 * @param int $order SORT_ASC or SORT_DESC
1311 * @return string HTML fragment.
1313 protected function sort_icon($isprimary, $order) {
1320 if ($order == SORT_ASC
) {
1321 return html_writer
::empty_tag('img',
1322 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1324 return html_writer
::empty_tag('img',
1325 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1330 * Generate the correct tool tip for changing the sort order. This is a
1331 * helper method used by {@link sort_link()}.
1332 * @param bool $isprimary whether the is column is the current primary sort column.
1333 * @param int $order SORT_ASC or SORT_DESC
1334 * @return string the correct title.
1336 protected function sort_order_name($isprimary, $order) {
1337 if ($isprimary && $order != SORT_ASC
) {
1338 return get_string('desc');
1340 return get_string('asc');
1345 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1346 * @param string $text the text for the link.
1347 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1348 * @param bool $isprimary whether the is column is the current primary sort column.
1349 * @param int $order SORT_ASC or SORT_DESC
1350 * @return string HTML fragment.
1352 protected function sort_link($text, $column, $isprimary, $order) {
1353 return html_writer
::link($this->baseurl
->out(false,
1354 array($this->request
[TABLE_VAR_SORT
] => $column)),
1355 $text . get_accesshide(get_string('sortby') . ' ' .
1356 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1357 $this->sort_icon($isprimary, $order);
1361 * This function is not part of the public api.
1363 function start_html() {
1366 // Render button to allow user to reset table preferences.
1367 echo $this->render_reset_button();
1369 // Do we need to print initial bars?
1370 $this->print_initials_bar();
1373 if ($this->use_pages
) {
1374 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1375 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1376 echo $OUTPUT->render($pagingbar);
1379 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1380 echo $this->download_buttons();
1383 $this->wrap_html_start();
1384 // Start of main data table
1386 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1387 echo html_writer
::start_tag('table', $this->attributes
);
1392 * This function is not part of the public api.
1393 * @param array $styles CSS-property => value
1394 * @return string values suitably to go in a style="" attribute in HTML.
1396 function make_styles_string($styles) {
1397 if (empty($styles)) {
1402 foreach($styles as $property => $value) {
1403 $string .= $property . ':' . $value . ';';
1409 * Generate the HTML for the table preferences reset button.
1411 * @return string HTML fragment, empty string if no need to reset
1413 protected function render_reset_button() {
1415 if (!$this->can_be_reset()) {
1419 $url = $this->baseurl
->out(false, array($this->request
[TABLE_VAR_RESET
] => 1));
1421 $html = html_writer
::start_div('resettable mdl-right');
1422 $html .= html_writer
::link($url, get_string('resettable'));
1423 $html .= html_writer
::end_div();
1429 * Are there some table preferences that can be reset?
1431 * If true, then the "reset table preferences" widget should be displayed.
1435 protected function can_be_reset() {
1437 // Loop through preferences and make sure they are empty or set to the default value.
1438 foreach ($this->prefs
as $prefname => $prefval) {
1440 if ($prefname === 'sortby' and !empty($this->sort_default_column
)) {
1441 // Check if the actual sorting differs from the default one.
1442 if (empty($prefval) or $prefval !== array($this->sort_default_column
=> $this->sort_default_order
)) {
1446 } else if ($prefname === 'collapse' and !empty($prefval)) {
1447 // Check if there are some collapsed columns (all are expanded by default).
1448 foreach ($prefval as $columnname => $iscollapsed) {
1454 } else if (!empty($prefval)) {
1455 // For all other cases, we just check if some preference is set.
1466 * @package moodlecore
1467 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1470 class table_sql
extends flexible_table
{
1472 public $countsql = NULL;
1473 public $countparams = NULL;
1475 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1479 * @var array|\Traversable Data fetched from the db.
1481 public $rawdata = NULL;
1484 * @var bool Overriding default for this.
1486 public $is_sortable = true;
1488 * @var bool Overriding default for this.
1490 public $is_collapsible = true;
1493 * @param string $uniqueid a string identifying this table.Used as a key in
1496 function __construct($uniqueid) {
1497 parent
::__construct($uniqueid);
1498 // some sensible defaults
1499 $this->set_attribute('cellspacing', '0');
1500 $this->set_attribute('class', 'generaltable generalbox');
1504 * Take the data returned from the db_query and go through all the rows
1505 * processing each col using either col_{columnname} method or other_cols
1506 * method or if other_cols returns NULL then put the data straight into the
1511 function build_table() {
1513 if ($this->rawdata
instanceof \Traversable
&& !$this->rawdata
->valid()) {
1516 if (!$this->rawdata
) {
1520 foreach ($this->rawdata
as $row) {
1521 $formattedrow = $this->format_row($row);
1522 $this->add_data_keyed($formattedrow,
1523 $this->get_row_class($row));
1526 if ($this->rawdata
instanceof \core\dml\recordset_walk ||
1527 $this->rawdata
instanceof moodle_recordset
) {
1528 $this->rawdata
->close();
1533 * Get any extra classes names to add to this row in the HTML.
1534 * @param $row array the data for this row.
1535 * @return string added to the class="" attribute of the tr.
1537 function get_row_class($row) {
1542 * This is only needed if you want to use different sql to count rows.
1543 * Used for example when perhaps all db JOINS are not needed when counting
1544 * records. You don't need to call this function the count_sql
1545 * will be generated automatically.
1547 * We need to count rows returned by the db seperately to the query itself
1548 * as we need to know how many pages of data we have to display.
1550 function set_count_sql($sql, array $params = NULL) {
1551 $this->countsql
= $sql;
1552 $this->countparams
= $params;
1556 * Set the sql to query the db. Query will be :
1557 * SELECT $fields FROM $from WHERE $where
1558 * Of course you can use sub-queries, JOINS etc. by putting them in the
1559 * appropriate clause of the query.
1561 function set_sql($fields, $from, $where, array $params = NULL) {
1562 $this->sql
= new stdClass();
1563 $this->sql
->fields
= $fields;
1564 $this->sql
->from
= $from;
1565 $this->sql
->where
= $where;
1566 $this->sql
->params
= $params;
1570 * Query the db. Store results in the table object for use by build_table.
1572 * @param int $pagesize size of page for paginated displayed table.
1573 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1574 * will only be used if there is a fullname column defined for the table.
1576 function query_db($pagesize, $useinitialsbar=true) {
1578 if (!$this->is_downloading()) {
1579 if ($this->countsql
=== NULL) {
1580 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1581 $this->countparams
= $this->sql
->params
;
1583 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1584 if ($useinitialsbar && !$this->is_downloading()) {
1585 $this->initialbars($grandtotal > $pagesize);
1588 list($wsql, $wparams) = $this->get_sql_where();
1590 $this->countsql
.= ' AND '.$wsql;
1591 $this->countparams
= array_merge($this->countparams
, $wparams);
1593 $this->sql
->where
.= ' AND '.$wsql;
1594 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1596 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1598 $total = $grandtotal;
1601 $this->pagesize($pagesize, $total);
1604 // Fetch the attempts
1605 $sort = $this->get_sql_sort();
1607 $sort = "ORDER BY $sort";
1610 {$this->sql->fields}
1611 FROM {$this->sql->from}
1612 WHERE {$this->sql->where}
1615 if (!$this->is_downloading()) {
1616 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
1618 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
1623 * Convenience method to call a number of methods for you to display the
1626 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1628 if (!$this->columns
) {
1629 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql
->params
);
1630 //if columns is not set then define columns as the keys of the rows returned
1632 $this->define_columns(array_keys((array)$onerow));
1633 $this->define_headers(array_keys((array)$onerow));
1636 $this->query_db($pagesize, $useinitialsbar);
1637 $this->build_table();
1638 $this->finish_output();
1644 * @package moodlecore
1645 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1648 class table_default_export_format_parent
{
1650 * @var flexible_table or child class reference pointing to table class
1651 * object from which to export data.
1656 * @var bool output started. Keeps track of whether any output has been
1659 var $documentstarted = false;
1664 * @param flexible_table $table
1666 public function __construct(&$table) {
1667 $this->table
=& $table;
1671 * Old syntax of class constructor for backward compatibility.
1673 public function table_default_export_format_parent(&$table) {
1674 self
::__construct($table);
1677 function set_table(&$table) {
1678 $this->table
=& $table;
1681 function add_data($row) {
1685 function add_seperator() {
1689 function document_started() {
1690 return $this->documentstarted
;
1693 * Given text in a variety of format codings, this function returns
1694 * the text as safe HTML or as plain text dependent on what is appropriate
1695 * for the download format. The default removes all tags.
1697 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1698 //use some whitespace to indicate where there was some line spacing.
1699 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1700 return strip_tags($text);
1706 * @package moodlecore
1707 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1710 class table_spreadsheet_export_format_parent
extends table_default_export_format_parent
{
1715 * @var object format object - format for normal table cells
1719 * @var object format object - format for header table cells
1724 * should be overriden in child class.
1729 * This method will be overridden in the child class.
1731 function define_workbook() {
1734 function start_document($filename) {
1735 $filename = $filename.'.'.$this->fileextension
;
1736 $this->define_workbook();
1738 $this->formatnormal
= $this->workbook
->add_format();
1739 $this->formatnormal
->set_bold(0);
1740 $this->formatheaders
= $this->workbook
->add_format();
1741 $this->formatheaders
->set_bold(1);
1742 $this->formatheaders
->set_align('center');
1743 // Sending HTTP headers
1744 $this->workbook
->send($filename);
1745 $this->documentstarted
= true;
1748 function start_table($sheettitle) {
1749 $this->worksheet
= $this->workbook
->add_worksheet($sheettitle);
1750 $this->currentrow
=0;
1753 function output_headers($headers) {
1755 foreach ($headers as $item) {
1756 $this->worksheet
->write($this->currentrow
,$colnum,$item,$this->formatheaders
);
1759 $this->currentrow++
;
1762 function add_data($row) {
1764 foreach ($row as $item) {
1765 $this->worksheet
->write($this->currentrow
,$colnum,$item,$this->formatnormal
);
1768 $this->currentrow++
;
1772 function add_seperator() {
1773 $this->currentrow++
;
1777 function finish_table() {
1780 function finish_document() {
1781 $this->workbook
->close();
1788 * @package moodlecore
1789 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1792 class table_excel_export_format
extends table_spreadsheet_export_format_parent
{
1793 var $fileextension = 'xls';
1795 function define_workbook() {
1797 require_once("$CFG->libdir/excellib.class.php");
1798 // Creating a workbook
1799 $this->workbook
= new MoodleExcelWorkbook("-");
1806 * @package moodlecore
1807 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1810 class table_ods_export_format
extends table_spreadsheet_export_format_parent
{
1811 var $fileextension = 'ods';
1812 function define_workbook() {
1814 require_once("$CFG->libdir/odslib.class.php");
1815 // Creating a workbook
1816 $this->workbook
= new MoodleODSWorkbook("-");
1822 * @package moodlecore
1823 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1826 class table_text_export_format_parent
extends table_default_export_format_parent
{
1827 protected $seperator = "tab";
1828 protected $mimetype = 'text/tab-separated-values';
1829 protected $ext = '.txt';
1830 protected $myexporter;
1832 public function __construct() {
1833 $this->myexporter
= new csv_export_writer($this->seperator
, '"', $this->mimetype
);
1836 public function start_document($filename) {
1837 $this->filename
= $filename;
1838 $this->documentstarted
= true;
1839 $this->myexporter
->set_filename($filename, $this->ext
);
1842 public function start_table($sheettitle) {
1843 //nothing to do here
1846 public function output_headers($headers) {
1847 $this->myexporter
->add_data($headers);
1850 public function add_data($row) {
1851 $this->myexporter
->add_data($row);
1855 public function finish_table() {
1856 //nothing to do here
1859 public function finish_document() {
1860 $this->myexporter
->download_file();
1865 * Format a row of data.
1866 * @param array $data
1868 protected function format_row($data) {
1869 $escapeddata = array();
1870 foreach ($data as $value) {
1871 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1873 return implode($this->seperator
, $escapeddata) . "\n";
1879 * @package moodlecore
1880 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1881 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1883 class table_tsv_export_format
extends table_text_export_format_parent
{
1884 protected $seperator = "tab";
1885 protected $mimetype = 'text/tab-separated-values';
1886 protected $ext = '.txt';
1889 require_once($CFG->libdir
. '/csvlib.class.php');
1891 * @package moodlecore
1892 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1893 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1895 class table_csv_export_format
extends table_text_export_format_parent
{
1896 protected $seperator = "comma";
1897 protected $mimetype = 'text/csv';
1898 protected $ext = '.csv';
1902 * @package moodlecore
1903 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1904 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1906 class table_xhtml_export_format
extends table_default_export_format_parent
{
1907 function start_document($filename) {
1908 header("Content-Type: application/download\n");
1909 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1910 header("Expires: 0");
1911 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1912 header("Pragma: public");
1915 <?xml version="1.0" encoding="UTF-8"?>
1917 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1918 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1920 <html xmlns="http://www.w3.org/1999/xhtml"
1921 xml:lang="en" lang="en">
1923 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1924 <style type="text/css">/*<![CDATA[*/
1929 th.header, td.header, div.header {
1930 border-color:#DDDDDD;
1931 background-color:lightGrey;
1946 body, table, td, th {
1947 font-family:Arial,Verdana,Helvetica,sans-serif;
1955 border-collapse:collapse;
1971 <title>$filename</title>
1975 $this->documentstarted
= true;
1978 function start_table($sheettitle) {
1979 $this->table
->sortable(false);
1980 $this->table
->collapsible(false);
1981 echo "<h2>{$sheettitle}</h2>";
1982 $this->table
->start_html();
1985 function output_headers($headers) {
1986 $this->table
->print_headers();
1987 echo html_writer
::start_tag('tbody');
1990 function add_data($row) {
1991 $this->table
->print_row($row);
1995 function add_seperator() {
1996 $this->table
->print_row(NULL);
2000 function finish_table() {
2001 $this->table
->finish_html();
2004 function finish_document() {
2005 echo "</body>\n</html>";
2009 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
2010 if (is_null($options)) {
2011 $options = new stdClass
;
2013 //some sensible defaults
2014 if (!isset($options->para
)) {
2015 $options->para
= false;
2017 if (!isset($options->newlines
)) {
2018 $options->newlines
= false;
2020 if (!isset($options->smiley
)) {
2021 $options->smiley
= false;
2023 if (!isset($options->filter
)) {
2024 $options->filter
= false;
2026 return format_text($text, $format, $options);