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);
40 * Constants that indicate whether the paging bar for the table
41 * appears above or below the table.
43 define('TABLE_P_TOP', 1);
44 define('TABLE_P_BOTTOM', 2);
50 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53 class flexible_table
{
56 var $attributes = array();
57 var $headers = array();
58 var $columns = array();
59 var $column_style = array();
60 var $column_class = array();
61 var $column_suppress = array();
62 var $column_nosort = array('userpic');
63 private $column_textsort = array();
67 var $request = array();
69 var $is_collapsible = false;
70 var $is_sortable = false;
71 var $use_pages = false;
72 var $use_initials = false;
78 var $sort_default_column = NULL;
79 var $sort_default_order = SORT_ASC
;
82 * Array of positions in which to display download controls.
84 var $showdownloadbuttonsat= array(TABLE_P_TOP
);
87 * @var string Key of field returned by db query that is the id field of the
88 * user table or equivalent.
90 public $useridfield = 'id';
93 * @var string which download plugin to use. Default '' means none - print
94 * html table with paging. Property set by is_downloading which typically
95 * passes in cleaned data from $
100 * @var bool whether data is downloadable from table. Determines whether
101 * to display download buttons. Set by method downloadable().
103 var $downloadable = false;
106 * @var string which download plugin to use. Default '' means none - print
107 * html table with paging.
109 var $defaultdownloadformat = 'csv';
112 * @var bool Has start output been called yet?
114 var $started_output = false;
116 var $exportclass = null;
120 * @param int $uniqueid all tables have to have a unique id, this is used
121 * as a key when storing table properties like sort order in the session.
123 function __construct($uniqueid) {
124 $this->uniqueid
= $uniqueid;
125 $this->request
= array(
126 TABLE_VAR_SORT
=> 'tsort',
127 TABLE_VAR_HIDE
=> 'thide',
128 TABLE_VAR_SHOW
=> 'tshow',
129 TABLE_VAR_IFIRST
=> 'tifirst',
130 TABLE_VAR_ILAST
=> 'tilast',
131 TABLE_VAR_PAGE
=> 'page',
136 * Call this to pass the download type. Use :
137 * $download = optional_param('download', '', PARAM_ALPHA);
138 * To get the download type. We assume that if you call this function with
139 * params that this table's data is downloadable, so we call is_downloadable
140 * for you (even if the param is '', which means no download this time.
141 * Also you can call this method with no params to get the current set
143 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
144 * @param string $filename filename for downloads without file extension.
145 * @param string $sheettitle title for downloaded data.
146 * @return string download type. One of csv, tsv, xhtml, ods, etc
148 function is_downloading($download = null, $filename='', $sheettitle='') {
149 if ($download!==null) {
150 $this->sheettitle
= $sheettitle;
151 $this->is_downloadable(true);
152 $this->download
= $download;
153 $this->filename
= clean_filename($filename);
154 $this->export_class_instance();
156 return $this->download
;
160 * Get, and optionally set, the export class.
161 * @param $exportclass (optional) if passed, set the table to use this export class.
162 * @return table_default_export_format_parent the export class in use (after any set).
164 function export_class_instance($exportclass = null) {
165 if (!is_null($exportclass)) {
166 $this->started_output
= true;
167 $this->exportclass
= $exportclass;
168 $this->exportclass
->table
= $this;
169 } else if (is_null($this->exportclass
) && !empty($this->download
)) {
170 $classname = 'table_'.$this->download
.'_export_format';
171 $this->exportclass
= new $classname($this);
172 if (!$this->exportclass
->document_started()) {
173 $this->exportclass
->start_document($this->filename
);
176 return $this->exportclass
;
180 * Probably don't need to call this directly. Calling is_downloading with a
181 * param automatically sets table as downloadable.
183 * @param bool $downloadable optional param to set whether data from
184 * table is downloadable. If ommitted this function can be used to get
185 * current state of table.
186 * @return bool whether table data is set to be downloadable.
188 function is_downloadable($downloadable = null) {
189 if ($downloadable !== null) {
190 $this->downloadable
= $downloadable;
192 return $this->downloadable
;
196 * Where to show download buttons.
197 * @param array $showat array of postions in which to show download buttons.
198 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
200 function show_download_buttons_at($showat) {
201 $this->showdownloadbuttonsat
= $showat;
205 * Sets the is_sortable variable to the given boolean, sort_default_column to
206 * the given string, and the sort_default_order to the given integer.
208 * @param string $defaultcolumn
209 * @param int $defaultorder
212 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC
) {
213 $this->is_sortable
= $bool;
214 $this->sort_default_column
= $defaultcolumn;
215 $this->sort_default_order
= $defaultorder;
219 * Use text sorting functions for this column (required for text columns with Oracle).
220 * @param string column name
222 function text_sorting($column) {
223 $this->column_textsort
[] = $column;
227 * Do not sort using this column
228 * @param string column name
230 function no_sorting($column) {
231 $this->column_nosort
[] = $column;
235 * Is the column sortable?
236 * @param string column name, null means table
239 function is_sortable($column = null) {
240 if (empty($column)) {
241 return $this->is_sortable
;
243 if (!$this->is_sortable
) {
246 return !in_array($column, $this->column_nosort
);
250 * Sets the is_collapsible variable to the given boolean.
254 function collapsible($bool) {
255 $this->is_collapsible
= $bool;
259 * Sets the use_pages variable to the given boolean.
263 function pageable($bool) {
264 $this->use_pages
= $bool;
268 * Sets the use_initials variable to the given boolean.
272 function initialbars($bool) {
273 $this->use_initials
= $bool;
277 * Sets the pagesize variable to the given integer, the totalrows variable
278 * to the given integer, and the use_pages variable to true.
279 * @param int $perpage
283 function pagesize($perpage, $total) {
284 $this->pagesize
= $perpage;
285 $this->totalrows
= $total;
286 $this->use_pages
= true;
290 * Assigns each given variable in the array to the corresponding index
291 * in the request class variable.
292 * @param array $variables
295 function set_control_variables($variables) {
296 foreach ($variables as $what => $variable) {
297 if (isset($this->request
[$what])) {
298 $this->request
[$what] = $variable;
304 * Gives the given $value to the $attribute index of $this->attributes.
305 * @param string $attribute
306 * @param mixed $value
309 function set_attribute($attribute, $value) {
310 $this->attributes
[$attribute] = $value;
314 * What this method does is set the column so that if the same data appears in
315 * consecutive rows, then it is not repeated.
317 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
318 * that when one student has made multiple attempts, their name is only printed in the row
319 * for their first attempt.
320 * @param int $column the index of a column.
322 function column_suppress($column) {
323 if (isset($this->column_suppress
[$column])) {
324 $this->column_suppress
[$column] = true;
329 * Sets the given $column index to the given $classname in $this->column_class.
331 * @param string $classname
334 function column_class($column, $classname) {
335 if (isset($this->column_class
[$column])) {
336 $this->column_class
[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
341 * Sets the given $column index and $property index to the given $value in $this->column_style.
343 * @param string $property
344 * @param mixed $value
347 function column_style($column, $property, $value) {
348 if (isset($this->column_style
[$column])) {
349 $this->column_style
[$column][$property] = $value;
354 * Sets all columns' $propertys to the given $value in $this->column_style.
355 * @param int $property
356 * @param string $value
359 function column_style_all($property, $value) {
360 foreach (array_keys($this->columns
) as $column) {
361 $this->column_style
[$column][$property] = $value;
366 * Sets $this->baseurl.
367 * @param moodle_url|string $url the url with params needed to call up this page
369 function define_baseurl($url) {
370 $this->baseurl
= new moodle_url($url);
374 * @param array $columns an array of identifying names for columns. If
375 * columns are sorted then column names must correspond to a field in sql.
377 function define_columns($columns) {
378 $this->columns
= array();
379 $this->column_style
= array();
380 $this->column_class
= array();
383 foreach ($columns as $column) {
384 $this->columns
[$column] = $colnum++
;
385 $this->column_style
[$column] = array();
386 $this->column_class
[$column] = '';
387 $this->column_suppress
[$column] = false;
392 * @param array $headers numerical keyed array of displayed string titles
395 function define_headers($headers) {
396 $this->headers
= $headers;
400 * Must be called after table is defined. Use methods above first. Cannot
401 * use functions below till after calling this method.
405 global $SESSION, $CFG;
407 if (empty($this->columns
) ||
empty($this->uniqueid
)) {
411 if (!isset($SESSION->flextable
)) {
412 $SESSION->flextable
= array();
415 if (!isset($SESSION->flextable
[$this->uniqueid
])) {
416 $SESSION->flextable
[$this->uniqueid
] = new stdClass
;
417 $SESSION->flextable
[$this->uniqueid
]->uniqueid
= $this->uniqueid
;
418 $SESSION->flextable
[$this->uniqueid
]->collapse
= array();
419 $SESSION->flextable
[$this->uniqueid
]->sortby
= array();
420 $SESSION->flextable
[$this->uniqueid
]->i_first
= '';
421 $SESSION->flextable
[$this->uniqueid
]->i_last
= '';
422 $SESSION->flextable
[$this->uniqueid
]->textsort
= $this->column_textsort
;
425 $this->sess
= &$SESSION->flextable
[$this->uniqueid
];
427 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
428 isset($this->columns
[$showcol])) {
429 $this->sess
->collapse
[$showcol] = false;
431 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
432 isset($this->columns
[$hidecol])) {
433 $this->sess
->collapse
[$hidecol] = true;
434 if (array_key_exists($hidecol, $this->sess
->sortby
)) {
435 unset($this->sess
->sortby
[$hidecol]);
439 // Now, update the column attributes for collapsed columns
440 foreach (array_keys($this->columns
) as $column) {
441 if (!empty($this->sess
->collapse
[$column])) {
442 $this->column_style
[$column]['width'] = '10px';
446 if (($sortcol = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
)) &&
447 $this->is_sortable($sortcol) && empty($this->sess
->collapse
[$sortcol]) &&
448 (isset($this->columns
[$sortcol]) ||
in_array($sortcol, array('firstname', 'lastname')) && isset($this->columns
['fullname']))) {
450 if (array_key_exists($sortcol, $this->sess
->sortby
)) {
451 // This key already exists somewhere. Change its sortorder and bring it to the top.
452 $sortorder = $this->sess
->sortby
[$sortcol] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
453 unset($this->sess
->sortby
[$sortcol]);
454 $this->sess
->sortby
= array_merge(array($sortcol => $sortorder), $this->sess
->sortby
);
456 // Key doesn't exist, so just add it to the beginning of the array, ascending order
457 $this->sess
->sortby
= array_merge(array($sortcol => SORT_ASC
), $this->sess
->sortby
);
460 // Finally, make sure that no more than $this->maxsortkeys are present into the array
461 $this->sess
->sortby
= array_slice($this->sess
->sortby
, 0, $this->maxsortkeys
);
464 // 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.
465 // This prevents results from being returned in a random order if the only order by column contains equal values.
466 if (!empty($this->sort_default_column
)) {
467 if (!array_key_exists($this->sort_default_column
, $this->sess
->sortby
)) {
468 $defaultsort = array($this->sort_default_column
=> $this->sort_default_order
);
469 $this->sess
->sortby
= array_merge($this->sess
->sortby
, $defaultsort);
473 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
474 if (!is_null($ilast) && ($ilast ==='' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
475 $this->sess
->i_last
= $ilast;
478 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
479 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
480 $this->sess
->i_first
= $ifirst;
483 if (empty($this->baseurl
)) {
484 debugging('You should set baseurl when using flexible_table.');
486 $this->baseurl
= $PAGE->url
;
489 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
492 // Always introduce the "flexible" class for the table if not specified
493 if (empty($this->attributes
)) {
494 $this->attributes
['class'] = 'flexible';
495 } else if (!isset($this->attributes
['class'])) {
496 $this->attributes
['class'] = 'flexible';
497 } else if (!in_array('flexible', explode(' ', $this->attributes
['class']))) {
498 $this->attributes
['class'] = trim('flexible ' . $this->attributes
['class']);
503 * Get the order by clause from the session, for the table with id $uniqueid.
504 * @param string $uniqueid the identifier for a table.
505 * @return SQL fragment that can be used in an ORDER BY clause.
507 public static function get_sort_for_table($uniqueid) {
509 if (empty($SESSION->flextable
[$uniqueid])) {
513 $sess = &$SESSION->flextable
[$uniqueid];
514 if (empty($sess->sortby
)) {
517 if (empty($sess->textsort
)) {
518 $sess->textsort
= array();
521 return self
::construct_order_by($sess->sortby
, $sess->textsort
);
525 * Prepare an an order by clause from the list of columns to be sorted.
526 * @param array $cols column name => SORT_ASC or SORT_DESC
527 * @return SQL fragment that can be used in an ORDER BY clause.
529 public static function construct_order_by($cols, $textsortcols=array()) {
533 foreach ($cols as $column => $order) {
534 if (in_array($column, $textsortcols)) {
535 $column = $DB->sql_order_by_text($column);
537 if ($order == SORT_ASC
) {
538 $bits[] = $column . ' ASC';
540 $bits[] = $column . ' DESC';
544 return implode(', ', $bits);
548 * @return SQL fragment that can be used in an ORDER BY clause.
550 public function get_sql_sort() {
551 return self
::construct_order_by($this->get_sort_columns(), $this->column_textsort
);
555 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
556 * @return array column name => SORT_... constant.
558 public function get_sort_columns() {
560 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
563 if (empty($this->sess
->sortby
)) {
567 foreach ($this->sess
->sortby
as $column => $notused) {
568 if (isset($this->columns
[$column])) {
569 continue; // This column is OK.
571 if (in_array($column, array('firstname', 'lastname')) &&
572 isset($this->columns
['fullname'])) {
573 continue; // This column is OK.
575 // This column is not OK.
576 unset($this->sess
->sortby
[$column]);
579 return $this->sess
->sortby
;
583 * @return int the offset for LIMIT clause of SQL
585 function get_page_start() {
586 if (!$this->use_pages
) {
589 return $this->currpage
* $this->pagesize
;
593 * @return int the pagesize for LIMIT clause of SQL
595 function get_page_size() {
596 if (!$this->use_pages
) {
599 return $this->pagesize
;
603 * @return string sql to add to where statement.
605 function get_sql_where() {
608 $conditions = array();
611 if (isset($this->columns
['fullname'])) {
615 if (!empty($this->sess
->i_first
)) {
616 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
617 $params['ifirstc'.$i] = $this->sess
->i_first
.'%';
619 if (!empty($this->sess
->i_last
)) {
620 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
621 $params['ilastc'.$i] = $this->sess
->i_last
.'%';
625 return array(implode(" AND ", $conditions), $params);
629 * Add a row of data to the table. This function takes an array with
630 * column names as keys.
631 * It ignores any elements with keys that are not defined as columns. It
632 * puts in empty strings into the row when there is no element in the passed
633 * array corresponding to a column in the table. It puts the row elements in
635 * @param $rowwithkeys array
636 * @param string $classname CSS class name to add to this row's tr tag.
638 function add_data_keyed($rowwithkeys, $classname = '') {
639 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
643 * Add a seperator line to table.
645 function add_separator() {
649 $this->add_data(NULL);
653 * This method actually directly echoes the row passed to it now or adds it
654 * to the download. If this is the first row and start_output has not
655 * already been called this method also calls start_output to open the table
656 * or send headers for the downloaded.
657 * Can be used as before. print_html now calls finish_html to close table.
659 * @param array $row a numerically keyed row of data to add to the table.
660 * @param string $classname CSS class name to add to this row's tr tag.
661 * @return bool success.
663 function add_data($row, $classname = '') {
667 if (!$this->started_output
) {
668 $this->start_output();
670 if ($this->exportclass
!==null) {
672 $this->exportclass
->add_seperator();
674 $this->exportclass
->add_data($row);
677 $this->print_row($row, $classname);
683 * You should call this to finish outputting the table data after adding
684 * data to the table with add_data or add_data_keyed.
687 function finish_output($closeexportclassdoc = true) {
688 if ($this->exportclass
!==null) {
689 $this->exportclass
->finish_table();
690 if ($closeexportclassdoc) {
691 $this->exportclass
->finish_document();
694 $this->finish_html();
699 * Hook that can be overridden in child classes to wrap a table in a form
700 * for example. Called only when there is data to display and not
703 function wrap_html_start() {
707 * Hook that can be overridden in child classes to wrap a table in a form
708 * for example. Called only when there is data to display and not
711 function wrap_html_finish() {
716 * @param array $row row of data from db used to make one row of the table.
717 * @return array one row for the table, added using add_data_keyed method.
719 function format_row($row) {
720 $formattedrow = array();
721 foreach (array_keys($this->columns
) as $column) {
722 $colmethodname = 'col_'.$column;
723 if (method_exists($this, $colmethodname)) {
724 $formattedcolumn = $this->$colmethodname($row);
726 $formattedcolumn = $this->other_cols($column, $row);
727 if ($formattedcolumn===NULL) {
728 $formattedcolumn = $row->$column;
731 $formattedrow[$column] = $formattedcolumn;
733 return $formattedrow;
737 * Fullname is treated as a special columname in tablelib and should always
738 * be treated the same as the fullname of a user.
739 * @uses $this->useridfield if the userid field is not expected to be id
740 * then you need to override $this->useridfield to point at the correct
741 * field for the user id.
744 function col_fullname($row) {
745 global $COURSE, $CFG;
747 $name = fullname($row);
748 if ($this->download
) {
752 $userid = $row->{$this->useridfield
};
753 if ($COURSE->id
== SITEID
) {
754 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
756 $profileurl = new moodle_url('/user/view.php',
757 array('id' => $userid, 'course' => $COURSE->id
));
759 return html_writer
::link($profileurl, $name);
763 * You can override this method in a child class. See the description of
764 * build_table which calls this method.
766 function other_cols($column, $row) {
771 * Used from col_* functions when text is to be displayed. Does the
772 * right thing - either converts text to html or strips any html tags
773 * depending on if we are downloading and what is the download type. Params
774 * are the same as format_text function in weblib.php but some default
775 * options are changed.
777 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
778 if (!$this->is_downloading()) {
779 if (is_null($options)) {
780 $options = new stdClass
;
782 //some sensible defaults
783 if (!isset($options->para
)) {
784 $options->para
= false;
786 if (!isset($options->newlines
)) {
787 $options->newlines
= false;
789 if (!isset($options->smiley
)) {
790 $options->smiley
= false;
792 if (!isset($options->filter
)) {
793 $options->filter
= false;
795 return format_text($text, $format, $options);
797 $eci =& $this->export_class_instance();
798 return $eci->format_text($text, $format, $options, $courseid);
802 * This method is deprecated although the old api is still supported.
803 * @deprecated 1.9.2 - Jun 2, 2008
805 function print_html() {
809 $this->finish_html();
813 * This function is not part of the public api.
814 * @return string initial of first name we are currently filtering by
816 function get_initial_first() {
817 if (!$this->use_initials
) {
821 return $this->sess
->i_first
;
825 * This function is not part of the public api.
826 * @return string initial of last name we are currently filtering by
828 function get_initial_last() {
829 if (!$this->use_initials
) {
833 return $this->sess
->i_last
;
837 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
838 * @param array $alpha of letters in the alphabet.
839 * @param string $current the currently selected letter.
840 * @param string $class class name to add to this initial bar.
841 * @param string $title the name to put in front of this initial bar.
842 * @param string $urlvar URL parameter name for this initial.
844 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
845 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
848 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
850 echo html_writer
::tag('strong', get_string('all'));
853 foreach ($alpha as $letter) {
854 if ($letter === $current) {
855 echo html_writer
::tag('strong', $letter);
857 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
861 echo html_writer
::end_tag('div');
865 * This function is not part of the public api.
867 function print_initials_bar() {
868 if ((!empty($this->sess
->i_last
) ||
!empty($this->sess
->i_first
) ||
$this->use_initials
)
869 && isset($this->columns
['fullname'])) {
871 $alpha = explode(',', get_string('alphabet', 'langconfig'));
873 // Bar of first initials
874 if (!empty($this->sess
->i_first
)) {
875 $ifirst = $this->sess
->i_first
;
879 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
880 get_string('firstname'), $this->request
[TABLE_VAR_IFIRST
]);
882 // Bar of last initials
883 if (!empty($this->sess
->i_last
)) {
884 $ilast = $this->sess
->i_last
;
888 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
889 get_string('lastname'), $this->request
[TABLE_VAR_ILAST
]);
894 * This function is not part of the public api.
896 function print_nothing_to_display() {
898 $this->print_initials_bar();
900 echo $OUTPUT->heading(get_string('nothingtodisplay'));
904 * This function is not part of the public api.
906 function get_row_from_keyed($rowwithkeys) {
907 if (is_object($rowwithkeys)) {
908 $rowwithkeys = (array)$rowwithkeys;
911 foreach (array_keys($this->columns
) as $column) {
912 if (isset($rowwithkeys[$column])) {
913 $row [] = $rowwithkeys[$column];
921 * This function is not part of the public api.
923 function get_download_menu() {
924 $allclasses= get_declared_classes();
925 $exportclasses = array();
926 foreach ($allclasses as $class) {
928 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
930 $exportclasses[$type]= get_string("download$type", 'table');
933 return $exportclasses;
937 * This function is not part of the public api.
939 function download_buttons() {
940 if ($this->is_downloadable() && !$this->is_downloading()) {
941 $downloadoptions = $this->get_download_menu();
943 $downloadelements = new stdClass();
944 $downloadelements->formatsmenu
= html_writer
::select($downloadoptions,
945 'download', $this->defaultdownloadformat
, false);
946 $downloadelements->downloadbutton
= '<input type="submit" value="'.
947 get_string('download').'"/>';
948 $html = '<form action="'. $this->baseurl
.'" method="post">';
949 $html .= '<div class="mdl-align">';
950 $html .= html_writer
::tag('label', get_string('downloadas', 'table', $downloadelements));
951 $html .= '</div></form>';
959 * This function is not part of the public api.
960 * You don't normally need to call this. It is called automatically when
961 * needed when you start adding data to the table.
964 function start_output() {
965 $this->started_output
= true;
966 if ($this->exportclass
!==null) {
967 $this->exportclass
->start_table($this->sheettitle
);
968 $this->exportclass
->output_headers($this->headers
);
971 $this->print_headers();
972 echo html_writer
::start_tag('tbody');
977 * This function is not part of the public api.
979 function print_row($row, $classname = '') {
980 static $suppress_lastrow = NULL;
982 $rowclasses = array('r' . $oddeven);
983 $oddeven = $oddeven ?
0 : 1;
986 $rowclasses[] = $classname;
989 echo html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses)));
991 // If we have a separator, print it
993 $colcount = count($this->columns
);
994 echo html_writer
::tag('td', html_writer
::tag('div', '',
995 array('class' => 'tabledivider')), array('colspan' => $colcount));
998 $colbyindex = array_flip($this->columns
);
999 foreach ($row as $index => $data) {
1000 $column = $colbyindex[$index];
1002 if (empty($this->sess
->collapse
[$column])) {
1003 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1004 $content = ' ';
1009 $content = ' ';
1012 echo html_writer
::tag('td', $content, array(
1013 'class' => 'cell c' . $index . $this->column_class
[$column],
1014 'style' => $this->make_styles_string($this->column_style
[$column])));
1018 echo html_writer
::end_tag('tr');
1020 $suppress_enabled = array_sum($this->column_suppress
);
1021 if ($suppress_enabled) {
1022 $suppress_lastrow = $row;
1027 * This function is not part of the public api.
1029 function finish_html() {
1031 if (!$this->started_output
) {
1032 //no data has been added to the table.
1033 $this->print_nothing_to_display();
1036 echo html_writer
::end_tag('tbody');
1037 echo html_writer
::end_tag('table');
1038 echo html_writer
::end_tag('div');
1039 $this->wrap_html_finish();
1042 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1043 echo $this->download_buttons();
1046 if($this->use_pages
) {
1047 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1048 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1049 echo $OUTPUT->render($pagingbar);
1055 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1056 * used by {@link print_headers()}.
1057 * @param string $column the column name, index into various names.
1058 * @param int $index numerical index of the column.
1059 * @return string HTML fragment.
1061 protected function show_hide_link($column, $index) {
1063 // Some headers contain <br /> tags, do not include in title, hence the
1066 if (!empty($this->sess
->collapse
[$column])) {
1067 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1068 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1069 array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index])));
1071 } else if ($this->headers
[$index] !== NULL) {
1072 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1073 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1074 array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index])));
1079 * This function is not part of the public api.
1081 function print_headers() {
1082 global $CFG, $OUTPUT;
1084 echo html_writer
::start_tag('thead');
1085 echo html_writer
::start_tag('tr');
1086 foreach ($this->columns
as $column => $index) {
1089 if ($this->is_collapsible
) {
1090 $icon_hide = $this->show_hide_link($column, $index);
1093 $primary_sort_column = '';
1094 $primary_sort_order = '';
1095 if (reset($this->sess
->sortby
)) {
1096 $primary_sort_column = key($this->sess
->sortby
);
1097 $primary_sort_order = current($this->sess
->sortby
);
1103 if ($this->is_sortable($column)) {
1104 $firstnamesortlink = $this->sort_link(get_string('firstname'),
1105 'firstname', $primary_sort_column === 'firstname', $primary_sort_order);
1107 $lastnamesortlink = $this->sort_link(get_string('lastname'),
1108 'lastname', $primary_sort_column === 'lastname', $primary_sort_order);
1110 $override = new stdClass();
1111 $override->firstname
= 'firstname';
1112 $override->lastname
= 'lastname';
1113 $fullnamelanguage = get_string('fullnamedisplay', '', $override);
1115 if (($CFG->fullnamedisplay
== 'firstname lastname') or
1116 ($CFG->fullnamedisplay
== 'firstname') or
1117 ($CFG->fullnamedisplay
== 'language' and $fullnamelanguage == 'firstname lastname' )) {
1118 $this->headers
[$index] = $firstnamesortlink . ' / ' . $lastnamesortlink;
1120 $this->headers
[$index] = $lastnamesortlink . ' / ' . $firstnamesortlink;
1126 // do nothing, do not display sortable links
1130 if ($this->is_sortable($column)) {
1131 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1132 $column, $primary_sort_column == $column, $primary_sort_order);
1136 $attributes = array(
1137 'class' => 'header c' . $index . $this->column_class
[$column],
1140 if ($this->headers
[$index] === NULL) {
1141 $content = ' ';
1142 } else if (!empty($this->sess
->collapse
[$column])) {
1143 $content = $icon_hide;
1145 if (is_array($this->column_style
[$column])) {
1146 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1148 $content = $this->headers
[$index] . html_writer
::tag('div',
1149 $icon_hide, array('class' => 'commands'));
1151 echo html_writer
::tag('th', $content, $attributes);
1154 echo html_writer
::end_tag('tr');
1155 echo html_writer
::end_tag('thead');
1159 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1160 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1161 * @param int $order SORT_ASC or SORT_DESC
1162 * @return string HTML fragment.
1164 protected function sort_icon($isprimary, $order) {
1171 if ($order == SORT_ASC
) {
1172 return html_writer
::empty_tag('img',
1173 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1175 return html_writer
::empty_tag('img',
1176 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1181 * Generate the correct tool tip for changing the sort order. This is a
1182 * helper method used by {@link sort_link()}.
1183 * @param bool $isprimary whether the is column is the current primary sort column.
1184 * @param int $order SORT_ASC or SORT_DESC
1185 * @return string the correct title.
1187 protected function sort_order_name($isprimary, $order) {
1188 if ($isprimary && $order != SORT_ASC
) {
1189 return get_string('desc');
1191 return get_string('asc');
1196 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1197 * @param string $text the text for the link.
1198 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1199 * @param bool $isprimary whether the is column is the current primary sort column.
1200 * @param int $order SORT_ASC or SORT_DESC
1201 * @return string HTML fragment.
1203 protected function sort_link($text, $column, $isprimary, $order) {
1204 return html_writer
::link($this->baseurl
->out(false,
1205 array($this->request
[TABLE_VAR_SORT
] => $column)),
1206 $text . get_accesshide(get_string('sortby') . ' ' .
1207 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1208 $this->sort_icon($isprimary, $order);
1212 * This function is not part of the public api.
1214 function start_html() {
1216 // Do we need to print initial bars?
1217 $this->print_initials_bar();
1220 if ($this->use_pages
) {
1221 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1222 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1223 echo $OUTPUT->render($pagingbar);
1226 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1227 echo $this->download_buttons();
1230 $this->wrap_html_start();
1231 // Start of main data table
1233 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1234 echo html_writer
::start_tag('table', $this->attributes
);
1239 * This function is not part of the public api.
1240 * @param array $styles CSS-property => value
1241 * @return string values suitably to go in a style="" attribute in HTML.
1243 function make_styles_string($styles) {
1244 if (empty($styles)) {
1249 foreach($styles as $property => $value) {
1250 $string .= $property . ':' . $value . ';';
1258 * @package moodlecore
1259 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1260 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1262 class table_sql
extends flexible_table
{
1264 public $countsql = NULL;
1265 public $countparams = NULL;
1267 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1271 * @var array Data fetched from the db.
1273 public $rawdata = NULL;
1276 * @var bool Overriding default for this.
1278 public $is_sortable = true;
1280 * @var bool Overriding default for this.
1282 public $is_collapsible = true;
1285 * @param string $uniqueid a string identifying this table.Used as a key in
1288 function __construct($uniqueid) {
1289 parent
::__construct($uniqueid);
1290 // some sensible defaults
1291 $this->set_attribute('cellspacing', '0');
1292 $this->set_attribute('class', 'generaltable generalbox');
1296 * Take the data returned from the db_query and go through all the rows
1297 * processing each col using either col_{columnname} method or other_cols
1298 * method or if other_cols returns NULL then put the data straight into the
1301 function build_table() {
1302 if ($this->rawdata
) {
1303 foreach ($this->rawdata
as $row) {
1304 $formattedrow = $this->format_row($row);
1305 $this->add_data_keyed($formattedrow,
1306 $this->get_row_class($row));
1312 * Get any extra classes names to add to this row in the HTML.
1313 * @param $row array the data for this row.
1314 * @return string added to the class="" attribute of the tr.
1316 function get_row_class($row) {
1321 * This is only needed if you want to use different sql to count rows.
1322 * Used for example when perhaps all db JOINS are not needed when counting
1323 * records. You don't need to call this function the count_sql
1324 * will be generated automatically.
1326 * We need to count rows returned by the db seperately to the query itself
1327 * as we need to know how many pages of data we have to display.
1329 function set_count_sql($sql, array $params = NULL) {
1330 $this->countsql
= $sql;
1331 $this->countparams
= $params;
1335 * Set the sql to query the db. Query will be :
1336 * SELECT $fields FROM $from WHERE $where
1337 * Of course you can use sub-queries, JOINS etc. by putting them in the
1338 * appropriate clause of the query.
1340 function set_sql($fields, $from, $where, array $params = NULL) {
1341 $this->sql
= new stdClass();
1342 $this->sql
->fields
= $fields;
1343 $this->sql
->from
= $from;
1344 $this->sql
->where
= $where;
1345 $this->sql
->params
= $params;
1349 * Query the db. Store results in the table object for use by build_table.
1351 * @param int $pagesize size of page for paginated displayed table.
1352 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1353 * will only be used if there is a fullname column defined for the table.
1355 function query_db($pagesize, $useinitialsbar=true) {
1357 if (!$this->is_downloading()) {
1358 if ($this->countsql
=== NULL) {
1359 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1360 $this->countparams
= $this->sql
->params
;
1362 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1363 if ($useinitialsbar && !$this->is_downloading()) {
1364 $this->initialbars($grandtotal > $pagesize);
1367 list($wsql, $wparams) = $this->get_sql_where();
1369 $this->countsql
.= ' AND '.$wsql;
1370 $this->countparams
= array_merge($this->countparams
, $wparams);
1372 $this->sql
->where
.= ' AND '.$wsql;
1373 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1375 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1377 $total = $grandtotal;
1380 $this->pagesize($pagesize, $total);
1383 // Fetch the attempts
1384 $sort = $this->get_sql_sort();
1386 $sort = "ORDER BY $sort";
1389 {$this->sql->fields}
1390 FROM {$this->sql->from}
1391 WHERE {$this->sql->where}
1394 if (!$this->is_downloading()) {
1395 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
1397 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
1402 * Convenience method to call a number of methods for you to display the
1405 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1407 if (!$this->columns
) {
1408 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql
->params
);
1409 //if columns is not set then define columns as the keys of the rows returned
1411 $this->define_columns(array_keys((array)$onerow));
1412 $this->define_headers(array_keys((array)$onerow));
1415 $this->query_db($pagesize, $useinitialsbar);
1416 $this->build_table();
1417 $this->finish_output();
1423 * @package moodlecore
1424 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1427 class table_default_export_format_parent
{
1429 * @var flexible_table or child class reference pointing to table class
1430 * object from which to export data.
1435 * @var bool output started. Keeps track of whether any output has been
1438 var $documentstarted = false;
1439 function table_default_export_format_parent(&$table) {
1440 $this->table
=& $table;
1443 function set_table(&$table) {
1444 $this->table
=& $table;
1447 function add_data($row) {
1451 function add_seperator() {
1455 function document_started() {
1456 return $this->documentstarted
;
1459 * Given text in a variety of format codings, this function returns
1460 * the text as safe HTML or as plain text dependent on what is appropriate
1461 * for the download format. The default removes all tags.
1463 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1464 //use some whitespace to indicate where there was some line spacing.
1465 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1466 return strip_tags($text);
1472 * @package moodlecore
1473 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1476 class table_spreadsheet_export_format_parent
extends table_default_export_format_parent
{
1481 * @var object format object - format for normal table cells
1485 * @var object format object - format for header table cells
1490 * should be overriden in child class.
1495 * This method will be overridden in the child class.
1497 function define_workbook() {
1500 function start_document($filename) {
1501 $filename = $filename.'.'.$this->fileextension
;
1502 $this->define_workbook();
1504 $this->formatnormal
=& $this->workbook
->add_format();
1505 $this->formatnormal
->set_bold(0);
1506 $this->formatheaders
=& $this->workbook
->add_format();
1507 $this->formatheaders
->set_bold(1);
1508 $this->formatheaders
->set_align('center');
1509 // Sending HTTP headers
1510 $this->workbook
->send($filename);
1511 $this->documentstarted
= true;
1514 function start_table($sheettitle) {
1515 $this->worksheet
= $this->workbook
->add_worksheet($sheettitle);
1519 function output_headers($headers) {
1521 foreach ($headers as $item) {
1522 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatheaders
);
1528 function add_data($row) {
1530 foreach ($row as $item) {
1531 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatnormal
);
1538 function add_seperator() {
1543 function finish_table() {
1546 function finish_document() {
1547 $this->workbook
->close();
1554 * @package moodlecore
1555 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1556 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1558 class table_excel_export_format
extends table_spreadsheet_export_format_parent
{
1559 var $fileextension = 'xls';
1561 function define_workbook() {
1563 require_once("$CFG->libdir/excellib.class.php");
1564 // Creating a workbook
1565 $this->workbook
= new MoodleExcelWorkbook("-");
1572 * @package moodlecore
1573 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1576 class table_ods_export_format
extends table_spreadsheet_export_format_parent
{
1577 var $fileextension = 'ods';
1578 function define_workbook() {
1580 require_once("$CFG->libdir/odslib.class.php");
1581 // Creating a workbook
1582 $this->workbook
= new MoodleODSWorkbook("-");
1588 * @package moodlecore
1589 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1590 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1592 class table_text_export_format_parent
extends table_default_export_format_parent
{
1593 protected $seperator = "tab";
1594 protected $mimetype = 'text/tab-separated-values';
1595 protected $ext = '.txt';
1596 protected $myexporter;
1598 public function __construct() {
1599 $this->myexporter
= new csv_export_writer($this->seperator
, '"', $this->mimetype
);
1602 public function start_document($filename) {
1603 $this->filename
= $filename;
1604 $this->documentstarted
= true;
1605 $this->myexporter
->set_filename($filename, $this->ext
);
1608 public function start_table($sheettitle) {
1609 //nothing to do here
1612 public function output_headers($headers) {
1613 $this->myexporter
->add_data($headers);
1616 public function add_data($row) {
1617 $this->myexporter
->add_data($row);
1621 public function finish_table() {
1622 //nothing to do here
1625 public function finish_document() {
1626 $this->myexporter
->download_file();
1631 * Format a row of data.
1632 * @param array $data
1634 protected function format_row($data) {
1635 $escapeddata = array();
1636 foreach ($data as $value) {
1637 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1639 return implode($this->seperator
, $escapeddata) . "\n";
1645 * @package moodlecore
1646 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1649 class table_tsv_export_format
extends table_text_export_format_parent
{
1650 protected $seperator = "tab";
1651 protected $mimetype = 'text/tab-separated-values';
1652 protected $ext = '.txt';
1655 require_once($CFG->libdir
. '/csvlib.class.php');
1657 * @package moodlecore
1658 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1661 class table_csv_export_format
extends table_text_export_format_parent
{
1662 protected $seperator = "comma";
1663 protected $mimetype = 'text/csv';
1664 protected $ext = '.csv';
1668 * @package moodlecore
1669 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1672 class table_xhtml_export_format
extends table_default_export_format_parent
{
1673 function start_document($filename) {
1674 header("Content-Type: application/download\n");
1675 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1676 header("Expires: 0");
1677 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1678 header("Pragma: public");
1681 <?xml version="1.0" encoding="UTF-8"?>
1683 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1684 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1686 <html xmlns="http://www.w3.org/1999/xhtml"
1687 xml:lang="en" lang="en">
1689 <style type="text/css">/*<![CDATA[*/
1694 th.header, td.header, div.header {
1695 border-color:#DDDDDD;
1696 background-color:lightGrey;
1711 body, table, td, th {
1712 font-family:Arial,Verdana,Helvetica,sans-serif;
1720 border-collapse:collapse;
1736 <title>$filename</title>
1740 $this->documentstarted
= true;
1743 function start_table($sheettitle) {
1744 $this->table
->sortable(false);
1745 $this->table
->collapsible(false);
1746 echo "<h2>{$sheettitle}</h2>";
1747 $this->table
->start_html();
1750 function output_headers($headers) {
1751 $this->table
->print_headers();
1752 echo html_writer
::start_tag('tbody');
1755 function add_data($row) {
1756 $this->table
->print_row($row);
1760 function add_seperator() {
1761 $this->table
->print_row(NULL);
1765 function finish_table() {
1766 $this->table
->finish_html();
1769 function finish_document() {
1770 echo "</body>\n</html>";
1774 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1775 if (is_null($options)) {
1776 $options = new stdClass
;
1778 //some sensible defaults
1779 if (!isset($options->para
)) {
1780 $options->para
= false;
1782 if (!isset($options->newlines
)) {
1783 $options->newlines
= false;
1785 if (!isset($options->smiley
)) {
1786 $options->smiley
= false;
1788 if (!isset($options->filter
)) {
1789 $options->filter
= false;
1791 return format_text($text, $format, $options);