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 * Call this to pass the download type. Use :
136 * $download = optional_param('download', '', PARAM_ALPHA);
137 * To get the download type. We assume that if you call this function with
138 * params that this table's data is downloadable, so we call is_downloadable
139 * for you (even if the param is '', which means no download this time.
140 * Also you can call this method with no params to get the current set
142 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
143 * @param string $filename filename for downloads without file extension.
144 * @param string $sheettitle title for downloaded data.
145 * @return string download type. One of csv, tsv, xhtml, ods, etc
147 function is_downloading($download = null, $filename='', $sheettitle='') {
148 if ($download!==null) {
149 $this->sheettitle
= $sheettitle;
150 $this->is_downloadable(true);
151 $this->download
= $download;
152 $this->filename
= clean_filename($filename);
153 $this->export_class_instance();
155 return $this->download
;
159 * Get, and optionally set, the export class.
160 * @param $exportclass (optional) if passed, set the table to use this export class.
161 * @return table_default_export_format_parent the export class in use (after any set).
163 function export_class_instance($exportclass = null) {
164 if (!is_null($exportclass)) {
165 $this->started_output
= true;
166 $this->exportclass
= $exportclass;
167 $this->exportclass
->table
= $this;
168 } else if (is_null($this->exportclass
) && !empty($this->download
)) {
169 $classname = 'table_'.$this->download
.'_export_format';
170 $this->exportclass
= new $classname($this);
171 if (!$this->exportclass
->document_started()) {
172 $this->exportclass
->start_document($this->filename
);
175 return $this->exportclass
;
179 * Probably don't need to call this directly. Calling is_downloading with a
180 * param automatically sets table as downloadable.
182 * @param bool $downloadable optional param to set whether data from
183 * table is downloadable. If ommitted this function can be used to get
184 * current state of table.
185 * @return bool whether table data is set to be downloadable.
187 function is_downloadable($downloadable = null) {
188 if ($downloadable !== null) {
189 $this->downloadable
= $downloadable;
191 return $this->downloadable
;
195 * Where to show download buttons.
196 * @param array $showat array of postions in which to show download buttons.
197 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
199 function show_download_buttons_at($showat) {
200 $this->showdownloadbuttonsat
= $showat;
204 * Sets the is_sortable variable to the given boolean, sort_default_column to
205 * the given string, and the sort_default_order to the given integer.
207 * @param string $defaultcolumn
208 * @param int $defaultorder
211 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC
) {
212 $this->is_sortable
= $bool;
213 $this->sort_default_column
= $defaultcolumn;
214 $this->sort_default_order
= $defaultorder;
218 * Do not sort using this column
219 * @param string column name
221 function no_sorting($column) {
222 $this->column_nosort
[] = $column;
226 * Is the column sortable?
227 * @param string column name, null means table
230 function is_sortable($column = null) {
231 if (empty($column)) {
232 return $this->is_sortable
;
234 if (!$this->is_sortable
) {
237 return !in_array($column, $this->column_nosort
);
241 * Sets the is_collapsible variable to the given boolean.
245 function collapsible($bool) {
246 $this->is_collapsible
= $bool;
250 * Sets the use_pages variable to the given boolean.
254 function pageable($bool) {
255 $this->use_pages
= $bool;
259 * Sets the use_initials variable to the given boolean.
263 function initialbars($bool) {
264 $this->use_initials
= $bool;
268 * Sets the pagesize variable to the given integer, the totalrows variable
269 * to the given integer, and the use_pages variable to true.
270 * @param int $perpage
274 function pagesize($perpage, $total) {
275 $this->pagesize
= $perpage;
276 $this->totalrows
= $total;
277 $this->use_pages
= true;
281 * Assigns each given variable in the array to the corresponding index
282 * in the request class variable.
283 * @param array $variables
286 function set_control_variables($variables) {
287 foreach ($variables as $what => $variable) {
288 if (isset($this->request
[$what])) {
289 $this->request
[$what] = $variable;
295 * Gives the given $value to the $attribute index of $this->attributes.
296 * @param string $attribute
297 * @param mixed $value
300 function set_attribute($attribute, $value) {
301 $this->attributes
[$attribute] = $value;
305 * What this method does is set the column so that if the same data appears in
306 * consecutive rows, then it is not repeated.
308 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
309 * that when one student has made multiple attempts, their name is only printed in the row
310 * for their first attempt.
311 * @param int $column the index of a column.
313 function column_suppress($column) {
314 if (isset($this->column_suppress
[$column])) {
315 $this->column_suppress
[$column] = true;
320 * Sets the given $column index to the given $classname in $this->column_class.
322 * @param string $classname
325 function column_class($column, $classname) {
326 if (isset($this->column_class
[$column])) {
327 $this->column_class
[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
332 * Sets the given $column index and $property index to the given $value in $this->column_style.
334 * @param string $property
335 * @param mixed $value
338 function column_style($column, $property, $value) {
339 if (isset($this->column_style
[$column])) {
340 $this->column_style
[$column][$property] = $value;
345 * Sets all columns' $propertys to the given $value in $this->column_style.
346 * @param int $property
347 * @param string $value
350 function column_style_all($property, $value) {
351 foreach (array_keys($this->columns
) as $column) {
352 $this->column_style
[$column][$property] = $value;
357 * Sets $this->baseurl.
358 * @param moodle_url|string $url the url with params needed to call up this page
360 function define_baseurl($url) {
361 $this->baseurl
= new moodle_url($url);
365 * @param array $columns an array of identifying names for columns. If
366 * columns are sorted then column names must correspond to a field in sql.
368 function define_columns($columns) {
369 $this->columns
= array();
370 $this->column_style
= array();
371 $this->column_class
= array();
374 foreach ($columns as $column) {
375 $this->columns
[$column] = $colnum++
;
376 $this->column_style
[$column] = array();
377 $this->column_class
[$column] = '';
378 $this->column_suppress
[$column] = false;
383 * @param array $headers numerical keyed array of displayed string titles
386 function define_headers($headers) {
387 $this->headers
= $headers;
391 * Must be called after table is defined. Use methods above first. Cannot
392 * use functions below till after calling this method.
396 global $SESSION, $CFG;
398 if (empty($this->columns
) ||
empty($this->uniqueid
)) {
402 if (!isset($SESSION->flextable
)) {
403 $SESSION->flextable
= array();
406 if (!isset($SESSION->flextable
[$this->uniqueid
])) {
407 $SESSION->flextable
[$this->uniqueid
] = new stdClass
;
408 $SESSION->flextable
[$this->uniqueid
]->uniqueid
= $this->uniqueid
;
409 $SESSION->flextable
[$this->uniqueid
]->collapse
= array();
410 $SESSION->flextable
[$this->uniqueid
]->sortby
= array();
411 $SESSION->flextable
[$this->uniqueid
]->i_first
= '';
412 $SESSION->flextable
[$this->uniqueid
]->i_last
= '';
415 $this->sess
= &$SESSION->flextable
[$this->uniqueid
];
417 if (($showcol = optional_param($this->request
[TABLE_VAR_SHOW
], '', PARAM_ALPHANUMEXT
)) &&
418 isset($this->columns
[$showcol])) {
419 $this->sess
->collapse
[$showcol] = false;
421 } else if (($hidecol = optional_param($this->request
[TABLE_VAR_HIDE
], '', PARAM_ALPHANUMEXT
)) &&
422 isset($this->columns
[$hidecol])) {
423 $this->sess
->collapse
[$hidecol] = true;
424 if (array_key_exists($hidecol, $this->sess
->sortby
)) {
425 unset($this->sess
->sortby
[$hidecol]);
429 // Now, update the column attributes for collapsed columns
430 foreach (array_keys($this->columns
) as $column) {
431 if (!empty($this->sess
->collapse
[$column])) {
432 $this->column_style
[$column]['width'] = '10px';
436 if (($sortcol = optional_param($this->request
[TABLE_VAR_SORT
], '', PARAM_ALPHANUMEXT
)) &&
437 $this->is_sortable($sortcol) && empty($this->sess
->collapse
[$sortcol]) &&
438 (isset($this->columns
[$sortcol]) ||
in_array($sortcol, array('firstname', 'lastname')) && isset($this->columns
['fullname']))) {
440 if (array_key_exists($sortcol, $this->sess
->sortby
)) {
441 // This key already exists somewhere. Change its sortorder and bring it to the top.
442 $sortorder = $this->sess
->sortby
[$sortcol] == SORT_ASC ? SORT_DESC
: SORT_ASC
;
443 unset($this->sess
->sortby
[$sortcol]);
444 $this->sess
->sortby
= array_merge(array($sortcol => $sortorder), $this->sess
->sortby
);
446 // Key doesn't exist, so just add it to the beginning of the array, ascending order
447 $this->sess
->sortby
= array_merge(array($sortcol => SORT_ASC
), $this->sess
->sortby
);
450 // Finally, make sure that no more than $this->maxsortkeys are present into the array
451 $this->sess
->sortby
= array_slice($this->sess
->sortby
, 0, $this->maxsortkeys
);
454 // 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.
455 // This prevents results from being returned in a random order if the only order by column contains equal values.
456 if (!empty($this->sort_default_column
)) {
457 if (!array_key_exists($this->sort_default_column
, $this->sess
->sortby
)) {
458 $defaultsort = array($this->sort_default_column
=> $this->sort_default_order
);
459 $this->sess
->sortby
= array_merge($this->sess
->sortby
, $defaultsort);
463 $ilast = optional_param($this->request
[TABLE_VAR_ILAST
], null, PARAM_RAW
);
464 if (!is_null($ilast) && ($ilast ==='' ||
strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
465 $this->sess
->i_last
= $ilast;
468 $ifirst = optional_param($this->request
[TABLE_VAR_IFIRST
], null, PARAM_RAW
);
469 if (!is_null($ifirst) && ($ifirst === '' ||
strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
470 $this->sess
->i_first
= $ifirst;
473 if (empty($this->baseurl
)) {
474 debugging('You should set baseurl when using flexible_table.');
476 $this->baseurl
= $PAGE->url
;
479 $this->currpage
= optional_param($this->request
[TABLE_VAR_PAGE
], 0, PARAM_INT
);
482 // Always introduce the "flexible" class for the table if not specified
483 if (empty($this->attributes
)) {
484 $this->attributes
['class'] = 'flexible';
485 } else if (!isset($this->attributes
['class'])) {
486 $this->attributes
['class'] = 'flexible';
487 } else if (!in_array('flexible', explode(' ', $this->attributes
['class']))) {
488 $this->attributes
['class'] = trim('flexible ' . $this->attributes
['class']);
493 * Get the order by clause from the session, for the table with id $uniqueid.
494 * @param string $uniqueid the identifier for a table.
495 * @return SQL fragment that can be used in an ORDER BY clause.
497 public static function get_sort_for_table($uniqueid) {
499 if (empty($SESSION->flextable
[$uniqueid])) {
503 $sess = &$SESSION->flextable
[$uniqueid];
504 if (empty($sess->sortby
)) {
508 return self
::construct_order_by($sess->sortby
);
512 * Prepare an an order by clause from the list of columns to be sorted.
513 * @param array $cols column name => SORT_ASC or SORT_DESC
514 * @return SQL fragment that can be used in an ORDER BY clause.
516 public static function construct_order_by($cols) {
519 foreach ($cols as $column => $order) {
520 if ($order == SORT_ASC
) {
521 $bits[] = $column . ' ASC';
523 $bits[] = $column . ' DESC';
527 return implode(', ', $bits);
531 * @return SQL fragment that can be used in an ORDER BY clause.
533 public function get_sql_sort() {
534 return self
::construct_order_by($this->get_sort_columns());
538 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
539 * @return array column name => SORT_... constant.
541 public function get_sort_columns() {
543 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
546 if (empty($this->sess
->sortby
)) {
550 foreach ($this->sess
->sortby
as $column => $notused) {
551 if (isset($this->columns
[$column])) {
552 continue; // This column is OK.
554 if (in_array($column, array('firstname', 'lastname')) &&
555 isset($this->columns
['fullname'])) {
556 continue; // This column is OK.
558 // This column is not OK.
559 unset($this->sess
->sortby
[$column]);
562 return $this->sess
->sortby
;
566 * @return int the offset for LIMIT clause of SQL
568 function get_page_start() {
569 if (!$this->use_pages
) {
572 return $this->currpage
* $this->pagesize
;
576 * @return int the pagesize for LIMIT clause of SQL
578 function get_page_size() {
579 if (!$this->use_pages
) {
582 return $this->pagesize
;
586 * @return string sql to add to where statement.
588 function get_sql_where() {
591 $conditions = array();
594 if (isset($this->columns
['fullname'])) {
598 if (!empty($this->sess
->i_first
)) {
599 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
600 $params['ifirstc'.$i] = $this->sess
->i_first
.'%';
602 if (!empty($this->sess
->i_last
)) {
603 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
604 $params['ilastc'.$i] = $this->sess
->i_last
.'%';
608 return array(implode(" AND ", $conditions), $params);
612 * Add a row of data to the table. This function takes an array with
613 * column names as keys.
614 * It ignores any elements with keys that are not defined as columns. It
615 * puts in empty strings into the row when there is no element in the passed
616 * array corresponding to a column in the table. It puts the row elements in
618 * @param $rowwithkeys array
619 * @param string $classname CSS class name to add to this row's tr tag.
621 function add_data_keyed($rowwithkeys, $classname = '') {
622 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
626 * Add a seperator line to table.
628 function add_separator() {
632 $this->add_data(NULL);
636 * This method actually directly echoes the row passed to it now or adds it
637 * to the download. If this is the first row and start_output has not
638 * already been called this method also calls start_output to open the table
639 * or send headers for the downloaded.
640 * Can be used as before. print_html now calls finish_html to close table.
642 * @param array $row a numerically keyed row of data to add to the table.
643 * @param string $classname CSS class name to add to this row's tr tag.
644 * @return bool success.
646 function add_data($row, $classname = '') {
650 if (!$this->started_output
) {
651 $this->start_output();
653 if ($this->exportclass
!==null) {
655 $this->exportclass
->add_seperator();
657 $this->exportclass
->add_data($row);
660 $this->print_row($row, $classname);
666 * You should call this to finish outputting the table data after adding
667 * data to the table with add_data or add_data_keyed.
670 function finish_output($closeexportclassdoc = true) {
671 if ($this->exportclass
!==null) {
672 $this->exportclass
->finish_table();
673 if ($closeexportclassdoc) {
674 $this->exportclass
->finish_document();
677 $this->finish_html();
682 * Hook that can be overridden in child classes to wrap a table in a form
683 * for example. Called only when there is data to display and not
686 function wrap_html_start() {
690 * Hook that can be overridden in child classes to wrap a table in a form
691 * for example. Called only when there is data to display and not
694 function wrap_html_finish() {
699 * @param array $row row of data from db used to make one row of the table.
700 * @return array one row for the table, added using add_data_keyed method.
702 function format_row($row) {
703 $formattedrow = array();
704 foreach (array_keys($this->columns
) as $column) {
705 $colmethodname = 'col_'.$column;
706 if (method_exists($this, $colmethodname)) {
707 $formattedcolumn = $this->$colmethodname($row);
709 $formattedcolumn = $this->other_cols($column, $row);
710 if ($formattedcolumn===NULL) {
711 $formattedcolumn = $row->$column;
714 $formattedrow[$column] = $formattedcolumn;
716 return $formattedrow;
720 * Fullname is treated as a special columname in tablelib and should always
721 * be treated the same as the fullname of a user.
722 * @uses $this->useridfield if the userid field is not expected to be id
723 * then you need to override $this->useridfield to point at the correct
724 * field for the user id.
727 function col_fullname($row) {
728 global $COURSE, $CFG;
730 $name = fullname($row);
731 if ($this->download
) {
735 $userid = $row->{$this->useridfield
};
736 if ($COURSE->id
== SITEID
) {
737 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
739 $profileurl = new moodle_url('/user/view.php',
740 array('id' => $userid, 'course' => $COURSE->id
));
742 return html_writer
::link($profileurl, $name);
746 * You can override this method in a child class. See the description of
747 * build_table which calls this method.
749 function other_cols($column, $row) {
754 * Used from col_* functions when text is to be displayed. Does the
755 * right thing - either converts text to html or strips any html tags
756 * depending on if we are downloading and what is the download type. Params
757 * are the same as format_text function in weblib.php but some default
758 * options are changed.
760 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
761 if (!$this->is_downloading()) {
762 if (is_null($options)) {
763 $options = new stdClass
;
765 //some sensible defaults
766 if (!isset($options->para
)) {
767 $options->para
= false;
769 if (!isset($options->newlines
)) {
770 $options->newlines
= false;
772 if (!isset($options->smiley
)) {
773 $options->smiley
= false;
775 if (!isset($options->filter
)) {
776 $options->filter
= false;
778 return format_text($text, $format, $options);
780 $eci =& $this->export_class_instance();
781 return $eci->format_text($text, $format, $options, $courseid);
785 * This method is deprecated although the old api is still supported.
786 * @deprecated 1.9.2 - Jun 2, 2008
788 function print_html() {
792 $this->finish_html();
796 * This function is not part of the public api.
797 * @return string initial of first name we are currently filtering by
799 function get_initial_first() {
800 if (!$this->use_initials
) {
804 return $this->sess
->i_first
;
808 * This function is not part of the public api.
809 * @return string initial of last name we are currently filtering by
811 function get_initial_last() {
812 if (!$this->use_initials
) {
816 return $this->sess
->i_last
;
820 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
821 * @param array $alpha of letters in the alphabet.
822 * @param string $current the currently selected letter.
823 * @param string $class class name to add to this initial bar.
824 * @param string $title the name to put in front of this initial bar.
825 * @param string $urlvar URL parameter name for this initial.
827 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
828 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
831 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
833 echo html_writer
::tag('strong', get_string('all'));
836 foreach ($alpha as $letter) {
837 if ($letter === $current) {
838 echo html_writer
::tag('strong', $letter);
840 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
844 echo html_writer
::end_tag('div');
848 * This function is not part of the public api.
850 function print_initials_bar() {
851 if ((!empty($this->sess
->i_last
) ||
!empty($this->sess
->i_first
) ||
$this->use_initials
)
852 && isset($this->columns
['fullname'])) {
854 $alpha = explode(',', get_string('alphabet', 'langconfig'));
856 // Bar of first initials
857 if (!empty($this->sess
->i_first
)) {
858 $ifirst = $this->sess
->i_first
;
862 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
863 get_string('firstname'), $this->request
[TABLE_VAR_IFIRST
]);
865 // Bar of last initials
866 if (!empty($this->sess
->i_last
)) {
867 $ilast = $this->sess
->i_last
;
871 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
872 get_string('lastname'), $this->request
[TABLE_VAR_ILAST
]);
877 * This function is not part of the public api.
879 function print_nothing_to_display() {
881 $this->print_initials_bar();
883 echo $OUTPUT->heading(get_string('nothingtodisplay'));
887 * This function is not part of the public api.
889 function get_row_from_keyed($rowwithkeys) {
890 if (is_object($rowwithkeys)) {
891 $rowwithkeys = (array)$rowwithkeys;
894 foreach (array_keys($this->columns
) as $column) {
895 if (isset($rowwithkeys[$column])) {
896 $row [] = $rowwithkeys[$column];
904 * This function is not part of the public api.
906 function get_download_menu() {
907 $allclasses= get_declared_classes();
908 $exportclasses = array();
909 foreach ($allclasses as $class) {
911 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
913 $exportclasses[$type]= get_string("download$type", 'table');
916 return $exportclasses;
920 * This function is not part of the public api.
922 function download_buttons() {
923 if ($this->is_downloadable() && !$this->is_downloading()) {
924 $downloadoptions = $this->get_download_menu();
925 $html = '<form action="'. $this->baseurl
.'" method="post">';
926 $html .= '<div class="mdl-align">';
927 $html .= '<input type="submit" value="'.get_string('downloadas', 'table').'"/>';
928 $html .= html_writer
::label(get_string('downloadoptions', 'table'), 'menudownload', false, array('class' => 'accesshide'));
929 $html .= html_writer
::select($downloadoptions, 'download', $this->defaultdownloadformat
, false);
930 $html .= '</div></form>';
938 * This function is not part of the public api.
939 * You don't normally need to call this. It is called automatically when
940 * needed when you start adding data to the table.
943 function start_output() {
944 $this->started_output
= true;
945 if ($this->exportclass
!==null) {
946 $this->exportclass
->start_table($this->sheettitle
);
947 $this->exportclass
->output_headers($this->headers
);
950 $this->print_headers();
955 * This function is not part of the public api.
957 function print_row($row, $classname = '') {
958 static $suppress_lastrow = NULL;
960 $rowclasses = array('r' . $oddeven);
961 $oddeven = $oddeven ?
0 : 1;
964 $rowclasses[] = $classname;
967 echo html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses)));
969 // If we have a separator, print it
971 $colcount = count($this->columns
);
972 echo html_writer
::tag('td', html_writer
::tag('div', '',
973 array('class' => 'tabledivider')), array('colspan' => $colcount));
976 $colbyindex = array_flip($this->columns
);
977 foreach ($row as $index => $data) {
978 $column = $colbyindex[$index];
980 if (empty($this->sess
->collapse
[$column])) {
981 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
990 echo html_writer
::tag('td', $content, array(
991 'class' => 'cell c' . $index . $this->column_class
[$column],
992 'style' => $this->make_styles_string($this->column_style
[$column])));
996 echo html_writer
::end_tag('tr');
998 $suppress_enabled = array_sum($this->column_suppress
);
999 if ($suppress_enabled) {
1000 $suppress_lastrow = $row;
1005 * This function is not part of the public api.
1007 function finish_html() {
1009 if (!$this->started_output
) {
1010 //no data has been added to the table.
1011 $this->print_nothing_to_display();
1014 echo html_writer
::end_tag('table');
1015 echo html_writer
::end_tag('div');
1016 $this->wrap_html_finish();
1019 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1020 echo $this->download_buttons();
1023 if($this->use_pages
) {
1024 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1025 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1026 echo $OUTPUT->render($pagingbar);
1032 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1033 * used by {@link print_headers()}.
1034 * @param string $column the column name, index into various names.
1035 * @param int $index numerical index of the column.
1036 * @return string HTML fragment.
1038 protected function show_hide_link($column, $index) {
1040 // Some headers contain <br /> tags, do not include in title, hence the
1043 if (!empty($this->sess
->collapse
[$column])) {
1044 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1045 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1046 array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index])));
1048 } else if ($this->headers
[$index] !== NULL) {
1049 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1050 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1051 array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index])));
1056 * This function is not part of the public api.
1058 function print_headers() {
1059 global $CFG, $OUTPUT;
1061 echo html_writer
::start_tag('tr');
1062 foreach ($this->columns
as $column => $index) {
1065 if ($this->is_collapsible
) {
1066 $icon_hide = $this->show_hide_link($column, $index);
1069 $primary_sort_column = '';
1070 $primary_sort_order = '';
1071 if (reset($this->sess
->sortby
)) {
1072 $primary_sort_column = key($this->sess
->sortby
);
1073 $primary_sort_order = current($this->sess
->sortby
);
1079 if ($this->is_sortable($column)) {
1080 $firstnamesortlink = $this->sort_link(get_string('firstname'),
1081 'firstname', $primary_sort_column === 'firstname', $primary_sort_order);
1083 $lastnamesortlink = $this->sort_link(get_string('lastname'),
1084 'lastname', $primary_sort_column === 'lastname', $primary_sort_order);
1086 $override = new stdClass();
1087 $override->firstname
= 'firstname';
1088 $override->lastname
= 'lastname';
1089 $fullnamelanguage = get_string('fullnamedisplay', '', $override);
1091 if (($CFG->fullnamedisplay
== 'firstname lastname') or
1092 ($CFG->fullnamedisplay
== 'firstname') or
1093 ($CFG->fullnamedisplay
== 'language' and $fullnamelanguage == 'firstname lastname' )) {
1094 $this->headers
[$index] = $firstnamesortlink . ' / ' . $lastnamesortlink;
1096 $this->headers
[$index] = $lastnamesortlink . ' / ' . $firstnamesortlink;
1102 // do nothing, do not display sortable links
1106 if ($this->is_sortable($column)) {
1107 $this->headers
[$index] = $this->sort_link($this->headers
[$index],
1108 $column, $primary_sort_column == $column, $primary_sort_order);
1112 $attributes = array(
1113 'class' => 'header c' . $index . $this->column_class
[$column],
1116 if ($this->headers
[$index] === NULL) {
1117 $content = ' ';
1118 } else if (!empty($this->sess
->collapse
[$column])) {
1119 $content = $icon_hide;
1121 if (is_array($this->column_style
[$column])) {
1122 $attributes['style'] = $this->make_styles_string($this->column_style
[$column]);
1124 $content = $this->headers
[$index] . html_writer
::tag('div',
1125 $icon_hide, array('class' => 'commands'));
1127 echo html_writer
::tag('th', $content, $attributes);
1130 echo html_writer
::end_tag('tr');
1134 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1135 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1136 * @param int $order SORT_ASC or SORT_DESC
1137 * @return string HTML fragment.
1139 protected function sort_icon($isprimary, $order) {
1146 if ($order == SORT_ASC
) {
1147 return html_writer
::empty_tag('img',
1148 array('src' => $OUTPUT->pix_url('t/down'), 'alt' => get_string('asc')));
1150 return html_writer
::empty_tag('img',
1151 array('src' => $OUTPUT->pix_url('t/up'), 'alt' => get_string('desc')));
1156 * Generate the correct tool tip for changing the sort order. This is a
1157 * helper method used by {@link sort_link()}.
1158 * @param bool $isprimary whether the is column is the current primary sort column.
1159 * @param int $order SORT_ASC or SORT_DESC
1160 * @return string the correct title.
1162 protected function sort_order_name($isprimary, $order) {
1163 if ($isprimary && $order != SORT_ASC
) {
1164 return get_string('desc');
1166 return get_string('asc');
1171 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1172 * @param string $text the text for the link.
1173 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1174 * @param bool $isprimary whether the is column is the current primary sort column.
1175 * @param int $order SORT_ASC or SORT_DESC
1176 * @return string HTML fragment.
1178 protected function sort_link($text, $column, $isprimary, $order) {
1179 return html_writer
::link($this->baseurl
->out(false,
1180 array($this->request
[TABLE_VAR_SORT
] => $column)),
1181 $text . get_accesshide(get_string('sortby') . ' ' .
1182 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1183 $this->sort_icon($isprimary, $order);
1187 * This function is not part of the public api.
1189 function start_html() {
1191 // Do we need to print initial bars?
1192 $this->print_initials_bar();
1195 if ($this->use_pages
) {
1196 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1197 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1198 echo $OUTPUT->render($pagingbar);
1201 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1202 echo $this->download_buttons();
1205 $this->wrap_html_start();
1206 // Start of main data table
1208 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1209 echo html_writer
::start_tag('table', $this->attributes
);
1214 * This function is not part of the public api.
1215 * @param array $styles CSS-property => value
1216 * @return string values suitably to go in a style="" attribute in HTML.
1218 function make_styles_string($styles) {
1219 if (empty($styles)) {
1224 foreach($styles as $property => $value) {
1225 $string .= $property . ':' . $value . ';';
1233 * @package moodlecore
1234 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1235 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1237 class table_sql
extends flexible_table
{
1239 public $countsql = NULL;
1240 public $countparams = NULL;
1242 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1246 * @var array Data fetched from the db.
1248 public $rawdata = NULL;
1251 * @var bool Overriding default for this.
1253 public $is_sortable = true;
1255 * @var bool Overriding default for this.
1257 public $is_collapsible = true;
1260 * @param string $uniqueid a string identifying this table.Used as a key in
1263 function __construct($uniqueid) {
1264 parent
::__construct($uniqueid);
1265 // some sensible defaults
1266 $this->set_attribute('cellspacing', '0');
1267 $this->set_attribute('class', 'generaltable generalbox');
1271 * Take the data returned from the db_query and go through all the rows
1272 * processing each col using either col_{columnname} method or other_cols
1273 * method or if other_cols returns NULL then put the data straight into the
1276 function build_table() {
1277 if ($this->rawdata
) {
1278 foreach ($this->rawdata
as $row) {
1279 $formattedrow = $this->format_row($row);
1280 $this->add_data_keyed($formattedrow,
1281 $this->get_row_class($row));
1287 * Get any extra classes names to add to this row in the HTML.
1288 * @param $row array the data for this row.
1289 * @return string added to the class="" attribute of the tr.
1291 function get_row_class($row) {
1296 * This is only needed if you want to use different sql to count rows.
1297 * Used for example when perhaps all db JOINS are not needed when counting
1298 * records. You don't need to call this function the count_sql
1299 * will be generated automatically.
1301 * We need to count rows returned by the db seperately to the query itself
1302 * as we need to know how many pages of data we have to display.
1304 function set_count_sql($sql, array $params = NULL) {
1305 $this->countsql
= $sql;
1306 $this->countparams
= $params;
1310 * Set the sql to query the db. Query will be :
1311 * SELECT $fields FROM $from WHERE $where
1312 * Of course you can use sub-queries, JOINS etc. by putting them in the
1313 * appropriate clause of the query.
1315 function set_sql($fields, $from, $where, array $params = NULL) {
1316 $this->sql
= new stdClass();
1317 $this->sql
->fields
= $fields;
1318 $this->sql
->from
= $from;
1319 $this->sql
->where
= $where;
1320 $this->sql
->params
= $params;
1324 * Query the db. Store results in the table object for use by build_table.
1326 * @param int $pagesize size of page for paginated displayed table.
1327 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1328 * will only be used if there is a fullname column defined for the table.
1330 function query_db($pagesize, $useinitialsbar=true) {
1332 if (!$this->is_downloading()) {
1333 if ($this->countsql
=== NULL) {
1334 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1335 $this->countparams
= $this->sql
->params
;
1337 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1338 if ($useinitialsbar && !$this->is_downloading()) {
1339 $this->initialbars($grandtotal > $pagesize);
1342 list($wsql, $wparams) = $this->get_sql_where();
1344 $this->countsql
.= ' AND '.$wsql;
1345 $this->countparams
= array_merge($this->countparams
, $wparams);
1347 $this->sql
->where
.= ' AND '.$wsql;
1348 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1350 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1352 $total = $grandtotal;
1355 $this->pagesize($pagesize, $total);
1358 // Fetch the attempts
1359 $sort = $this->get_sql_sort();
1361 $sort = "ORDER BY $sort";
1364 {$this->sql->fields}
1365 FROM {$this->sql->from}
1366 WHERE {$this->sql->where}
1369 if (!$this->is_downloading()) {
1370 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
1372 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
1377 * Convenience method to call a number of methods for you to display the
1380 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1382 if (!$this->columns
) {
1383 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql
->params
);
1384 //if columns is not set then define columns as the keys of the rows returned
1386 $this->define_columns(array_keys((array)$onerow));
1387 $this->define_headers(array_keys((array)$onerow));
1390 $this->query_db($pagesize, $useinitialsbar);
1391 $this->build_table();
1392 $this->finish_output();
1398 * @package moodlecore
1399 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1402 class table_default_export_format_parent
{
1404 * @var flexible_table or child class reference pointing to table class
1405 * object from which to export data.
1410 * @var bool output started. Keeps track of whether any output has been
1413 var $documentstarted = false;
1414 function table_default_export_format_parent(&$table) {
1415 $this->table
=& $table;
1418 function set_table(&$table) {
1419 $this->table
=& $table;
1422 function add_data($row) {
1426 function add_seperator() {
1430 function document_started() {
1431 return $this->documentstarted
;
1434 * Given text in a variety of format codings, this function returns
1435 * the text as safe HTML or as plain text dependent on what is appropriate
1436 * for the download format. The default removes all tags.
1438 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1439 //use some whitespace to indicate where there was some line spacing.
1440 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1441 return strip_tags($text);
1447 * @package moodlecore
1448 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1451 class table_spreadsheet_export_format_parent
extends table_default_export_format_parent
{
1456 * @var object format object - format for normal table cells
1460 * @var object format object - format for header table cells
1465 * should be overriden in child class.
1470 * This method will be overridden in the child class.
1472 function define_workbook() {
1475 function start_document($filename) {
1476 $filename = $filename.'.'.$this->fileextension
;
1477 $this->define_workbook();
1479 $this->formatnormal
=& $this->workbook
->add_format();
1480 $this->formatnormal
->set_bold(0);
1481 $this->formatheaders
=& $this->workbook
->add_format();
1482 $this->formatheaders
->set_bold(1);
1483 $this->formatheaders
->set_align('center');
1484 // Sending HTTP headers
1485 $this->workbook
->send($filename);
1486 $this->documentstarted
= true;
1489 function start_table($sheettitle) {
1490 $this->worksheet
=& $this->workbook
->add_worksheet($sheettitle);
1494 function output_headers($headers) {
1496 foreach ($headers as $item) {
1497 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatheaders
);
1503 function add_data($row) {
1505 foreach ($row as $item) {
1506 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatnormal
);
1513 function add_seperator() {
1518 function finish_table() {
1521 function finish_document() {
1522 $this->workbook
->close();
1529 * @package moodlecore
1530 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 class table_excel_export_format
extends table_spreadsheet_export_format_parent
{
1534 var $fileextension = 'xls';
1536 function define_workbook() {
1538 require_once("$CFG->libdir/excellib.class.php");
1539 // Creating a workbook
1540 $this->workbook
= new MoodleExcelWorkbook("-");
1547 * @package moodlecore
1548 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1551 class table_ods_export_format
extends table_spreadsheet_export_format_parent
{
1552 var $fileextension = 'ods';
1553 function define_workbook() {
1555 require_once("$CFG->libdir/odslib.class.php");
1556 // Creating a workbook
1557 $this->workbook
= new MoodleODSWorkbook("-");
1563 * @package moodlecore
1564 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1567 class table_text_export_format_parent
extends table_default_export_format_parent
{
1568 protected $seperator = "\t";
1569 protected $mimetype = 'text/tab-separated-values';
1570 protected $ext = '.txt';
1572 public function start_document($filename) {
1573 $this->filename
= $filename . $this->ext
;
1574 header('Content-Type: ' . $this->mimetype
. '; charset=UTF-8');
1575 header('Content-Disposition: attachment; filename="' . $this->filename
. '"');
1576 header('Expires: 0');
1577 header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
1578 header('Pragma: public');
1579 $this->documentstarted
= true;
1582 public function start_table($sheettitle) {
1583 //nothing to do here
1586 public function output_headers($headers) {
1587 echo $this->format_row($headers);
1590 public function add_data($row) {
1591 echo $this->format_row($row);
1595 public function finish_table() {
1599 public function finish_document() {
1604 * Format a row of data.
1605 * @param array $data
1607 protected function format_row($data) {
1608 $escapeddata = array();
1609 foreach ($data as $value) {
1610 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1612 return implode($this->seperator
, $escapeddata) . "\n";
1618 * @package moodlecore
1619 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1622 class table_tsv_export_format
extends table_text_export_format_parent
{
1623 protected $seperator = "\t";
1624 protected $mimetype = 'text/tab-separated-values';
1625 protected $ext = '.txt';
1630 * @package moodlecore
1631 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1634 class table_csv_export_format
extends table_text_export_format_parent
{
1635 protected $seperator = ",";
1636 protected $mimetype = 'text/csv';
1637 protected $ext = '.csv';
1642 * @package moodlecore
1643 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1646 class table_xhtml_export_format
extends table_default_export_format_parent
{
1647 function start_document($filename) {
1648 header("Content-Type: application/download\n");
1649 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1650 header("Expires: 0");
1651 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1652 header("Pragma: public");
1655 <?xml version="1.0" encoding="UTF-8"?>
1657 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1658 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1660 <html xmlns="http://www.w3.org/1999/xhtml"
1661 xml:lang="en" lang="en">
1663 <style type="text/css">/*<![CDATA[*/
1668 th.header, td.header, div.header {
1669 border-color:#DDDDDD;
1670 background-color:lightGrey;
1685 body, table, td, th {
1686 font-family:Arial,Verdana,Helvetica,sans-serif;
1694 border-collapse:collapse;
1710 <title>$filename</title>
1714 $this->documentstarted
= true;
1717 function start_table($sheettitle) {
1718 $this->table
->sortable(false);
1719 $this->table
->collapsible(false);
1720 echo "<h2>{$sheettitle}</h2>";
1721 $this->table
->start_html();
1724 function output_headers($headers) {
1725 $this->table
->print_headers();
1728 function add_data($row) {
1729 $this->table
->print_row($row);
1733 function add_seperator() {
1734 $this->table
->print_row(NULL);
1738 function finish_table() {
1739 $this->table
->finish_html();
1742 function finish_document() {
1743 echo "</body>\n</html>";
1747 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1748 if (is_null($options)) {
1749 $options = new stdClass
;
1751 //some sensible defaults
1752 if (!isset($options->para
)) {
1753 $options->para
= false;
1755 if (!isset($options->newlines
)) {
1756 $options->newlines
= false;
1758 if (!isset($options->smiley
)) {
1759 $options->smiley
= false;
1761 if (!isset($options->filter
)) {
1762 $options->filter
= false;
1764 return format_text($text, $format, $options);