Merge branch 'MDL-48202-M30' of git://github.com/lazydaisy/moodle
[moodle.git] / lib / tablelib.php
blob39afa90c2e43a375cfc706d3e4f597853ae7cd5f
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 define('TABLE_VAR_RESET', 7);
38 /**#@-*/
40 /**#@+
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);
46 /**#@-*/
49 /**
50 * @package moodlecore
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 {
56 var $uniqueid = NULL;
57 var $attributes = array();
58 var $headers = array();
59 var $columns = array();
60 var $column_style = array();
61 var $column_class = array();
62 var $column_suppress = array();
63 var $column_nosort = array('userpic');
64 private $column_textsort = array();
65 var $setup = false;
66 var $baseurl = NULL;
67 var $request = array();
69 /**
70 * @var bool Whether or not to store table properties in the user_preferences table.
72 private $persistent = false;
73 var $is_collapsible = false;
74 var $is_sortable = false;
75 var $use_pages = false;
76 var $use_initials = false;
78 var $maxsortkeys = 2;
79 var $pagesize = 30;
80 var $currpage = 0;
81 var $totalrows = 0;
82 var $currentrow = 0;
83 var $sort_default_column = NULL;
84 var $sort_default_order = SORT_ASC;
86 /**
87 * Array of positions in which to display download controls.
89 var $showdownloadbuttonsat= array(TABLE_P_TOP);
91 /**
92 * @var string Key of field returned by db query that is the id field of the
93 * user table or equivalent.
95 public $useridfield = 'id';
97 /**
98 * @var string which download plugin to use. Default '' means none - print
99 * html table with paging. Property set by is_downloading which typically
100 * passes in cleaned data from $
102 var $download = '';
105 * @var bool whether data is downloadable from table. Determines whether
106 * to display download buttons. Set by method downloadable().
108 var $downloadable = false;
111 * @var string which download plugin to use. Default '' means none - print
112 * html table with paging.
114 var $defaultdownloadformat = 'csv';
117 * @var bool Has start output been called yet?
119 var $started_output = false;
121 var $exportclass = null;
124 * @var array For storing user-customised table properties in the user_preferences db table.
126 private $prefs = array();
129 * Constructor
130 * @param int $uniqueid all tables have to have a unique id, this is used
131 * as a key when storing table properties like sort order in the session.
133 function __construct($uniqueid) {
134 $this->uniqueid = $uniqueid;
135 $this->request = array(
136 TABLE_VAR_SORT => 'tsort',
137 TABLE_VAR_HIDE => 'thide',
138 TABLE_VAR_SHOW => 'tshow',
139 TABLE_VAR_IFIRST => 'tifirst',
140 TABLE_VAR_ILAST => 'tilast',
141 TABLE_VAR_PAGE => 'page',
142 TABLE_VAR_RESET => 'treset'
147 * Call this to pass the download type. Use :
148 * $download = optional_param('download', '', PARAM_ALPHA);
149 * To get the download type. We assume that if you call this function with
150 * params that this table's data is downloadable, so we call is_downloadable
151 * for you (even if the param is '', which means no download this time.
152 * Also you can call this method with no params to get the current set
153 * download type.
154 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
155 * @param string $filename filename for downloads without file extension.
156 * @param string $sheettitle title for downloaded data.
157 * @return string download type. One of csv, tsv, xhtml, ods, etc
159 function is_downloading($download = null, $filename='', $sheettitle='') {
160 if ($download!==null) {
161 $this->sheettitle = $sheettitle;
162 $this->is_downloadable(true);
163 $this->download = $download;
164 $this->filename = clean_filename($filename);
165 $this->export_class_instance();
167 return $this->download;
171 * Get, and optionally set, the export class.
172 * @param $exportclass (optional) if passed, set the table to use this export class.
173 * @return table_default_export_format_parent the export class in use (after any set).
175 function export_class_instance($exportclass = null) {
176 if (!is_null($exportclass)) {
177 $this->started_output = true;
178 $this->exportclass = $exportclass;
179 $this->exportclass->table = $this;
180 } else if (is_null($this->exportclass) && !empty($this->download)) {
181 $classname = 'table_'.$this->download.'_export_format';
182 $this->exportclass = new $classname($this);
183 if (!$this->exportclass->document_started()) {
184 $this->exportclass->start_document($this->filename);
187 return $this->exportclass;
191 * Probably don't need to call this directly. Calling is_downloading with a
192 * param automatically sets table as downloadable.
194 * @param bool $downloadable optional param to set whether data from
195 * table is downloadable. If ommitted this function can be used to get
196 * current state of table.
197 * @return bool whether table data is set to be downloadable.
199 function is_downloadable($downloadable = null) {
200 if ($downloadable !== null) {
201 $this->downloadable = $downloadable;
203 return $this->downloadable;
207 * Call with boolean true to store table layout changes in the user_preferences table.
208 * Note: user_preferences.value has a maximum length of 1333 characters.
209 * Call with no parameter to get current state of table persistence.
211 * @param bool $persistent Optional parameter to set table layout persistence.
212 * @return bool Whether or not the table layout preferences will persist.
214 public function is_persistent($persistent = null) {
215 if ($persistent == true) {
216 $this->persistent = true;
218 return $this->persistent;
222 * Where to show download buttons.
223 * @param array $showat array of postions in which to show download buttons.
224 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
226 function show_download_buttons_at($showat) {
227 $this->showdownloadbuttonsat = $showat;
231 * Sets the is_sortable variable to the given boolean, sort_default_column to
232 * the given string, and the sort_default_order to the given integer.
233 * @param bool $bool
234 * @param string $defaultcolumn
235 * @param int $defaultorder
236 * @return void
238 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
239 $this->is_sortable = $bool;
240 $this->sort_default_column = $defaultcolumn;
241 $this->sort_default_order = $defaultorder;
245 * Use text sorting functions for this column (required for text columns with Oracle).
246 * Be warned that you cannot use this with column aliases. You can only do this
247 * with real columns. See MDL-40481 for an example.
248 * @param string column name
250 function text_sorting($column) {
251 $this->column_textsort[] = $column;
255 * Do not sort using this column
256 * @param string column name
258 function no_sorting($column) {
259 $this->column_nosort[] = $column;
263 * Is the column sortable?
264 * @param string column name, null means table
265 * @return bool
267 function is_sortable($column = null) {
268 if (empty($column)) {
269 return $this->is_sortable;
271 if (!$this->is_sortable) {
272 return false;
274 return !in_array($column, $this->column_nosort);
278 * Sets the is_collapsible variable to the given boolean.
279 * @param bool $bool
280 * @return void
282 function collapsible($bool) {
283 $this->is_collapsible = $bool;
287 * Sets the use_pages variable to the given boolean.
288 * @param bool $bool
289 * @return void
291 function pageable($bool) {
292 $this->use_pages = $bool;
296 * Sets the use_initials variable to the given boolean.
297 * @param bool $bool
298 * @return void
300 function initialbars($bool) {
301 $this->use_initials = $bool;
305 * Sets the pagesize variable to the given integer, the totalrows variable
306 * to the given integer, and the use_pages variable to true.
307 * @param int $perpage
308 * @param int $total
309 * @return void
311 function pagesize($perpage, $total) {
312 $this->pagesize = $perpage;
313 $this->totalrows = $total;
314 $this->use_pages = true;
318 * Assigns each given variable in the array to the corresponding index
319 * in the request class variable.
320 * @param array $variables
321 * @return void
323 function set_control_variables($variables) {
324 foreach ($variables as $what => $variable) {
325 if (isset($this->request[$what])) {
326 $this->request[$what] = $variable;
332 * Gives the given $value to the $attribute index of $this->attributes.
333 * @param string $attribute
334 * @param mixed $value
335 * @return void
337 function set_attribute($attribute, $value) {
338 $this->attributes[$attribute] = $value;
342 * What this method does is set the column so that if the same data appears in
343 * consecutive rows, then it is not repeated.
345 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
346 * that when one student has made multiple attempts, their name is only printed in the row
347 * for their first attempt.
348 * @param int $column the index of a column.
350 function column_suppress($column) {
351 if (isset($this->column_suppress[$column])) {
352 $this->column_suppress[$column] = true;
357 * Sets the given $column index to the given $classname in $this->column_class.
358 * @param int $column
359 * @param string $classname
360 * @return void
362 function column_class($column, $classname) {
363 if (isset($this->column_class[$column])) {
364 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
369 * Sets the given $column index and $property index to the given $value in $this->column_style.
370 * @param int $column
371 * @param string $property
372 * @param mixed $value
373 * @return void
375 function column_style($column, $property, $value) {
376 if (isset($this->column_style[$column])) {
377 $this->column_style[$column][$property] = $value;
382 * Sets all columns' $propertys to the given $value in $this->column_style.
383 * @param int $property
384 * @param string $value
385 * @return void
387 function column_style_all($property, $value) {
388 foreach (array_keys($this->columns) as $column) {
389 $this->column_style[$column][$property] = $value;
394 * Sets $this->baseurl.
395 * @param moodle_url|string $url the url with params needed to call up this page
397 function define_baseurl($url) {
398 $this->baseurl = new moodle_url($url);
402 * @param array $columns an array of identifying names for columns. If
403 * columns are sorted then column names must correspond to a field in sql.
405 function define_columns($columns) {
406 $this->columns = array();
407 $this->column_style = array();
408 $this->column_class = array();
409 $colnum = 0;
411 foreach ($columns as $column) {
412 $this->columns[$column] = $colnum++;
413 $this->column_style[$column] = array();
414 $this->column_class[$column] = '';
415 $this->column_suppress[$column] = false;
420 * @param array $headers numerical keyed array of displayed string titles
421 * for each column.
423 function define_headers($headers) {
424 $this->headers = $headers;
428 * Must be called after table is defined. Use methods above first. Cannot
429 * use functions below till after calling this method.
430 * @return type?
432 function setup() {
433 global $SESSION;
435 if (empty($this->columns) || empty($this->uniqueid)) {
436 return false;
439 // Load any existing user preferences.
440 if ($this->persistent) {
441 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
442 } else if (isset($SESSION->flextable[$this->uniqueid])) {
443 $this->prefs = $SESSION->flextable[$this->uniqueid];
445 if (!$this->prefs) {
446 $this->prefs = array(
447 'collapse' => array(),
448 'sortby' => array(),
449 'i_first' => '',
450 'i_last' => '',
451 'textsort' => $this->column_textsort,
454 $oldprefs = $this->prefs;
456 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
457 isset($this->columns[$showcol])) {
458 $this->prefs['collapse'][$showcol] = false;
460 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
461 isset($this->columns[$hidecol])) {
462 $this->prefs['collapse'][$hidecol] = true;
463 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
464 unset($this->prefs['sortby'][$hidecol]);
468 // Now, update the column attributes for collapsed columns
469 foreach (array_keys($this->columns) as $column) {
470 if (!empty($this->prefs['collapse'][$column])) {
471 $this->column_style[$column]['width'] = '10px';
475 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
476 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
477 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
478 && isset($this->columns['fullname']))) {
480 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
481 // This key already exists somewhere. Change its sortorder and bring it to the top.
482 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
483 unset($this->prefs['sortby'][$sortcol]);
484 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
485 } else {
486 // Key doesn't exist, so just add it to the beginning of the array, ascending order
487 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
490 // Finally, make sure that no more than $this->maxsortkeys are present into the array
491 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
494 // 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.
495 // This prevents results from being returned in a random order if the only order by column contains equal values.
496 if (!empty($this->sort_default_column)) {
497 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
498 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
499 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
503 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
504 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
505 $this->prefs['i_last'] = $ilast;
508 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
509 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
510 $this->prefs['i_first'] = $ifirst;
513 // Allow user to reset table preferences.
514 if (optional_param($this->request[TABLE_VAR_RESET], 0, PARAM_BOOL) === 1) {
515 $this->prefs = array(
516 'collapse' => array(),
517 'sortby' => array(),
518 'i_first' => '',
519 'i_last' => '',
520 'textsort' => $this->column_textsort,
524 // Save user preferences if they have changed.
525 if ($this->prefs != $oldprefs) {
526 if ($this->persistent) {
527 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
528 } else {
529 $SESSION->flextable[$this->uniqueid] = $this->prefs;
532 unset($oldprefs);
534 if (empty($this->baseurl)) {
535 debugging('You should set baseurl when using flexible_table.');
536 global $PAGE;
537 $this->baseurl = $PAGE->url;
540 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
541 $this->setup = true;
543 // Always introduce the "flexible" class for the table if not specified
544 if (empty($this->attributes)) {
545 $this->attributes['class'] = 'flexible';
546 } else if (!isset($this->attributes['class'])) {
547 $this->attributes['class'] = 'flexible';
548 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
549 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
554 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
555 * @param string $uniqueid the identifier for a table.
556 * @return SQL fragment that can be used in an ORDER BY clause.
558 public static function get_sort_for_table($uniqueid) {
559 global $SESSION;
560 if (isset($SESSION->flextable[$uniqueid])) {
561 $prefs = $SESSION->flextable[$uniqueid];
562 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
563 return '';
566 if (empty($prefs['sortby'])) {
567 return '';
569 if (empty($prefs['textsort'])) {
570 $prefs['textsort'] = array();
573 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
577 * Prepare an an order by clause from the list of columns to be sorted.
578 * @param array $cols column name => SORT_ASC or SORT_DESC
579 * @return SQL fragment that can be used in an ORDER BY clause.
581 public static function construct_order_by($cols, $textsortcols=array()) {
582 global $DB;
583 $bits = array();
585 foreach ($cols as $column => $order) {
586 if (in_array($column, $textsortcols)) {
587 $column = $DB->sql_order_by_text($column);
589 if ($order == SORT_ASC) {
590 $bits[] = $column . ' ASC';
591 } else {
592 $bits[] = $column . ' DESC';
596 return implode(', ', $bits);
600 * @return SQL fragment that can be used in an ORDER BY clause.
602 public function get_sql_sort() {
603 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
607 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
608 * @return array column name => SORT_... constant.
610 public function get_sort_columns() {
611 if (!$this->setup) {
612 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
615 if (empty($this->prefs['sortby'])) {
616 return array();
619 foreach ($this->prefs['sortby'] as $column => $notused) {
620 if (isset($this->columns[$column])) {
621 continue; // This column is OK.
623 if (in_array($column, get_all_user_name_fields()) &&
624 isset($this->columns['fullname'])) {
625 continue; // This column is OK.
627 // This column is not OK.
628 unset($this->prefs['sortby'][$column]);
631 return $this->prefs['sortby'];
635 * @return int the offset for LIMIT clause of SQL
637 function get_page_start() {
638 if (!$this->use_pages) {
639 return '';
641 return $this->currpage * $this->pagesize;
645 * @return int the pagesize for LIMIT clause of SQL
647 function get_page_size() {
648 if (!$this->use_pages) {
649 return '';
651 return $this->pagesize;
655 * @return string sql to add to where statement.
657 function get_sql_where() {
658 global $DB;
660 $conditions = array();
661 $params = array();
663 if (isset($this->columns['fullname'])) {
664 static $i = 0;
665 $i++;
667 if (!empty($this->prefs['i_first'])) {
668 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
669 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
671 if (!empty($this->prefs['i_last'])) {
672 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
673 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
677 return array(implode(" AND ", $conditions), $params);
681 * Add a row of data to the table. This function takes an array or object with
682 * column names as keys or property names.
684 * It ignores any elements with keys that are not defined as columns. It
685 * puts in empty strings into the row when there is no element in the passed
686 * array corresponding to a column in the table. It puts the row elements in
687 * the proper order (internally row table data is stored by in arrays with
688 * a numerical index corresponding to the column number).
690 * @param object|array $rowwithkeys array keys or object property names are column names,
691 * as defined in call to define_columns.
692 * @param string $classname CSS class name to add to this row's tr tag.
694 function add_data_keyed($rowwithkeys, $classname = '') {
695 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
699 * Add a number of rows to the table at once. And optionally finish output after they have been added.
701 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
702 * object or array is added to table. We expect properties for the row array as would be
703 * passed to add_data_keyed.
704 * @param bool $finish
706 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
707 foreach ($rowstoadd as $row) {
708 if (is_null($row)) {
709 $this->add_separator();
710 } else {
711 $this->add_data_keyed($this->format_row($row));
714 if ($finish) {
715 $this->finish_output(!$this->is_downloading());
720 * Add a seperator line to table.
722 function add_separator() {
723 if (!$this->setup) {
724 return false;
726 $this->add_data(NULL);
730 * This method actually directly echoes the row passed to it now or adds it
731 * to the download. If this is the first row and start_output has not
732 * already been called this method also calls start_output to open the table
733 * or send headers for the downloaded.
734 * Can be used as before. print_html now calls finish_html to close table.
736 * @param array $row a numerically keyed row of data to add to the table.
737 * @param string $classname CSS class name to add to this row's tr tag.
738 * @return bool success.
740 function add_data($row, $classname = '') {
741 if (!$this->setup) {
742 return false;
744 if (!$this->started_output) {
745 $this->start_output();
747 if ($this->exportclass!==null) {
748 if ($row === null) {
749 $this->exportclass->add_seperator();
750 } else {
751 $this->exportclass->add_data($row);
753 } else {
754 $this->print_row($row, $classname);
756 return true;
760 * You should call this to finish outputting the table data after adding
761 * data to the table with add_data or add_data_keyed.
764 function finish_output($closeexportclassdoc = true) {
765 if ($this->exportclass!==null) {
766 $this->exportclass->finish_table();
767 if ($closeexportclassdoc) {
768 $this->exportclass->finish_document();
770 } else {
771 $this->finish_html();
776 * Hook that can be overridden in child classes to wrap a table in a form
777 * for example. Called only when there is data to display and not
778 * downloading.
780 function wrap_html_start() {
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
786 * downloading.
788 function wrap_html_finish() {
792 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
793 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
794 * displaying table as html, adding a div wrap, etc.
796 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
798 * @param array|object $row row of data from db used to make one row of the table.
799 * @return array one row for the table, added using add_data_keyed method.
801 function format_row($row) {
802 if (is_array($row)) {
803 $row = (object)$row;
805 $formattedrow = array();
806 foreach (array_keys($this->columns) as $column) {
807 $colmethodname = 'col_'.$column;
808 if (method_exists($this, $colmethodname)) {
809 $formattedcolumn = $this->$colmethodname($row);
810 } else {
811 $formattedcolumn = $this->other_cols($column, $row);
812 if ($formattedcolumn===NULL) {
813 $formattedcolumn = $row->$column;
816 $formattedrow[$column] = $formattedcolumn;
818 return $formattedrow;
822 * Fullname is treated as a special columname in tablelib and should always
823 * be treated the same as the fullname of a user.
824 * @uses $this->useridfield if the userid field is not expected to be id
825 * then you need to override $this->useridfield to point at the correct
826 * field for the user id.
828 * @param object $row the data from the db containing all fields from the
829 * users table necessary to construct the full name of the user in
830 * current language.
831 * @return string contents of cell in column 'fullname', for this row.
833 function col_fullname($row) {
834 global $COURSE;
836 $name = fullname($row);
837 if ($this->download) {
838 return $name;
841 $userid = $row->{$this->useridfield};
842 if ($COURSE->id == SITEID) {
843 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
844 } else {
845 $profileurl = new moodle_url('/user/view.php',
846 array('id' => $userid, 'course' => $COURSE->id));
848 return html_writer::link($profileurl, $name);
852 * You can override this method in a child class. See the description of
853 * build_table which calls this method.
855 function other_cols($column, $row) {
856 return NULL;
860 * Used from col_* functions when text is to be displayed. Does the
861 * right thing - either converts text to html or strips any html tags
862 * depending on if we are downloading and what is the download type. Params
863 * are the same as format_text function in weblib.php but some default
864 * options are changed.
866 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
867 if (!$this->is_downloading()) {
868 if (is_null($options)) {
869 $options = new stdClass;
871 //some sensible defaults
872 if (!isset($options->para)) {
873 $options->para = false;
875 if (!isset($options->newlines)) {
876 $options->newlines = false;
878 if (!isset($options->smiley)) {
879 $options->smiley = false;
881 if (!isset($options->filter)) {
882 $options->filter = false;
884 return format_text($text, $format, $options);
885 } else {
886 $eci = $this->export_class_instance();
887 return $eci->format_text($text, $format, $options, $courseid);
891 * This method is deprecated although the old api is still supported.
892 * @deprecated 1.9.2 - Jun 2, 2008
894 function print_html() {
895 if (!$this->setup) {
896 return false;
898 $this->finish_html();
902 * This function is not part of the public api.
903 * @return string initial of first name we are currently filtering by
905 function get_initial_first() {
906 if (!$this->use_initials) {
907 return NULL;
910 return $this->prefs['i_first'];
914 * This function is not part of the public api.
915 * @return string initial of last name we are currently filtering by
917 function get_initial_last() {
918 if (!$this->use_initials) {
919 return NULL;
922 return $this->prefs['i_last'];
926 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
927 * @param array $alpha of letters in the alphabet.
928 * @param string $current the currently selected letter.
929 * @param string $class class name to add to this initial bar.
930 * @param string $title the name to put in front of this initial bar.
931 * @param string $urlvar URL parameter name for this initial.
933 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
934 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
935 $title . ' : ';
936 if ($current) {
937 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
938 } else {
939 echo html_writer::tag('strong', get_string('all'));
942 foreach ($alpha as $letter) {
943 if ($letter === $current) {
944 echo html_writer::tag('strong', $letter);
945 } else {
946 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
950 echo html_writer::end_tag('div');
954 * This function is not part of the public api.
956 function print_initials_bar() {
957 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
958 && isset($this->columns['fullname'])) {
960 $alpha = explode(',', get_string('alphabet', 'langconfig'));
962 // Bar of first initials
963 if (!empty($this->prefs['i_first'])) {
964 $ifirst = $this->prefs['i_first'];
965 } else {
966 $ifirst = '';
968 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
969 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
971 // Bar of last initials
972 if (!empty($this->prefs['i_last'])) {
973 $ilast = $this->prefs['i_last'];
974 } else {
975 $ilast = '';
977 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
978 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
983 * This function is not part of the public api.
985 function print_nothing_to_display() {
986 global $OUTPUT;
988 // Render button to allow user to reset table preferences.
989 echo $this->render_reset_button();
991 $this->print_initials_bar();
993 echo $OUTPUT->heading(get_string('nothingtodisplay'));
997 * This function is not part of the public api.
999 function get_row_from_keyed($rowwithkeys) {
1000 if (is_object($rowwithkeys)) {
1001 $rowwithkeys = (array)$rowwithkeys;
1003 $row = array();
1004 foreach (array_keys($this->columns) as $column) {
1005 if (isset($rowwithkeys[$column])) {
1006 $row [] = $rowwithkeys[$column];
1007 } else {
1008 $row[] ='';
1011 return $row;
1014 * This function is not part of the public api.
1016 function get_download_menu() {
1017 $allclasses= get_declared_classes();
1018 $exportclasses = array();
1019 foreach ($allclasses as $class) {
1020 $matches = array();
1021 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
1022 $type = $matches[1];
1023 $exportclasses[$type]= get_string("download$type", 'table');
1026 return $exportclasses;
1030 * This function is not part of the public api.
1032 function download_buttons() {
1033 if ($this->is_downloadable() && !$this->is_downloading()) {
1034 $downloadoptions = $this->get_download_menu();
1036 $downloadelements = new stdClass();
1037 $downloadelements->formatsmenu = html_writer::select($downloadoptions,
1038 'download', $this->defaultdownloadformat, false);
1039 $downloadelements->downloadbutton = '<input type="submit" value="'.
1040 get_string('download').'"/>';
1041 $html = '<form action="'. $this->baseurl .'" method="post">';
1042 $html .= '<div class="mdl-align">';
1043 $html .= html_writer::tag('label', get_string('downloadas', 'table', $downloadelements));
1044 $html .= '</div></form>';
1046 return $html;
1047 } else {
1048 return '';
1052 * This function is not part of the public api.
1053 * You don't normally need to call this. It is called automatically when
1054 * needed when you start adding data to the table.
1057 function start_output() {
1058 $this->started_output = true;
1059 if ($this->exportclass!==null) {
1060 $this->exportclass->start_table($this->sheettitle);
1061 $this->exportclass->output_headers($this->headers);
1062 } else {
1063 $this->start_html();
1064 $this->print_headers();
1065 echo html_writer::start_tag('tbody');
1070 * This function is not part of the public api.
1072 function print_row($row, $classname = '') {
1073 echo $this->get_row_html($row, $classname);
1077 * Generate html code for the passed row.
1079 * @param array $row Row data.
1080 * @param string $classname classes to add.
1082 * @return string $html html code for the row passed.
1084 public function get_row_html($row, $classname = '') {
1085 static $suppress_lastrow = NULL;
1086 $rowclasses = array();
1088 if ($classname) {
1089 $rowclasses[] = $classname;
1092 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1093 $html = '';
1095 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1097 // If we have a separator, print it
1098 if ($row === NULL) {
1099 $colcount = count($this->columns);
1100 $html .= html_writer::tag('td', html_writer::tag('div', '',
1101 array('class' => 'tabledivider')), array('colspan' => $colcount));
1103 } else {
1104 $colbyindex = array_flip($this->columns);
1105 foreach ($row as $index => $data) {
1106 $column = $colbyindex[$index];
1108 if (empty($this->prefs['collapse'][$column])) {
1109 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1110 $content = '&nbsp;';
1111 } else {
1112 $content = $data;
1114 } else {
1115 $content = '&nbsp;';
1118 $html .= html_writer::tag('td', $content, array(
1119 'class' => 'cell c' . $index . $this->column_class[$column],
1120 'id' => $rowid . '_c' . $index,
1121 'style' => $this->make_styles_string($this->column_style[$column])));
1125 $html .= html_writer::end_tag('tr');
1127 $suppress_enabled = array_sum($this->column_suppress);
1128 if ($suppress_enabled) {
1129 $suppress_lastrow = $row;
1131 $this->currentrow++;
1132 return $html;
1136 * This function is not part of the public api.
1138 function finish_html() {
1139 global $OUTPUT;
1140 if (!$this->started_output) {
1141 //no data has been added to the table.
1142 $this->print_nothing_to_display();
1144 } else {
1145 // Print empty rows to fill the table to the current pagesize.
1146 // This is done so the header aria-controls attributes do not point to
1147 // non existant elements.
1148 $emptyrow = array_fill(0, count($this->columns), '');
1149 while ($this->currentrow < $this->pagesize) {
1150 $this->print_row($emptyrow, 'emptyrow');
1153 echo html_writer::end_tag('tbody');
1154 echo html_writer::end_tag('table');
1155 echo html_writer::end_tag('div');
1156 $this->wrap_html_finish();
1158 // Paging bar
1159 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1160 echo $this->download_buttons();
1163 if($this->use_pages) {
1164 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1165 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1166 echo $OUTPUT->render($pagingbar);
1172 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1173 * used by {@link print_headers()}.
1174 * @param string $column the column name, index into various names.
1175 * @param int $index numerical index of the column.
1176 * @return string HTML fragment.
1178 protected function show_hide_link($column, $index) {
1179 global $OUTPUT;
1180 // Some headers contain <br /> tags, do not include in title, hence the
1181 // strip tags.
1183 $ariacontrols = '';
1184 for ($i = 0; $i < $this->pagesize; $i++) {
1185 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1188 $ariacontrols = trim($ariacontrols);
1190 if (!empty($this->prefs['collapse'][$column])) {
1191 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1192 'aria-expanded' => 'false',
1193 'aria-controls' => $ariacontrols);
1194 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1195 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1196 $linkattributes);
1198 } else if ($this->headers[$index] !== NULL) {
1199 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1200 'aria-expanded' => 'true',
1201 'aria-controls' => $ariacontrols);
1202 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1203 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1204 $linkattributes);
1209 * This function is not part of the public api.
1211 function print_headers() {
1212 global $CFG, $OUTPUT;
1214 echo html_writer::start_tag('thead');
1215 echo html_writer::start_tag('tr');
1216 foreach ($this->columns as $column => $index) {
1218 $icon_hide = '';
1219 if ($this->is_collapsible) {
1220 $icon_hide = $this->show_hide_link($column, $index);
1223 $primarysortcolumn = '';
1224 $primarysortorder = '';
1225 if (reset($this->prefs['sortby'])) {
1226 $primarysortcolumn = key($this->prefs['sortby']);
1227 $primarysortorder = current($this->prefs['sortby']);
1230 switch ($column) {
1232 case 'fullname':
1233 // Check the full name display for sortable fields.
1234 $nameformat = $CFG->fullnamedisplay;
1235 if ($nameformat == 'language') {
1236 $nameformat = get_string('fullnamedisplay');
1238 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1240 if (!empty($requirednames)) {
1241 if ($this->is_sortable($column)) {
1242 // Done this way for the possibility of more than two sortable full name display fields.
1243 $this->headers[$index] = '';
1244 foreach ($requirednames as $name) {
1245 $sortname = $this->sort_link(get_string($name),
1246 $name, $primarysortcolumn === $name, $primarysortorder);
1247 $this->headers[$index] .= $sortname . ' / ';
1249 $this->headers[$index] = substr($this->headers[$index], 0, -3);
1252 break;
1254 case 'userpic':
1255 // do nothing, do not display sortable links
1256 break;
1258 default:
1259 if ($this->is_sortable($column)) {
1260 $this->headers[$index] = $this->sort_link($this->headers[$index],
1261 $column, $primarysortcolumn == $column, $primarysortorder);
1265 $attributes = array(
1266 'class' => 'header c' . $index . $this->column_class[$column],
1267 'scope' => 'col',
1269 if ($this->headers[$index] === NULL) {
1270 $content = '&nbsp;';
1271 } else if (!empty($this->prefs['collapse'][$column])) {
1272 $content = $icon_hide;
1273 } else {
1274 if (is_array($this->column_style[$column])) {
1275 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1277 $content = $this->headers[$index] . html_writer::tag('div',
1278 $icon_hide, array('class' => 'commands'));
1280 echo html_writer::tag('th', $content, $attributes);
1283 echo html_writer::end_tag('tr');
1284 echo html_writer::end_tag('thead');
1288 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1289 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1290 * @param int $order SORT_ASC or SORT_DESC
1291 * @return string HTML fragment.
1293 protected function sort_icon($isprimary, $order) {
1294 global $OUTPUT;
1296 if (!$isprimary) {
1297 return '';
1300 if ($order == SORT_ASC) {
1301 return html_writer::empty_tag('img',
1302 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1303 } else {
1304 return html_writer::empty_tag('img',
1305 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1310 * Generate the correct tool tip for changing the sort order. This is a
1311 * helper method used by {@link sort_link()}.
1312 * @param bool $isprimary whether the is column is the current primary sort column.
1313 * @param int $order SORT_ASC or SORT_DESC
1314 * @return string the correct title.
1316 protected function sort_order_name($isprimary, $order) {
1317 if ($isprimary && $order != SORT_ASC) {
1318 return get_string('desc');
1319 } else {
1320 return get_string('asc');
1325 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1326 * @param string $text the text for the link.
1327 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1328 * @param bool $isprimary whether the is column is the current primary sort column.
1329 * @param int $order SORT_ASC or SORT_DESC
1330 * @return string HTML fragment.
1332 protected function sort_link($text, $column, $isprimary, $order) {
1333 return html_writer::link($this->baseurl->out(false,
1334 array($this->request[TABLE_VAR_SORT] => $column)),
1335 $text . get_accesshide(get_string('sortby') . ' ' .
1336 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1337 $this->sort_icon($isprimary, $order);
1341 * This function is not part of the public api.
1343 function start_html() {
1344 global $OUTPUT;
1346 // Render button to allow user to reset table preferences.
1347 echo $this->render_reset_button();
1349 // Do we need to print initial bars?
1350 $this->print_initials_bar();
1352 // Paging bar
1353 if ($this->use_pages) {
1354 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1355 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1356 echo $OUTPUT->render($pagingbar);
1359 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1360 echo $this->download_buttons();
1363 $this->wrap_html_start();
1364 // Start of main data table
1366 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1367 echo html_writer::start_tag('table', $this->attributes);
1372 * This function is not part of the public api.
1373 * @param array $styles CSS-property => value
1374 * @return string values suitably to go in a style="" attribute in HTML.
1376 function make_styles_string($styles) {
1377 if (empty($styles)) {
1378 return null;
1381 $string = '';
1382 foreach($styles as $property => $value) {
1383 $string .= $property . ':' . $value . ';';
1385 return $string;
1389 * Generate the HTML for the table preferences reset button.
1391 * @return string HTML fragment.
1393 private function render_reset_button() {
1394 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1396 $html = html_writer::start_div('mdl-right');
1397 $html .= html_writer::link($url, get_string('resettable'));
1398 $html .= html_writer::end_div();
1400 return $html;
1406 * @package moodlecore
1407 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1410 class table_sql extends flexible_table {
1412 public $countsql = NULL;
1413 public $countparams = NULL;
1415 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1417 public $sql = NULL;
1419 * @var array|\Traversable Data fetched from the db.
1421 public $rawdata = NULL;
1424 * @var bool Overriding default for this.
1426 public $is_sortable = true;
1428 * @var bool Overriding default for this.
1430 public $is_collapsible = true;
1433 * @param string $uniqueid a string identifying this table.Used as a key in
1434 * session vars.
1436 function __construct($uniqueid) {
1437 parent::__construct($uniqueid);
1438 // some sensible defaults
1439 $this->set_attribute('cellspacing', '0');
1440 $this->set_attribute('class', 'generaltable generalbox');
1444 * Take the data returned from the db_query and go through all the rows
1445 * processing each col using either col_{columnname} method or other_cols
1446 * method or if other_cols returns NULL then put the data straight into the
1447 * table.
1449 * @return void
1451 function build_table() {
1453 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1454 return;
1456 if (!$this->rawdata) {
1457 return;
1460 foreach ($this->rawdata as $row) {
1461 $formattedrow = $this->format_row($row);
1462 $this->add_data_keyed($formattedrow,
1463 $this->get_row_class($row));
1466 if ($this->rawdata instanceof \core\dml\recordset_walk ||
1467 $this->rawdata instanceof moodle_recordset) {
1468 $this->rawdata->close();
1473 * Get any extra classes names to add to this row in the HTML.
1474 * @param $row array the data for this row.
1475 * @return string added to the class="" attribute of the tr.
1477 function get_row_class($row) {
1478 return '';
1482 * This is only needed if you want to use different sql to count rows.
1483 * Used for example when perhaps all db JOINS are not needed when counting
1484 * records. You don't need to call this function the count_sql
1485 * will be generated automatically.
1487 * We need to count rows returned by the db seperately to the query itself
1488 * as we need to know how many pages of data we have to display.
1490 function set_count_sql($sql, array $params = NULL) {
1491 $this->countsql = $sql;
1492 $this->countparams = $params;
1496 * Set the sql to query the db. Query will be :
1497 * SELECT $fields FROM $from WHERE $where
1498 * Of course you can use sub-queries, JOINS etc. by putting them in the
1499 * appropriate clause of the query.
1501 function set_sql($fields, $from, $where, array $params = NULL) {
1502 $this->sql = new stdClass();
1503 $this->sql->fields = $fields;
1504 $this->sql->from = $from;
1505 $this->sql->where = $where;
1506 $this->sql->params = $params;
1510 * Query the db. Store results in the table object for use by build_table.
1512 * @param int $pagesize size of page for paginated displayed table.
1513 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1514 * will only be used if there is a fullname column defined for the table.
1516 function query_db($pagesize, $useinitialsbar=true) {
1517 global $DB;
1518 if (!$this->is_downloading()) {
1519 if ($this->countsql === NULL) {
1520 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1521 $this->countparams = $this->sql->params;
1523 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1524 if ($useinitialsbar && !$this->is_downloading()) {
1525 $this->initialbars($grandtotal > $pagesize);
1528 list($wsql, $wparams) = $this->get_sql_where();
1529 if ($wsql) {
1530 $this->countsql .= ' AND '.$wsql;
1531 $this->countparams = array_merge($this->countparams, $wparams);
1533 $this->sql->where .= ' AND '.$wsql;
1534 $this->sql->params = array_merge($this->sql->params, $wparams);
1536 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1537 } else {
1538 $total = $grandtotal;
1541 $this->pagesize($pagesize, $total);
1544 // Fetch the attempts
1545 $sort = $this->get_sql_sort();
1546 if ($sort) {
1547 $sort = "ORDER BY $sort";
1549 $sql = "SELECT
1550 {$this->sql->fields}
1551 FROM {$this->sql->from}
1552 WHERE {$this->sql->where}
1553 {$sort}";
1555 if (!$this->is_downloading()) {
1556 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1557 } else {
1558 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1563 * Convenience method to call a number of methods for you to display the
1564 * table.
1566 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1567 global $DB;
1568 if (!$this->columns) {
1569 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1570 //if columns is not set then define columns as the keys of the rows returned
1571 //from the db.
1572 $this->define_columns(array_keys((array)$onerow));
1573 $this->define_headers(array_keys((array)$onerow));
1575 $this->setup();
1576 $this->query_db($pagesize, $useinitialsbar);
1577 $this->build_table();
1578 $this->finish_output();
1584 * @package moodlecore
1585 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1588 class table_default_export_format_parent {
1590 * @var flexible_table or child class reference pointing to table class
1591 * object from which to export data.
1593 var $table;
1596 * @var bool output started. Keeps track of whether any output has been
1597 * started yet.
1599 var $documentstarted = false;
1600 function table_default_export_format_parent(&$table) {
1601 $this->table =& $table;
1604 function set_table(&$table) {
1605 $this->table =& $table;
1608 function add_data($row) {
1609 return false;
1612 function add_seperator() {
1613 return false;
1616 function document_started() {
1617 return $this->documentstarted;
1620 * Given text in a variety of format codings, this function returns
1621 * the text as safe HTML or as plain text dependent on what is appropriate
1622 * for the download format. The default removes all tags.
1624 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1625 //use some whitespace to indicate where there was some line spacing.
1626 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1627 return strip_tags($text);
1633 * @package moodlecore
1634 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1637 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1638 var $currentrow;
1639 var $workbook;
1640 var $worksheet;
1642 * @var object format object - format for normal table cells
1644 var $formatnormal;
1646 * @var object format object - format for header table cells
1648 var $formatheaders;
1651 * should be overriden in child class.
1653 var $fileextension;
1656 * This method will be overridden in the child class.
1658 function define_workbook() {
1661 function start_document($filename) {
1662 $filename = $filename.'.'.$this->fileextension;
1663 $this->define_workbook();
1664 // format types
1665 $this->formatnormal = $this->workbook->add_format();
1666 $this->formatnormal->set_bold(0);
1667 $this->formatheaders = $this->workbook->add_format();
1668 $this->formatheaders->set_bold(1);
1669 $this->formatheaders->set_align('center');
1670 // Sending HTTP headers
1671 $this->workbook->send($filename);
1672 $this->documentstarted = true;
1675 function start_table($sheettitle) {
1676 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1677 $this->currentrow=0;
1680 function output_headers($headers) {
1681 $colnum = 0;
1682 foreach ($headers as $item) {
1683 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1684 $colnum++;
1686 $this->currentrow++;
1689 function add_data($row) {
1690 $colnum = 0;
1691 foreach ($row as $item) {
1692 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1693 $colnum++;
1695 $this->currentrow++;
1696 return true;
1699 function add_seperator() {
1700 $this->currentrow++;
1701 return true;
1704 function finish_table() {
1707 function finish_document() {
1708 $this->workbook->close();
1709 exit;
1715 * @package moodlecore
1716 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1717 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1719 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1720 var $fileextension = 'xls';
1722 function define_workbook() {
1723 global $CFG;
1724 require_once("$CFG->libdir/excellib.class.php");
1725 // Creating a workbook
1726 $this->workbook = new MoodleExcelWorkbook("-");
1733 * @package moodlecore
1734 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1737 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1738 var $fileextension = 'ods';
1739 function define_workbook() {
1740 global $CFG;
1741 require_once("$CFG->libdir/odslib.class.php");
1742 // Creating a workbook
1743 $this->workbook = new MoodleODSWorkbook("-");
1749 * @package moodlecore
1750 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1753 class table_text_export_format_parent extends table_default_export_format_parent {
1754 protected $seperator = "tab";
1755 protected $mimetype = 'text/tab-separated-values';
1756 protected $ext = '.txt';
1757 protected $myexporter;
1759 public function __construct() {
1760 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1763 public function start_document($filename) {
1764 $this->filename = $filename;
1765 $this->documentstarted = true;
1766 $this->myexporter->set_filename($filename, $this->ext);
1769 public function start_table($sheettitle) {
1770 //nothing to do here
1773 public function output_headers($headers) {
1774 $this->myexporter->add_data($headers);
1777 public function add_data($row) {
1778 $this->myexporter->add_data($row);
1779 return true;
1782 public function finish_table() {
1783 //nothing to do here
1786 public function finish_document() {
1787 $this->myexporter->download_file();
1788 exit;
1792 * Format a row of data.
1793 * @param array $data
1795 protected function format_row($data) {
1796 $escapeddata = array();
1797 foreach ($data as $value) {
1798 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1800 return implode($this->seperator, $escapeddata) . "\n";
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_tsv_export_format extends table_text_export_format_parent {
1811 protected $seperator = "tab";
1812 protected $mimetype = 'text/tab-separated-values';
1813 protected $ext = '.txt';
1816 require_once($CFG->libdir . '/csvlib.class.php');
1818 * @package moodlecore
1819 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1820 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1822 class table_csv_export_format extends table_text_export_format_parent {
1823 protected $seperator = "comma";
1824 protected $mimetype = 'text/csv';
1825 protected $ext = '.csv';
1829 * @package moodlecore
1830 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1831 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1833 class table_xhtml_export_format extends table_default_export_format_parent {
1834 function start_document($filename) {
1835 header("Content-Type: application/download\n");
1836 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1837 header("Expires: 0");
1838 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1839 header("Pragma: public");
1840 //html headers
1841 echo <<<EOF
1842 <?xml version="1.0" encoding="UTF-8"?>
1843 <!DOCTYPE html
1844 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1845 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1847 <html xmlns="http://www.w3.org/1999/xhtml"
1848 xml:lang="en" lang="en">
1849 <head>
1850 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1851 <style type="text/css">/*<![CDATA[*/
1853 .flexible th {
1854 white-space:normal;
1856 th.header, td.header, div.header {
1857 border-color:#DDDDDD;
1858 background-color:lightGrey;
1860 .flexible th {
1861 white-space:nowrap;
1863 th {
1864 font-weight:bold;
1867 .generaltable {
1868 border-style:solid;
1870 .generalbox {
1871 border-style:solid;
1873 body, table, td, th {
1874 font-family:Arial,Verdana,Helvetica,sans-serif;
1875 font-size:100%;
1877 td {
1878 border-style:solid;
1879 border-width:1pt;
1881 table {
1882 border-collapse:collapse;
1883 border-spacing:0pt;
1884 width:80%;
1885 margin:auto;
1888 h1, h2 {
1889 text-align:center;
1891 .bold {
1892 font-weight:bold;
1894 .mdl-align {
1895 text-align:center;
1897 /*]]>*/</style>
1898 <title>$filename</title>
1899 </head>
1900 <body>
1901 EOF;
1902 $this->documentstarted = true;
1905 function start_table($sheettitle) {
1906 $this->table->sortable(false);
1907 $this->table->collapsible(false);
1908 echo "<h2>{$sheettitle}</h2>";
1909 $this->table->start_html();
1912 function output_headers($headers) {
1913 $this->table->print_headers();
1914 echo html_writer::start_tag('tbody');
1917 function add_data($row) {
1918 $this->table->print_row($row);
1919 return true;
1922 function add_seperator() {
1923 $this->table->print_row(NULL);
1924 return true;
1927 function finish_table() {
1928 $this->table->finish_html();
1931 function finish_document() {
1932 echo "</body>\n</html>";
1933 exit;
1936 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1937 if (is_null($options)) {
1938 $options = new stdClass;
1940 //some sensible defaults
1941 if (!isset($options->para)) {
1942 $options->para = false;
1944 if (!isset($options->newlines)) {
1945 $options->newlines = false;
1947 if (!isset($options->smiley)) {
1948 $options->smiley = false;
1950 if (!isset($options->filter)) {
1951 $options->filter = false;
1953 return format_text($text, $format, $options);