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');
66 var $request = array();
68 var $is_collapsible = false;
69 var $is_sortable = false;
70 var $use_pages = false;
71 var $use_initials = false;
77 var $sort_default_column = NULL;
78 var $sort_default_order = SORT_ASC
;
81 * Array of positions in which to display download controls.
83 var $showdownloadbuttonsat= array(TABLE_P_TOP
);
86 * @var string Key of field returned by db query that is the id field of the
87 * user table or equivalent.
89 public $useridfield = 'id';
92 * @var string which download plugin to use. Default '' means none - print
93 * html table with paging. Property set by is_downloading which typically
94 * passes in cleaned data from $
99 * @var bool whether data is downloadable from table. Determines whether
100 * to display download buttons. Set by method downloadable().
102 var $downloadable = false;
105 * @var string which download plugin to use. Default '' means none - print
106 * html table with paging.
108 var $defaultdownloadformat = 'csv';
111 * @var bool Has start output been called yet?
113 var $started_output = false;
115 var $exportclass = null;
119 * @param int $uniqueid all tables have to have a unique id, this is used
120 * as a key when storing table properties like sort order in the session.
122 function __construct($uniqueid) {
123 $this->uniqueid
= $uniqueid;
124 $this->request
= array(
125 TABLE_VAR_SORT
=> 'tsort',
126 TABLE_VAR_HIDE
=> 'thide',
127 TABLE_VAR_SHOW
=> 'tshow',
128 TABLE_VAR_IFIRST
=> 'tifirst',
129 TABLE_VAR_ILAST
=> 'tilast',
130 TABLE_VAR_PAGE
=> 'page',
135 * Backwards-compatible constructor, so that legacy code subclassing
136 * flexible_table does not break.
137 * @deprecated since Moodle 2.0. Will be removed in Moodle 2.1.
139 function flexible_table($uniqueid) {
140 debugging('Please update your code to user PHP5-style parent::__construct(...), ' .
141 'not parent::flexible_table(...).');
142 $this->__construct($uniqueid);
146 * Call this to pass the download type. Use :
147 * $download = optional_param('download', '', PARAM_ALPHA);
148 * To get the download type. We assume that if you call this function with
149 * params that this table's data is downloadable, so we call is_downloadable
150 * for you (even if the param is '', which means no download this time.
151 * Also you can call this method with no params to get the current set
153 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
154 * @param string $filename filename for downloads without file extension.
155 * @param string $sheettitle title for downloaded data.
156 * @return string download type. One of csv, tsv, xhtml, ods, etc
158 function is_downloading($download = null, $filename='', $sheettitle='') {
159 if ($download!==null) {
160 $this->sheettitle
= $sheettitle;
161 $this->is_downloadable(true);
162 $this->download
= $download;
163 $this->filename
= clean_filename($filename);
164 $this->export_class_instance();
166 return $this->download
;
170 * Get, and optionally set, the export class.
171 * @param $exportclass (optional) if passed, set the table to use this export class.
172 * @return table_default_export_format_parent the export class in use (after any set).
174 function export_class_instance($exportclass = null) {
175 if (!is_null($exportclass)) {
176 $this->started_output
= true;
177 $this->exportclass
= $exportclass;
178 $this->exportclass
->table
= $this;
179 } else if (is_null($this->exportclass
) && !empty($this->download
)) {
180 $classname = 'table_'.$this->download
.'_export_format';
181 $this->exportclass
= new $classname($this);
182 if (!$this->exportclass
->document_started()) {
183 $this->exportclass
->start_document($this->filename
);
186 return $this->exportclass
;
190 * Probably don't need to call this directly. Calling is_downloading with a
191 * param automatically sets table as downloadable.
193 * @param bool $downloadable optional param to set whether data from
194 * table is downloadable. If ommitted this function can be used to get
195 * current state of table.
196 * @return bool whether table data is set to be downloadable.
198 function is_downloadable($downloadable = null) {
199 if ($downloadable !== null) {
200 $this->downloadable
= $downloadable;
202 return $this->downloadable
;
206 * Where to show download buttons.
207 * @param array $showat array of postions in which to show download buttons.
208 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
210 function show_download_buttons_at($showat) {
211 $this->showdownloadbuttonsat
= $showat;
215 * Sets the is_sortable variable to the given boolean, sort_default_column to
216 * the given string, and the sort_default_order to the given integer.
218 * @param string $defaultcolumn
219 * @param int $defaultorder
222 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC
) {
223 $this->is_sortable
= $bool;
224 $this->sort_default_column
= $defaultcolumn;
225 $this->sort_default_order
= $defaultorder;
229 * Do not sort using this column
230 * @param string column name
232 function no_sorting($column) {
233 $this->column_nosort
[] = $column;
237 * Is the column sortable?
238 * @param string column name, null means table
241 function is_sortable($column = null) {
242 if (empty($column)) {
243 return $this->is_sortable
;
245 if (!$this->is_sortable
) {
248 return !in_array($column, $this->column_nosort
);
252 * Sets the is_collapsible variable to the given boolean.
256 function collapsible($bool) {
257 $this->is_collapsible
= $bool;
261 * Sets the use_pages variable to the given boolean.
265 function pageable($bool) {
266 $this->use_pages
= $bool;
270 * Sets the use_initials variable to the given boolean.
274 function initialbars($bool) {
275 $this->use_initials
= $bool;
279 * Sets the pagesize variable to the given integer, the totalrows variable
280 * to the given integer, and the use_pages variable to true.
281 * @param int $perpage
285 function pagesize($perpage, $total) {
286 $this->pagesize
= $perpage;
287 $this->totalrows
= $total;
288 $this->use_pages
= true;
292 * Assigns each given variable in the array to the corresponding index
293 * in the request class variable.
294 * @param array $variables
297 function set_control_variables($variables) {
298 foreach ($variables as $what => $variable) {
299 if (isset($this->request
[$what])) {
300 $this->request
[$what] = $variable;
306 * Gives the given $value to the $attribute index of $this->attributes.
307 * @param string $attribute
308 * @param mixed $value
311 function set_attribute($attribute, $value) {
312 $this->attributes
[$attribute] = $value;
316 * What this method does is set the column so that if the same data appears in
317 * consecutive rows, then it is not repeated.
319 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
320 * that when one student has made multiple attempts, their name is only printed in the row
321 * for their first attempt.
322 * @param int $column the index of a column.
324 function column_suppress($column) {
325 if (isset($this->column_suppress
[$column])) {
326 $this->column_suppress
[$column] = true;
331 * Sets the given $column index to the given $classname in $this->column_class.
333 * @param string $classname
336 function column_class($column, $classname) {
337 if (isset($this->column_class
[$column])) {
338 $this->column_class
[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
343 * Sets the given $column index and $property index to the given $value in $this->column_style.
345 * @param string $property
346 * @param mixed $value
349 function column_style($column, $property, $value) {
350 if (isset($this->column_style
[$column])) {
351 $this->column_style
[$column][$property] = $value;
356 * Sets all columns' $propertys to the given $value in $this->column_style.
357 * @param int $property
358 * @param string $value
361 function column_style_all($property, $value) {
362 foreach (array_keys($this->columns
) as $column) {
363 $this->column_style
[$column][$property] = $value;
368 * Sets $this->baseurl.
369 * @param moodle_url|string $url the url with params needed to call up this page
371 function define_baseurl($url) {
372 $this->baseurl
= new moodle_url($url);
376 * @param array $columns an array of identifying names for columns. If
377 * columns are sorted then column names must correspond to a field in sql.
379 function define_columns($columns) {
380 $this->columns
= array();
381 $this->column_style
= array();
382 $this->column_class
= array();
385 foreach ($columns as $column) {
386 $this->columns
[$column] = $colnum++
;
387 $this->column_style
[$column] = array();
388 $this->column_class
[$column] = '';
389 $this->column_suppress
[$column] = false;
394 * @param array $headers numerical keyed array of displayed string titles
397 function define_headers($headers) {
398 $this->headers
= $headers;
402 * Must be called after table is defined. Use methods above first. Cannot
403 * use functions below till after calling this method.
407 global $SESSION, $CFG;
409 if (empty($this->columns
) ||
empty($this->uniqueid
)) {
413 if (!isset($SESSION->flextable
)) {
414 $SESSION->flextable
= array();
417 if (!isset($SESSION->flextable
[$this->uniqueid
])) {
418 $SESSION->flextable
[$this->uniqueid
] = new stdClass
;
419 $SESSION->flextable
[$this->uniqueid
]->uniqueid
= $this->uniqueid
;
420 $SESSION->flextable
[$this->uniqueid
]->collapse
= array();
421 $SESSION->flextable
[$this->uniqueid
]->sortby
= array();
422 $SESSION->flextable
[$this->uniqueid
]->i_first
= '';
423 $SESSION->flextable
[$this->uniqueid
]->i_last
= '';
426 $this->sess
= &$SESSION->flextable
[$this->uniqueid
];
428 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
429 isset($this->columns
[$showcol])) {
430 $this->sess
->collapse
[$showcol] = false;
432 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
433 isset($this->columns
[$hidecol])) {
434 $this->sess
->collapse
[$hidecol] = true;
435 if (array_key_exists($hidecol, $this->sess
->sortby
)) {
436 unset($this->sess
->sortby
[$hidecol]);
440 // Now, update the column attributes for collapsed columns
441 foreach (array_keys($this->columns
) as $column) {
442 if (!empty($this->sess
->collapse
[$column])) {
443 $this->column_style
[$column]['width'] = '10px';
447 if (($sortcol = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
)) &&
448 $this->is_sortable($sortcol) && empty($this->sess
->collapse
[$sortcol]) &&
449 (isset($this->columns
[$sortcol]) ||
in_array($sortcol, array('firstname', 'lastname')) && isset($this->columns
['fullname']))) {
451 if (array_key_exists($sortcol, $this->sess
->sortby
)) {
452 // This key already exists somewhere. Change its sortorder and bring it to the top.
453 $sortorder = $this->sess
->sortby
[$sortcol] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
454 unset($this->sess
->sortby
[$sortcol]);
455 $this->sess
->sortby
= array_merge(array($sortcol => $sortorder), $this->sess
->sortby
);
457 // Key doesn't exist, so just add it to the beginning of the array, ascending order
458 $this->sess
->sortby
= array_merge(array($sortcol => SORT_ASC
), $this->sess
->sortby
);
461 // Finally, make sure that no more than $this->maxsortkeys are present into the array
462 $this->sess
->sortby
= array_slice($this->sess
->sortby
, 0, $this->maxsortkeys
);
465 // If we didn't sort just now, then use the default sort order if one is defined and the column exists
466 if (empty($this->sess
->sortby
) && !empty($this->sort_default_column
)) {
467 $this->sess
->sortby
= array ($this->sort_default_column
=> ($this->sort_default_order
== SORT_DESC ? SORT_DESC
: SORT_ASC
));
470 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
471 if (!is_null($ilast) && ($ilast ==='' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
472 $this->sess
->i_last
= $ilast;
475 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
476 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
477 $this->sess
->i_first
= $ifirst;
480 if (empty($this->baseurl
)) {
481 debugging('You should set baseurl when using flexible_table.');
483 $this->baseurl
= $PAGE->url
;
486 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
489 // Always introduce the "flexible" class for the table if not specified
490 if (empty($this->attributes
)) {
491 $this->attributes
['class'] = 'flexible';
492 } else if (!isset($this->attributes
['class'])) {
493 $this->attributes
['class'] = 'flexible';
494 } else if (!in_array('flexible', explode(' ', $this->attributes
['class']))) {
495 $this->attributes
['class'] = trim('flexible ' . $this->attributes
['class']);
500 * Get the order by clause from the session, for the table with id $uniqueid.
501 * @param string $uniqueid the identifier for a table.
502 * @return SQL fragment that can be used in an ORDER BY clause.
504 public static function get_sort_for_table($uniqueid) {
506 if (empty($SESSION->flextable
[$uniqueid])) {
510 $sess = &$SESSION->flextable
[$uniqueid];
511 if (empty($sess->sortby
)) {
515 return self
::construct_order_by($sess->sortby
);
519 * Prepare an an order by clause from the list of columns to be sorted.
520 * @param array $cols column name => SORT_ASC or SORT_DESC
521 * @return SQL fragment that can be used in an ORDER BY clause.
523 public static function construct_order_by($cols) {
526 foreach ($cols as $column => $order) {
527 if ($order == SORT_ASC
) {
528 $bits[] = $column . ' ASC';
530 $bits[] = $column . ' DESC';
534 return implode(', ', $bits);
538 * @return SQL fragment that can be used in an ORDER BY clause.
540 public function get_sql_sort() {
541 return self
::construct_order_by($this->get_sort_columns());
545 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
546 * @return array column name => SORT_... constant.
548 public function get_sort_columns() {
550 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
553 if (empty($this->sess
->sortby
)) {
557 foreach ($this->sess
->sortby
as $column => $notused) {
558 if (isset($this->columns
[$column])) {
559 continue; // This column is OK.
561 if (in_array($column, array('firstname', 'lastname')) &&
562 isset($this->columns
['fullname'])) {
563 continue; // This column is OK.
565 // This column is not OK.
566 unset($this->sess
->sortby
[$column]);
569 return $this->sess
->sortby
;
573 * @return int the offset for LIMIT clause of SQL
575 function get_page_start() {
576 if (!$this->use_pages
) {
579 return $this->currpage
* $this->pagesize
;
583 * @return int the pagesize for LIMIT clause of SQL
585 function get_page_size() {
586 if (!$this->use_pages
) {
589 return $this->pagesize
;
593 * @return string sql to add to where statement.
595 function get_sql_where() {
598 $conditions = array();
601 if (isset($this->columns
['fullname'])) {
605 if (!empty($this->sess
->i_first
)) {
606 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
607 $params['ifirstc'.$i] = $this->sess
->i_first
.'%';
609 if (!empty($this->sess
->i_last
)) {
610 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
611 $params['ilastc'.$i] = $this->sess
->i_last
.'%';
615 return array(implode(" AND ", $conditions), $params);
619 * Add a row of data to the table. This function takes an array with
620 * column names as keys.
621 * It ignores any elements with keys that are not defined as columns. It
622 * puts in empty strings into the row when there is no element in the passed
623 * array corresponding to a column in the table. It puts the row elements in
625 * @param $rowwithkeys array
626 * @param string $classname CSS class name to add to this row's tr tag.
628 function add_data_keyed($rowwithkeys, $classname = '') {
629 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
633 * Add a seperator line to table.
635 function add_separator() {
639 $this->add_data(NULL);
643 * This method actually directly echoes the row passed to it now or adds it
644 * to the download. If this is the first row and start_output has not
645 * already been called this method also calls start_output to open the table
646 * or send headers for the downloaded.
647 * Can be used as before. print_html now calls finish_html to close table.
649 * @param array $row a numerically keyed row of data to add to the table.
650 * @param string $classname CSS class name to add to this row's tr tag.
651 * @return bool success.
653 function add_data($row, $classname = '') {
657 if (!$this->started_output
) {
658 $this->start_output();
660 if ($this->exportclass
!==null) {
662 $this->exportclass
->add_seperator();
664 $this->exportclass
->add_data($row);
667 $this->print_row($row, $classname);
673 * You should call this to finish outputting the table data after adding
674 * data to the table with add_data or add_data_keyed.
677 function finish_output($closeexportclassdoc = true) {
678 if ($this->exportclass
!==null) {
679 $this->exportclass
->finish_table();
680 if ($closeexportclassdoc) {
681 $this->exportclass
->finish_document();
684 $this->finish_html();
689 * Hook that can be overridden in child classes to wrap a table in a form
690 * for example. Called only when there is data to display and not
693 function wrap_html_start() {
697 * Hook that can be overridden in child classes to wrap a table in a form
698 * for example. Called only when there is data to display and not
701 function wrap_html_finish() {
706 * @param array $row row of data from db used to make one row of the table.
707 * @return array one row for the table, added using add_data_keyed method.
709 function format_row($row) {
710 $formattedrow = array();
711 foreach (array_keys($this->columns
) as $column) {
712 $colmethodname = 'col_'.$column;
713 if (method_exists($this, $colmethodname)) {
714 $formattedcolumn = $this->$colmethodname($row);
716 $formattedcolumn = $this->other_cols($column, $row);
717 if ($formattedcolumn===NULL) {
718 $formattedcolumn = $row->$column;
721 $formattedrow[$column] = $formattedcolumn;
723 return $formattedrow;
727 * Fullname is treated as a special columname in tablelib and should always
728 * be treated the same as the fullname of a user.
729 * @uses $this->useridfield if the userid field is not expected to be id
730 * then you need to override $this->useridfield to point at the correct
731 * field for the user id.
734 function col_fullname($row) {
735 global $COURSE, $CFG;
737 if (!$this->download
) {
738 $profileurl = new moodle_url('/user/profile.php', array('id' => $row->{$this->useridfield
}));
739 if ($COURSE->id
!= SITEID
) {
740 $profileurl->param('course', $COURSE->id
);
742 return html_writer
::link($profileurl, fullname($row));
745 return fullname($row);
750 * You can override this method in a child class. See the description of
751 * build_table which calls this method.
753 function other_cols($column, $row) {
758 * Used from col_* functions when text is to be displayed. Does the
759 * right thing - either converts text to html or strips any html tags
760 * depending on if we are downloading and what is the download type. Params
761 * are the same as format_text function in weblib.php but some default
762 * options are changed.
764 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
765 if (!$this->is_downloading()) {
766 if (is_null($options)) {
767 $options = new stdClass
;
769 //some sensible defaults
770 if (!isset($options->para
)) {
771 $options->para
= false;
773 if (!isset($options->newlines
)) {
774 $options->newlines
= false;
776 if (!isset($options->smiley
)) {
777 $options->smiley
= false;
779 if (!isset($options->filter
)) {
780 $options->filter
= false;
782 return format_text($text, $format, $options);
784 $eci =& $this->export_class_instance();
785 return $eci->format_text($text, $format, $options, $courseid);
789 * This method is deprecated although the old api is still supported.
790 * @deprecated 1.9.2 - Jun 2, 2008
792 function print_html() {
796 $this->finish_html();
800 * This function is not part of the public api.
801 * @return string initial of first name we are currently filtering by
803 function get_initial_first() {
804 if (!$this->use_initials
) {
808 return $this->sess
->i_first
;
812 * This function is not part of the public api.
813 * @return string initial of last name we are currently filtering by
815 function get_initial_last() {
816 if (!$this->use_initials
) {
820 return $this->sess
->i_last
;
824 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
825 * @param array $alpha of letters in the alphabet.
826 * @param string $current the currently selected letter.
827 * @param string $class class name to add to this initial bar.
828 * @param string $title the name to put in front of this initial bar.
829 * @param string $urlvar URL parameter name for this initial.
831 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
832 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
835 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
837 echo html_writer
::tag('strong', get_string('all'));
840 foreach ($alpha as $letter) {
841 if ($letter === $current) {
842 echo html_writer
::tag('strong', $letter);
844 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
848 echo html_writer
::end_tag('div');
852 * This function is not part of the public api.
854 function print_initials_bar() {
855 if ((!empty($this->sess
->i_last
) ||
!empty($this->sess
->i_first
) ||
$this->use_initials
)
856 && isset($this->columns
['fullname'])) {
858 $alpha = explode(',', get_string('alphabet', 'langconfig'));
860 // Bar of first initials
861 if (!empty($this->sess
->i_first
)) {
862 $ifirst = $this->sess
->i_first
;
866 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
867 get_string('firstname'), $this->request
[TABLE_VAR_IFIRST
]);
869 // Bar of last initials
870 if (!empty($this->sess
->i_last
)) {
871 $ilast = $this->sess
->i_last
;
875 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
876 get_string('lastname'), $this->request
[TABLE_VAR_ILAST
]);
881 * This function is not part of the public api.
883 function print_nothing_to_display() {
885 $this->print_initials_bar();
887 echo $OUTPUT->heading(get_string('nothingtodisplay'));
891 * This function is not part of the public api.
893 function get_row_from_keyed($rowwithkeys) {
894 if (is_object($rowwithkeys)) {
895 $rowwithkeys = (array)$rowwithkeys;
898 foreach (array_keys($this->columns
) as $column) {
899 if (isset($rowwithkeys[$column])) {
900 $row [] = $rowwithkeys[$column];
908 * This function is not part of the public api.
910 function get_download_menu() {
911 $allclasses= get_declared_classes();
912 $exportclasses = array();
913 foreach ($allclasses as $class) {
915 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
917 $exportclasses[$type]= get_string("download$type", 'table');
920 return $exportclasses;
924 * This function is not part of the public api.
926 function download_buttons() {
927 if ($this->is_downloadable() && !$this->is_downloading()) {
928 $downloadoptions = $this->get_download_menu();
929 $html = '<form action="'. $this->baseurl
.'" method="post">';
930 $html .= '<div class="mdl-align">';
931 $html .= '<input type="submit" value="'.get_string('downloadas', 'table').'"/>';
932 $html .= html_writer
::label(get_string('downloadoptions', 'table'), 'menudownload', false, array('class' => 'accesshide'));
933 $html .= html_writer
::select($downloadoptions, 'download', $this->defaultdownloadformat
, false);
934 $html .= '</div></form>';
942 * This function is not part of the public api.
943 * You don't normally need to call this. It is called automatically when
944 * needed when you start adding data to the table.
947 function start_output() {
948 $this->started_output
= true;
949 if ($this->exportclass
!==null) {
950 $this->exportclass
->start_table($this->sheettitle
);
951 $this->exportclass
->output_headers($this->headers
);
954 $this->print_headers();
959 * This function is not part of the public api.
961 function print_row($row, $classname = '') {
962 static $suppress_lastrow = NULL;
964 $rowclasses = array('r' . $oddeven);
965 $oddeven = $oddeven ?
0 : 1;
968 $rowclasses[] = $classname;
971 echo html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses)));
973 // If we have a separator, print it
975 $colcount = count($this->columns
);
976 echo html_writer
::tag('td', html_writer
::tag('div', '',
977 array('class' => 'tabledivider')), array('colspan' => $colcount));
980 $colbyindex = array_flip($this->columns
);
981 foreach ($row as $index => $data) {
982 $column = $colbyindex[$index];
984 if (empty($this->sess
->collapse
[$column])) {
985 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
994 echo html_writer
::tag('td', $content, array(
995 'class' => 'cell c' . $index . $this->column_class
[$column],
996 'style' => $this->make_styles_string($this->column_style
[$column])));
1000 echo html_writer
::end_tag('tr');
1002 $suppress_enabled = array_sum($this->column_suppress
);
1003 if ($suppress_enabled) {
1004 $suppress_lastrow = $row;
1009 * This function is not part of the public api.
1011 function finish_html() {
1013 if (!$this->started_output
) {
1014 //no data has been added to the table.
1015 $this->print_nothing_to_display();
1018 echo html_writer
::end_tag('table');
1019 echo html_writer
::end_tag('div');
1020 $this->wrap_html_finish();
1023 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1024 echo $this->download_buttons();
1027 if($this->use_pages
) {
1028 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1029 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1030 echo $OUTPUT->render($pagingbar);
1036 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1037 * used by {@link print_headers()}.
1038 * @param string $column the column name, index into various names.
1039 * @param int $index numerical index of the column.
1040 * @return string HTML fragment.
1042 protected function show_hide_link($column, $index) {
1044 // Some headers contain <br /> tags, do not include in title, hence the
1047 if (!empty($this->sess
->collapse
[$column])) {
1048 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1049 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1050 array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index])));
1052 } else if ($this->headers
[$index] !== NULL) {
1053 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1054 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1055 array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index])));
1060 * This function is not part of the public api.
1062 function print_headers() {
1063 global $CFG, $OUTPUT;
1065 echo html_writer
::start_tag('tr');
1066 foreach ($this->columns
as $column => $index) {
1069 if ($this->is_collapsible
) {
1070 $icon_hide = $this->show_hide_link($column, $index);
1073 $primary_sort_column = '';
1074 $primary_sort_order = '';
1075 if (reset($this->sess
->sortby
)) {
1076 $primary_sort_column = key($this->sess
->sortby
);
1077 $primary_sort_order = current($this->sess
->sortby
);
1083 if ($this->is_sortable($column)) {
1084 $firstnamesortlink = $this->sort_link(get_string('firstname'),
1085 'firstname', $primary_sort_column === 'firstname', $primary_sort_order);
1087 $lastnamesortlink = $this->sort_link(get_string('lastname'),
1088 'lastname', $primary_sort_column === 'lastname', $primary_sort_order);
1090 $override = new stdClass();
1091 $override->firstname
= 'firstname';
1092 $override->lastname
= 'lastname';
1093 $fullnamelanguage = get_string('fullnamedisplay', '', $override);
1095 if (($CFG->fullnamedisplay
== 'firstname lastname') or
1096 ($CFG->fullnamedisplay
== 'firstname') or
1097 ($CFG->fullnamedisplay
== 'language' and $fullnamelanguage == 'firstname lastname' )) {
1098 $this->headers
[$index] = $firstnamesortlink . ' / ' . $lastnamesortlink;
1100 $this->headers
[$index] = $lastnamesortlink . ' / ' . $firstnamesortlink;
1106 // do nothing, do not display sortable links
1110 if ($this->is_sortable($column)) {
1111 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1112 $column, $primary_sort_column == $column, $primary_sort_order);
1116 $attributes = array(
1117 'class' => 'header c' . $index . $this->column_class
[$column],
1120 if ($this->headers
[$index] === NULL) {
1121 $content = ' ';
1122 } else if (!empty($this->sess
->collapse
[$column])) {
1123 $content = $icon_hide;
1125 if (is_array($this->column_style
[$column])) {
1126 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1128 $content = $this->headers
[$index] . html_writer
::tag('div',
1129 $icon_hide, array('class' => 'commands'));
1131 echo html_writer
::tag('th', $content, $attributes);
1134 echo html_writer
::end_tag('tr');
1138 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1139 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1140 * @param int $order SORT_ASC or SORT_DESC
1141 * @return string HTML fragment.
1143 protected function sort_icon($isprimary, $order) {
1150 if ($order == SORT_ASC
) {
1151 return html_writer
::empty_tag('img',
1152 array('src' => $OUTPUT->pix_url('t/down'), 'alt' => get_string('asc')));
1154 return html_writer
::empty_tag('img',
1155 array('src' => $OUTPUT->pix_url('t/up'), 'alt' => get_string('desc')));
1160 * Generate the correct tool tip for changing the sort order. This is a
1161 * helper method used by {@link sort_link()}.
1162 * @param bool $isprimary whether the is column is the current primary sort column.
1163 * @param int $order SORT_ASC or SORT_DESC
1164 * @return string the correct title.
1166 protected function sort_order_name($isprimary, $order) {
1167 if ($isprimary && $order != SORT_ASC
) {
1168 return get_string('desc');
1170 return get_string('asc');
1175 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1176 * @param string $text the text for the link.
1177 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1178 * @param bool $isprimary whether the is column is the current primary sort column.
1179 * @param int $order SORT_ASC or SORT_DESC
1180 * @return string HTML fragment.
1182 protected function sort_link($text, $column, $isprimary, $order) {
1183 return html_writer
::link($this->baseurl
->out(false,
1184 array($this->request
[TABLE_VAR_SORT
] => $column)),
1185 $text . get_accesshide(get_string('sortby') . ' ' .
1186 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1187 $this->sort_icon($isprimary, $order);
1191 * This function is not part of the public api.
1193 function start_html() {
1195 // Do we need to print initial bars?
1196 $this->print_initials_bar();
1199 if ($this->use_pages
) {
1200 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1201 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1202 echo $OUTPUT->render($pagingbar);
1205 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1206 echo $this->download_buttons();
1209 $this->wrap_html_start();
1210 // Start of main data table
1212 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1213 echo html_writer
::start_tag('table', $this->attributes
);
1218 * This function is not part of the public api.
1219 * @param array $styles CSS-property => value
1220 * @return string values suitably to go in a style="" attribute in HTML.
1222 function make_styles_string($styles) {
1223 if (empty($styles)) {
1228 foreach($styles as $property => $value) {
1229 $string .= $property . ':' . $value . ';';
1237 * @package moodlecore
1238 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1241 class table_sql
extends flexible_table
{
1243 public $countsql = NULL;
1244 public $countparams = NULL;
1246 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1250 * @var array Data fetched from the db.
1252 public $rawdata = NULL;
1255 * @var bool Overriding default for this.
1257 public $is_sortable = true;
1259 * @var bool Overriding default for this.
1261 public $is_collapsible = true;
1264 * @param string $uniqueid a string identifying this table.Used as a key in
1267 function __construct($uniqueid) {
1268 parent
::__construct($uniqueid);
1269 // some sensible defaults
1270 $this->set_attribute('cellspacing', '0');
1271 $this->set_attribute('class', 'generaltable generalbox');
1275 * Backwards-compatible constructor, so that legacy code subclassing
1276 * table_sql does not break.
1277 * @deprecated since Moodle 2.0. Will be removed in Moodle 2.1.
1279 function table_sql($uniqueid) {
1280 debugging('Please update your code to user PHP5-style parent::__construct(...), ' .
1281 'not parent::table_sql(...).');
1282 $this->__construct($uniqueid);
1286 * Take the data returned from the db_query and go through all the rows
1287 * processing each col using either col_{columnname} method or other_cols
1288 * method or if other_cols returns NULL then put the data straight into the
1291 function build_table() {
1292 if ($this->rawdata
) {
1293 foreach ($this->rawdata
as $row) {
1294 $formattedrow = $this->format_row($row);
1295 $this->add_data_keyed($formattedrow,
1296 $this->get_row_class($row));
1302 * Get any extra classes names to add to this row in the HTML.
1303 * @param $row array the data for this row.
1304 * @return string added to the class="" attribute of the tr.
1306 function get_row_class($row) {
1311 * This is only needed if you want to use different sql to count rows.
1312 * Used for example when perhaps all db JOINS are not needed when counting
1313 * records. You don't need to call this function the count_sql
1314 * will be generated automatically.
1316 * We need to count rows returned by the db seperately to the query itself
1317 * as we need to know how many pages of data we have to display.
1319 function set_count_sql($sql, array $params = NULL) {
1320 $this->countsql
= $sql;
1321 $this->countparams
= $params;
1325 * Set the sql to query the db. Query will be :
1326 * SELECT $fields FROM $from WHERE $where
1327 * Of course you can use sub-queries, JOINS etc. by putting them in the
1328 * appropriate clause of the query.
1330 function set_sql($fields, $from, $where, array $params = NULL) {
1331 $this->sql
= new stdClass();
1332 $this->sql
->fields
= $fields;
1333 $this->sql
->from
= $from;
1334 $this->sql
->where
= $where;
1335 $this->sql
->params
= $params;
1339 * Query the db. Store results in the table object for use by build_table.
1341 * @param int $pagesize size of page for paginated displayed table.
1342 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1343 * will only be used if there is a fullname column defined for the table.
1345 function query_db($pagesize, $useinitialsbar=true) {
1347 if (!$this->is_downloading()) {
1348 if ($this->countsql
=== NULL) {
1349 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1350 $this->countparams
= $this->sql
->params
;
1352 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1353 if ($useinitialsbar && !$this->is_downloading()) {
1354 $this->initialbars($grandtotal > $pagesize);
1357 list($wsql, $wparams) = $this->get_sql_where();
1359 $this->countsql
.= ' AND '.$wsql;
1360 $this->countparams
= array_merge($this->countparams
, $wparams);
1362 $this->sql
->where
.= ' AND '.$wsql;
1363 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1365 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1367 $total = $grandtotal;
1370 $this->pagesize($pagesize, $total);
1373 // Fetch the attempts
1374 $sort = $this->get_sql_sort();
1376 $sort = "ORDER BY $sort";
1379 {$this->sql->fields}
1380 FROM {$this->sql->from}
1381 WHERE {$this->sql->where}
1384 if (!$this->is_downloading()) {
1385 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
1387 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
1392 * Convenience method to call a number of methods for you to display the
1395 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1397 if (!$this->columns
) {
1398 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql
->params
);
1399 //if columns is not set then define columns as the keys of the rows returned
1401 $this->define_columns(array_keys((array)$onerow));
1402 $this->define_headers(array_keys((array)$onerow));
1405 $this->query_db($pagesize, $useinitialsbar);
1406 $this->build_table();
1407 $this->finish_output();
1413 * @package moodlecore
1414 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1417 class table_default_export_format_parent
{
1419 * @var flexible_table or child class reference pointing to table class
1420 * object from which to export data.
1425 * @var bool output started. Keeps track of whether any output has been
1428 var $documentstarted = false;
1429 function table_default_export_format_parent(&$table) {
1430 $this->table
=& $table;
1433 function set_table(&$table) {
1434 $this->table
=& $table;
1437 function add_data($row) {
1441 function add_seperator() {
1445 function document_started() {
1446 return $this->documentstarted
;
1449 * Given text in a variety of format codings, this function returns
1450 * the text as safe HTML or as plain text dependent on what is appropriate
1451 * for the download format. The default removes all tags.
1453 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1454 //use some whitespace to indicate where there was some line spacing.
1455 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1456 return strip_tags($text);
1462 * @package moodlecore
1463 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1466 class table_spreadsheet_export_format_parent
extends table_default_export_format_parent
{
1471 * @var object format object - format for normal table cells
1475 * @var object format object - format for header table cells
1480 * should be overriden in child class.
1485 * This method will be overridden in the child class.
1487 function define_workbook() {
1490 function start_document($filename) {
1491 $filename = $filename.'.'.$this->fileextension
;
1492 $this->define_workbook();
1494 $this->formatnormal
=& $this->workbook
->add_format();
1495 $this->formatnormal
->set_bold(0);
1496 $this->formatheaders
=& $this->workbook
->add_format();
1497 $this->formatheaders
->set_bold(1);
1498 $this->formatheaders
->set_align('center');
1499 // Sending HTTP headers
1500 $this->workbook
->send($filename);
1501 $this->documentstarted
= true;
1504 function start_table($sheettitle) {
1505 $this->worksheet
=& $this->workbook
->add_worksheet($sheettitle);
1509 function output_headers($headers) {
1511 foreach ($headers as $item) {
1512 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatheaders
);
1518 function add_data($row) {
1520 foreach ($row as $item) {
1521 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatnormal
);
1528 function add_seperator() {
1533 function finish_table() {
1536 function finish_document() {
1537 $this->workbook
->close();
1544 * @package moodlecore
1545 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1548 class table_excel_export_format
extends table_spreadsheet_export_format_parent
{
1549 var $fileextension = 'xls';
1551 function define_workbook() {
1553 require_once("$CFG->libdir/excellib.class.php");
1554 // Creating a workbook
1555 $this->workbook
= new MoodleExcelWorkbook("-");
1562 * @package moodlecore
1563 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1564 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1566 class table_ods_export_format
extends table_spreadsheet_export_format_parent
{
1567 var $fileextension = 'ods';
1568 function define_workbook() {
1570 require_once("$CFG->libdir/odslib.class.php");
1571 // Creating a workbook
1572 $this->workbook
= new MoodleODSWorkbook("-");
1578 * @package moodlecore
1579 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1582 class table_text_export_format_parent
extends table_default_export_format_parent
{
1583 protected $seperator = "\t";
1584 protected $mimetype = 'text/tab-separated-values';
1585 protected $ext = '.txt';
1587 public function start_document($filename) {
1588 $this->filename
= $filename . $this->ext
;
1589 header('Content-Type: ' . $this->mimetype
. '; charset=UTF-8');
1590 header('Content-Disposition: attachment; filename="' . $this->filename
. '"');
1591 header('Expires: 0');
1592 header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
1593 header('Pragma: public');
1594 $this->documentstarted
= true;
1597 public function start_table($sheettitle) {
1598 //nothing to do here
1601 public function output_headers($headers) {
1602 echo $this->format_row($headers);
1605 public function add_data($row) {
1606 echo $this->format_row($row);
1610 public function finish_table() {
1614 public function finish_document() {
1619 * Format a row of data.
1620 * @param array $data
1622 protected function format_row($data) {
1623 $escapeddata = array();
1624 foreach ($data as $value) {
1625 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1627 return implode($this->seperator
, $escapeddata) . "\n";
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_tsv_export_format
extends table_text_export_format_parent
{
1638 protected $seperator = "\t";
1639 protected $mimetype = 'text/tab-separated-values';
1640 protected $ext = '.txt';
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_csv_export_format
extends table_text_export_format_parent
{
1650 protected $seperator = ",";
1651 protected $mimetype = 'text/csv';
1652 protected $ext = '.csv';
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_xhtml_export_format
extends table_default_export_format_parent
{
1662 function start_document($filename) {
1663 header("Content-Type: application/download\n");
1664 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1665 header("Expires: 0");
1666 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1667 header("Pragma: public");
1670 <?xml version="1.0" encoding="UTF-8"?>
1672 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1673 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1675 <html xmlns="http://www.w3.org/1999/xhtml"
1676 xml:lang="en" lang="en">
1678 <style type="text/css">/*<![CDATA[*/
1683 th.header, td.header, div.header {
1684 border-color:#DDDDDD;
1685 background-color:lightGrey;
1700 body, table, td, th {
1701 font-family:Arial,Verdana,Helvetica,sans-serif;
1709 border-collapse:collapse;
1725 <title>$filename</title>
1729 $this->documentstarted
= true;
1732 function start_table($sheettitle) {
1733 $this->table
->sortable(false);
1734 $this->table
->collapsible(false);
1735 echo "<h2>{$sheettitle}</h2>";
1736 $this->table
->start_html();
1739 function output_headers($headers) {
1740 $this->table
->print_headers();
1743 function add_data($row) {
1744 $this->table
->print_row($row);
1748 function add_seperator() {
1749 $this->table
->print_row(NULL);
1753 function finish_table() {
1754 $this->table
->finish_html();
1757 function finish_document() {
1758 echo "</body>\n</html>";
1762 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1763 if (is_null($options)) {
1764 $options = new stdClass
;
1766 //some sensible defaults
1767 if (!isset($options->para
)) {
1768 $options->para
= false;
1770 if (!isset($options->newlines
)) {
1771 $options->newlines
= false;
1773 if (!isset($options->smiley
)) {
1774 $options->smiley
= false;
1776 if (!isset($options->filter
)) {
1777 $options->filter
= false;
1779 return format_text($text, $format, $options);