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 if (!$this->download
) {
731 $profileurl = new moodle_url('/user/profile.php', array('id' => $row->{$this->useridfield
}));
732 if ($COURSE->id
!= SITEID
) {
733 $profileurl->param('course', $COURSE->id
);
735 return html_writer
::link($profileurl, fullname($row));
738 return fullname($row);
743 * You can override this method in a child class. See the description of
744 * build_table which calls this method.
746 function other_cols($column, $row) {
751 * Used from col_* functions when text is to be displayed. Does the
752 * right thing - either converts text to html or strips any html tags
753 * depending on if we are downloading and what is the download type. Params
754 * are the same as format_text function in weblib.php but some default
755 * options are changed.
757 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
758 if (!$this->is_downloading()) {
759 if (is_null($options)) {
760 $options = new stdClass
;
762 //some sensible defaults
763 if (!isset($options->para
)) {
764 $options->para
= false;
766 if (!isset($options->newlines
)) {
767 $options->newlines
= false;
769 if (!isset($options->smiley
)) {
770 $options->smiley
= false;
772 if (!isset($options->filter
)) {
773 $options->filter
= false;
775 return format_text($text, $format, $options);
777 $eci =& $this->export_class_instance();
778 return $eci->format_text($text, $format, $options, $courseid);
782 * This method is deprecated although the old api is still supported.
783 * @deprecated 1.9.2 - Jun 2, 2008
785 function print_html() {
789 $this->finish_html();
793 * This function is not part of the public api.
794 * @return string initial of first name we are currently filtering by
796 function get_initial_first() {
797 if (!$this->use_initials
) {
801 return $this->sess
->i_first
;
805 * This function is not part of the public api.
806 * @return string initial of last name we are currently filtering by
808 function get_initial_last() {
809 if (!$this->use_initials
) {
813 return $this->sess
->i_last
;
817 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
818 * @param array $alpha of letters in the alphabet.
819 * @param string $current the currently selected letter.
820 * @param string $class class name to add to this initial bar.
821 * @param string $title the name to put in front of this initial bar.
822 * @param string $urlvar URL parameter name for this initial.
824 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
825 echo html_writer
::start_tag('div', array('class' => 'initialbar ' . $class)) .
828 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => '')), get_string('all'));
830 echo html_writer
::tag('strong', get_string('all'));
833 foreach ($alpha as $letter) {
834 if ($letter === $current) {
835 echo html_writer
::tag('strong', $letter);
837 echo html_writer
::link($this->baseurl
->out(false, array($urlvar => $letter)), $letter);
841 echo html_writer
::end_tag('div');
845 * This function is not part of the public api.
847 function print_initials_bar() {
848 if ((!empty($this->sess
->i_last
) ||
!empty($this->sess
->i_first
) ||
$this->use_initials
)
849 && isset($this->columns
['fullname'])) {
851 $alpha = explode(',', get_string('alphabet', 'langconfig'));
853 // Bar of first initials
854 if (!empty($this->sess
->i_first
)) {
855 $ifirst = $this->sess
->i_first
;
859 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
860 get_string('firstname'), $this->request
[TABLE_VAR_IFIRST
]);
862 // Bar of last initials
863 if (!empty($this->sess
->i_last
)) {
864 $ilast = $this->sess
->i_last
;
868 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
869 get_string('lastname'), $this->request
[TABLE_VAR_ILAST
]);
874 * This function is not part of the public api.
876 function print_nothing_to_display() {
878 $this->print_initials_bar();
880 echo $OUTPUT->heading(get_string('nothingtodisplay'));
884 * This function is not part of the public api.
886 function get_row_from_keyed($rowwithkeys) {
887 if (is_object($rowwithkeys)) {
888 $rowwithkeys = (array)$rowwithkeys;
891 foreach (array_keys($this->columns
) as $column) {
892 if (isset($rowwithkeys[$column])) {
893 $row [] = $rowwithkeys[$column];
901 * This function is not part of the public api.
903 function get_download_menu() {
904 $allclasses= get_declared_classes();
905 $exportclasses = array();
906 foreach ($allclasses as $class) {
908 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
910 $exportclasses[$type]= get_string("download$type", 'table');
913 return $exportclasses;
917 * This function is not part of the public api.
919 function download_buttons() {
920 if ($this->is_downloadable() && !$this->is_downloading()) {
921 $downloadoptions = $this->get_download_menu();
923 $downloadelements = new stdClass();
924 $downloadelements->formatsmenu
= html_writer
::select($downloadoptions,
925 'download', $this->defaultdownloadformat
, false);
926 $downloadelements->downloadbutton
= '<input type="submit" value="'.
927 get_string('download').'"/>';
928 $html = '<form action="'. $this->baseurl
.'" method="post">';
929 $html .= '<div class="mdl-align">';
930 $html .= html_writer
::tag('label', get_string('downloadas', 'table', $downloadelements));
931 $html .= '</div></form>';
939 * This function is not part of the public api.
940 * You don't normally need to call this. It is called automatically when
941 * needed when you start adding data to the table.
944 function start_output() {
945 $this->started_output
= true;
946 if ($this->exportclass
!==null) {
947 $this->exportclass
->start_table($this->sheettitle
);
948 $this->exportclass
->output_headers($this->headers
);
951 $this->print_headers();
952 echo html_writer
::start_tag('tbody');
957 * This function is not part of the public api.
959 function print_row($row, $classname = '') {
960 static $suppress_lastrow = NULL;
962 $rowclasses = array('r' . $oddeven);
963 $oddeven = $oddeven ?
0 : 1;
966 $rowclasses[] = $classname;
969 echo html_writer
::start_tag('tr', array('class' => implode(' ', $rowclasses)));
971 // If we have a separator, print it
973 $colcount = count($this->columns
);
974 echo html_writer
::tag('td', html_writer
::tag('div', '',
975 array('class' => 'tabledivider')), array('colspan' => $colcount));
978 $colbyindex = array_flip($this->columns
);
979 foreach ($row as $index => $data) {
980 $column = $colbyindex[$index];
982 if (empty($this->sess
->collapse
[$column])) {
983 if ($this->column_suppress
[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
992 echo html_writer
::tag('td', $content, array(
993 'class' => 'cell c' . $index . $this->column_class
[$column],
994 'style' => $this->make_styles_string($this->column_style
[$column])));
998 echo html_writer
::end_tag('tr');
1000 $suppress_enabled = array_sum($this->column_suppress
);
1001 if ($suppress_enabled) {
1002 $suppress_lastrow = $row;
1007 * This function is not part of the public api.
1009 function finish_html() {
1011 if (!$this->started_output
) {
1012 //no data has been added to the table.
1013 $this->print_nothing_to_display();
1016 echo html_writer
::end_tag('tbody');
1017 echo html_writer
::end_tag('table');
1018 echo html_writer
::end_tag('div');
1019 $this->wrap_html_finish();
1022 if(in_array(TABLE_P_BOTTOM
, $this->showdownloadbuttonsat
)) {
1023 echo $this->download_buttons();
1026 if($this->use_pages
) {
1027 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1028 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1029 echo $OUTPUT->render($pagingbar);
1035 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1036 * used by {@link print_headers()}.
1037 * @param string $column the column name, index into various names.
1038 * @param int $index numerical index of the column.
1039 * @return string HTML fragment.
1041 protected function show_hide_link($column, $index) {
1043 // Some headers contain <br /> tags, do not include in title, hence the
1046 if (!empty($this->sess
->collapse
[$column])) {
1047 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_SHOW
] => $column)),
1048 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1049 array('title' => get_string('show') . ' ' . strip_tags($this->headers
[$index])));
1051 } else if ($this->headers
[$index] !== NULL) {
1052 return html_writer
::link($this->baseurl
->out(false, array($this->request
[TABLE_VAR_HIDE
] => $column)),
1053 html_writer
::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1054 array('title' => get_string('hide') . ' ' . strip_tags($this->headers
[$index])));
1059 * This function is not part of the public api.
1061 function print_headers() {
1062 global $CFG, $OUTPUT;
1064 echo html_writer
::start_tag('thead');
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');
1135 echo html_writer
::end_tag('thead');
1139 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1140 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1141 * @param int $order SORT_ASC or SORT_DESC
1142 * @return string HTML fragment.
1144 protected function sort_icon($isprimary, $order) {
1151 if ($order == SORT_ASC
) {
1152 return html_writer
::empty_tag('img',
1153 array('src' => $OUTPUT->pix_url('t/down'), 'alt' => get_string('asc')));
1155 return html_writer
::empty_tag('img',
1156 array('src' => $OUTPUT->pix_url('t/up'), 'alt' => get_string('desc')));
1161 * Generate the correct tool tip for changing the sort order. This is a
1162 * helper method used by {@link sort_link()}.
1163 * @param bool $isprimary whether the is column is the current primary sort column.
1164 * @param int $order SORT_ASC or SORT_DESC
1165 * @return string the correct title.
1167 protected function sort_order_name($isprimary, $order) {
1168 if ($isprimary && $order != SORT_ASC
) {
1169 return get_string('desc');
1171 return get_string('asc');
1176 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1177 * @param string $text the text for the link.
1178 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1179 * @param bool $isprimary whether the is column is the current primary sort column.
1180 * @param int $order SORT_ASC or SORT_DESC
1181 * @return string HTML fragment.
1183 protected function sort_link($text, $column, $isprimary, $order) {
1184 return html_writer
::link($this->baseurl
->out(false,
1185 array($this->request
[TABLE_VAR_SORT
] => $column)),
1186 $text . get_accesshide(get_string('sortby') . ' ' .
1187 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1188 $this->sort_icon($isprimary, $order);
1192 * This function is not part of the public api.
1194 function start_html() {
1196 // Do we need to print initial bars?
1197 $this->print_initials_bar();
1200 if ($this->use_pages
) {
1201 $pagingbar = new paging_bar($this->totalrows
, $this->currpage
, $this->pagesize
, $this->baseurl
);
1202 $pagingbar->pagevar
= $this->request
[TABLE_VAR_PAGE
];
1203 echo $OUTPUT->render($pagingbar);
1206 if (in_array(TABLE_P_TOP
, $this->showdownloadbuttonsat
)) {
1207 echo $this->download_buttons();
1210 $this->wrap_html_start();
1211 // Start of main data table
1213 echo html_writer
::start_tag('div', array('class' => 'no-overflow'));
1214 echo html_writer
::start_tag('table', $this->attributes
);
1219 * This function is not part of the public api.
1220 * @param array $styles CSS-property => value
1221 * @return string values suitably to go in a style="" attribute in HTML.
1223 function make_styles_string($styles) {
1224 if (empty($styles)) {
1229 foreach($styles as $property => $value) {
1230 $string .= $property . ':' . $value . ';';
1238 * @package moodlecore
1239 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1242 class table_sql
extends flexible_table
{
1244 public $countsql = NULL;
1245 public $countparams = NULL;
1247 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1251 * @var array Data fetched from the db.
1253 public $rawdata = NULL;
1256 * @var bool Overriding default for this.
1258 public $is_sortable = true;
1260 * @var bool Overriding default for this.
1262 public $is_collapsible = true;
1265 * @param string $uniqueid a string identifying this table.Used as a key in
1268 function __construct($uniqueid) {
1269 parent
::__construct($uniqueid);
1270 // some sensible defaults
1271 $this->set_attribute('cellspacing', '0');
1272 $this->set_attribute('class', 'generaltable generalbox');
1276 * Take the data returned from the db_query and go through all the rows
1277 * processing each col using either col_{columnname} method or other_cols
1278 * method or if other_cols returns NULL then put the data straight into the
1281 function build_table() {
1282 if ($this->rawdata
) {
1283 foreach ($this->rawdata
as $row) {
1284 $formattedrow = $this->format_row($row);
1285 $this->add_data_keyed($formattedrow,
1286 $this->get_row_class($row));
1292 * Get any extra classes names to add to this row in the HTML.
1293 * @param $row array the data for this row.
1294 * @return string added to the class="" attribute of the tr.
1296 function get_row_class($row) {
1301 * This is only needed if you want to use different sql to count rows.
1302 * Used for example when perhaps all db JOINS are not needed when counting
1303 * records. You don't need to call this function the count_sql
1304 * will be generated automatically.
1306 * We need to count rows returned by the db seperately to the query itself
1307 * as we need to know how many pages of data we have to display.
1309 function set_count_sql($sql, array $params = NULL) {
1310 $this->countsql
= $sql;
1311 $this->countparams
= $params;
1315 * Set the sql to query the db. Query will be :
1316 * SELECT $fields FROM $from WHERE $where
1317 * Of course you can use sub-queries, JOINS etc. by putting them in the
1318 * appropriate clause of the query.
1320 function set_sql($fields, $from, $where, array $params = NULL) {
1321 $this->sql
= new stdClass();
1322 $this->sql
->fields
= $fields;
1323 $this->sql
->from
= $from;
1324 $this->sql
->where
= $where;
1325 $this->sql
->params
= $params;
1329 * Query the db. Store results in the table object for use by build_table.
1331 * @param int $pagesize size of page for paginated displayed table.
1332 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1333 * will only be used if there is a fullname column defined for the table.
1335 function query_db($pagesize, $useinitialsbar=true) {
1337 if (!$this->is_downloading()) {
1338 if ($this->countsql
=== NULL) {
1339 $this->countsql
= 'SELECT COUNT(1) FROM '.$this->sql
->from
.' WHERE '.$this->sql
->where
;
1340 $this->countparams
= $this->sql
->params
;
1342 $grandtotal = $DB->count_records_sql($this->countsql
, $this->countparams
);
1343 if ($useinitialsbar && !$this->is_downloading()) {
1344 $this->initialbars($grandtotal > $pagesize);
1347 list($wsql, $wparams) = $this->get_sql_where();
1349 $this->countsql
.= ' AND '.$wsql;
1350 $this->countparams
= array_merge($this->countparams
, $wparams);
1352 $this->sql
->where
.= ' AND '.$wsql;
1353 $this->sql
->params
= array_merge($this->sql
->params
, $wparams);
1355 $total = $DB->count_records_sql($this->countsql
, $this->countparams
);
1357 $total = $grandtotal;
1360 $this->pagesize($pagesize, $total);
1363 // Fetch the attempts
1364 $sort = $this->get_sql_sort();
1366 $sort = "ORDER BY $sort";
1369 {$this->sql->fields}
1370 FROM {$this->sql->from}
1371 WHERE {$this->sql->where}
1374 if (!$this->is_downloading()) {
1375 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
, $this->get_page_start(), $this->get_page_size());
1377 $this->rawdata
= $DB->get_records_sql($sql, $this->sql
->params
);
1382 * Convenience method to call a number of methods for you to display the
1385 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1387 if (!$this->columns
) {
1388 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql
->params
);
1389 //if columns is not set then define columns as the keys of the rows returned
1391 $this->define_columns(array_keys((array)$onerow));
1392 $this->define_headers(array_keys((array)$onerow));
1395 $this->query_db($pagesize, $useinitialsbar);
1396 $this->build_table();
1397 $this->finish_output();
1403 * @package moodlecore
1404 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1405 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1407 class table_default_export_format_parent
{
1409 * @var flexible_table or child class reference pointing to table class
1410 * object from which to export data.
1415 * @var bool output started. Keeps track of whether any output has been
1418 var $documentstarted = false;
1419 function table_default_export_format_parent(&$table) {
1420 $this->table
=& $table;
1423 function set_table(&$table) {
1424 $this->table
=& $table;
1427 function add_data($row) {
1431 function add_seperator() {
1435 function document_started() {
1436 return $this->documentstarted
;
1439 * Given text in a variety of format codings, this function returns
1440 * the text as safe HTML or as plain text dependent on what is appropriate
1441 * for the download format. The default removes all tags.
1443 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1444 //use some whitespace to indicate where there was some line spacing.
1445 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1446 return strip_tags($text);
1452 * @package moodlecore
1453 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1456 class table_spreadsheet_export_format_parent
extends table_default_export_format_parent
{
1461 * @var object format object - format for normal table cells
1465 * @var object format object - format for header table cells
1470 * should be overriden in child class.
1475 * This method will be overridden in the child class.
1477 function define_workbook() {
1480 function start_document($filename) {
1481 $filename = $filename.'.'.$this->fileextension
;
1482 $this->define_workbook();
1484 $this->formatnormal
=& $this->workbook
->add_format();
1485 $this->formatnormal
->set_bold(0);
1486 $this->formatheaders
=& $this->workbook
->add_format();
1487 $this->formatheaders
->set_bold(1);
1488 $this->formatheaders
->set_align('center');
1489 // Sending HTTP headers
1490 $this->workbook
->send($filename);
1491 $this->documentstarted
= true;
1494 function start_table($sheettitle) {
1495 $this->worksheet
=& $this->workbook
->add_worksheet($sheettitle);
1499 function output_headers($headers) {
1501 foreach ($headers as $item) {
1502 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatheaders
);
1508 function add_data($row) {
1510 foreach ($row as $item) {
1511 $this->worksheet
->write($this->rownum
,$colnum,$item,$this->formatnormal
);
1518 function add_seperator() {
1523 function finish_table() {
1526 function finish_document() {
1527 $this->workbook
->close();
1534 * @package moodlecore
1535 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1538 class table_excel_export_format
extends table_spreadsheet_export_format_parent
{
1539 var $fileextension = 'xls';
1541 function define_workbook() {
1543 require_once("$CFG->libdir/excellib.class.php");
1544 // Creating a workbook
1545 $this->workbook
= new MoodleExcelWorkbook("-");
1552 * @package moodlecore
1553 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1556 class table_ods_export_format
extends table_spreadsheet_export_format_parent
{
1557 var $fileextension = 'ods';
1558 function define_workbook() {
1560 require_once("$CFG->libdir/odslib.class.php");
1561 // Creating a workbook
1562 $this->workbook
= new MoodleODSWorkbook("-");
1568 * @package moodlecore
1569 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1572 class table_text_export_format_parent
extends table_default_export_format_parent
{
1573 protected $seperator = "tab";
1574 protected $mimetype = 'text/tab-separated-values';
1575 protected $ext = '.txt';
1576 protected $myexporter;
1578 public function __construct() {
1579 $this->myexporter
= new csv_export_writer($this->seperator
, '"', $this->mimetype
);
1582 public function start_document($filename) {
1583 $this->filename
= $filename;
1584 $this->documentstarted
= true;
1585 $this->myexporter
->set_filename($filename, $this->ext
);
1588 public function start_table($sheettitle) {
1589 //nothing to do here
1592 public function output_headers($headers) {
1593 $this->myexporter
->add_data($headers);
1596 public function add_data($row) {
1597 $this->myexporter
->add_data($row);
1601 public function finish_table() {
1602 //nothing to do here
1605 public function finish_document() {
1606 $this->myexporter
->download_file();
1611 * Format a row of data.
1612 * @param array $data
1614 protected function format_row($data) {
1615 $escapeddata = array();
1616 foreach ($data as $value) {
1617 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1619 return implode($this->seperator
, $escapeddata) . "\n";
1625 * @package moodlecore
1626 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1629 class table_tsv_export_format
extends table_text_export_format_parent
{
1630 protected $seperator = "tab";
1631 protected $mimetype = 'text/tab-separated-values';
1632 protected $ext = '.txt';
1635 require_once($CFG->libdir
. '/csvlib.class.php');
1637 * @package moodlecore
1638 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1641 class table_csv_export_format
extends table_text_export_format_parent
{
1642 protected $seperator = "comma";
1643 protected $mimetype = 'text/csv';
1644 protected $ext = '.csv';
1648 * @package moodlecore
1649 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1652 class table_xhtml_export_format
extends table_default_export_format_parent
{
1653 function start_document($filename) {
1654 header("Content-Type: application/download\n");
1655 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1656 header("Expires: 0");
1657 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1658 header("Pragma: public");
1661 <?xml version="1.0" encoding="UTF-8"?>
1663 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1664 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1666 <html xmlns="http://www.w3.org/1999/xhtml"
1667 xml:lang="en" lang="en">
1669 <style type="text/css">/*<![CDATA[*/
1674 th.header, td.header, div.header {
1675 border-color:#DDDDDD;
1676 background-color:lightGrey;
1691 body, table, td, th {
1692 font-family:Arial,Verdana,Helvetica,sans-serif;
1700 border-collapse:collapse;
1716 <title>$filename</title>
1720 $this->documentstarted
= true;
1723 function start_table($sheettitle) {
1724 $this->table
->sortable(false);
1725 $this->table
->collapsible(false);
1726 echo "<h2>{$sheettitle}</h2>";
1727 $this->table
->start_html();
1730 function output_headers($headers) {
1731 $this->table
->print_headers();
1732 echo html_writer
::start_tag('tbody');
1735 function add_data($row) {
1736 $this->table
->print_row($row);
1740 function add_seperator() {
1741 $this->table
->print_row(NULL);
1745 function finish_table() {
1746 $this->table
->finish_html();
1749 function finish_document() {
1750 echo "</body>\n</html>";
1754 function format_text($text, $format=FORMAT_MOODLE
, $options=NULL, $courseid=NULL) {
1755 if (is_null($options)) {
1756 $options = new stdClass
;
1758 //some sensible defaults
1759 if (!isset($options->para
)) {
1760 $options->para
= false;
1762 if (!isset($options->newlines
)) {
1763 $options->newlines
= false;
1765 if (!isset($options->smiley
)) {
1766 $options->smiley
= false;
1768 if (!isset($options->filter
)) {
1769 $options->filter
= false;
1771 return format_text($text, $format, $options);