MDL-52927 qtype ddwtos and ddimageortext focus using keyboard
[moodle.git] / lib / tablelib.php
blobe921805f064a3919c838623c398dd47ef80d33bc
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @package core
20 * @subpackage lib
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /**#@+
29 * These constants relate to the table's handling of URL parameters.
31 define('TABLE_VAR_SORT', 1);
32 define('TABLE_VAR_HIDE', 2);
33 define('TABLE_VAR_SHOW', 3);
34 define('TABLE_VAR_IFIRST', 4);
35 define('TABLE_VAR_ILAST', 5);
36 define('TABLE_VAR_PAGE', 6);
37 define('TABLE_VAR_RESET', 7);
38 /**#@-*/
40 /**#@+
41 * Constants that indicate whether the paging bar for the table
42 * appears above or below the table.
44 define('TABLE_P_TOP', 1);
45 define('TABLE_P_BOTTOM', 2);
46 /**#@-*/
49 /**
50 * @package moodlecore
51 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
52 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
54 class flexible_table {
56 var $uniqueid = NULL;
57 var $attributes = array();
58 var $headers = array();
60 /**
61 * @var string For create header with help icon.
63 private $helpforheaders = array();
64 var $columns = array();
65 var $column_style = array();
66 var $column_class = array();
67 var $column_suppress = array();
68 var $column_nosort = array('userpic');
69 private $column_textsort = array();
70 /** @var boolean Stores if setup has already been called on this flixible table. */
71 var $setup = false;
72 var $baseurl = NULL;
73 var $request = array();
75 /**
76 * @var bool Whether or not to store table properties in the user_preferences table.
78 private $persistent = false;
79 var $is_collapsible = false;
80 var $is_sortable = false;
81 var $use_pages = false;
82 var $use_initials = false;
84 var $maxsortkeys = 2;
85 var $pagesize = 30;
86 var $currpage = 0;
87 var $totalrows = 0;
88 var $currentrow = 0;
89 var $sort_default_column = NULL;
90 var $sort_default_order = SORT_ASC;
92 /**
93 * Array of positions in which to display download controls.
95 var $showdownloadbuttonsat= array(TABLE_P_TOP);
97 /**
98 * @var string Key of field returned by db query that is the id field of the
99 * user table or equivalent.
101 public $useridfield = 'id';
104 * @var string which download plugin to use. Default '' means none - print
105 * html table with paging. Property set by is_downloading which typically
106 * passes in cleaned data from $
108 var $download = '';
111 * @var bool whether data is downloadable from table. Determines whether
112 * to display download buttons. Set by method downloadable().
114 var $downloadable = false;
117 * @var string which download plugin to use. Default '' means none - print
118 * html table with paging.
120 var $defaultdownloadformat = 'csv';
123 * @var bool Has start output been called yet?
125 var $started_output = false;
127 var $exportclass = null;
130 * @var array For storing user-customised table properties in the user_preferences db table.
132 private $prefs = array();
135 * Constructor
136 * @param int $uniqueid all tables have to have a unique id, this is used
137 * as a key when storing table properties like sort order in the session.
139 function __construct($uniqueid) {
140 $this->uniqueid = $uniqueid;
141 $this->request = array(
142 TABLE_VAR_SORT => 'tsort',
143 TABLE_VAR_HIDE => 'thide',
144 TABLE_VAR_SHOW => 'tshow',
145 TABLE_VAR_IFIRST => 'tifirst',
146 TABLE_VAR_ILAST => 'tilast',
147 TABLE_VAR_PAGE => 'page',
148 TABLE_VAR_RESET => 'treset'
153 * Call this to pass the download type. Use :
154 * $download = optional_param('download', '', PARAM_ALPHA);
155 * To get the download type. We assume that if you call this function with
156 * params that this table's data is downloadable, so we call is_downloadable
157 * for you (even if the param is '', which means no download this time.
158 * Also you can call this method with no params to get the current set
159 * download type.
160 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
161 * @param string $filename filename for downloads without file extension.
162 * @param string $sheettitle title for downloaded data.
163 * @return string download type. One of csv, tsv, xhtml, ods, etc
165 function is_downloading($download = null, $filename='', $sheettitle='') {
166 if ($download!==null) {
167 $this->sheettitle = $sheettitle;
168 $this->is_downloadable(true);
169 $this->download = $download;
170 $this->filename = clean_filename($filename);
171 $this->export_class_instance();
173 return $this->download;
177 * Get, and optionally set, the export class.
178 * @param $exportclass (optional) if passed, set the table to use this export class.
179 * @return table_default_export_format_parent the export class in use (after any set).
181 function export_class_instance($exportclass = null) {
182 if (!is_null($exportclass)) {
183 $this->started_output = true;
184 $this->exportclass = $exportclass;
185 $this->exportclass->table = $this;
186 } else if (is_null($this->exportclass) && !empty($this->download)) {
187 $classname = 'table_'.$this->download.'_export_format';
188 $this->exportclass = new $classname($this);
189 if (!$this->exportclass->document_started()) {
190 $this->exportclass->start_document($this->filename);
193 return $this->exportclass;
197 * Probably don't need to call this directly. Calling is_downloading with a
198 * param automatically sets table as downloadable.
200 * @param bool $downloadable optional param to set whether data from
201 * table is downloadable. If ommitted this function can be used to get
202 * current state of table.
203 * @return bool whether table data is set to be downloadable.
205 function is_downloadable($downloadable = null) {
206 if ($downloadable !== null) {
207 $this->downloadable = $downloadable;
209 return $this->downloadable;
213 * Call with boolean true to store table layout changes in the user_preferences table.
214 * Note: user_preferences.value has a maximum length of 1333 characters.
215 * Call with no parameter to get current state of table persistence.
217 * @param bool $persistent Optional parameter to set table layout persistence.
218 * @return bool Whether or not the table layout preferences will persist.
220 public function is_persistent($persistent = null) {
221 if ($persistent == true) {
222 $this->persistent = true;
224 return $this->persistent;
228 * Where to show download buttons.
229 * @param array $showat array of postions in which to show download buttons.
230 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
232 function show_download_buttons_at($showat) {
233 $this->showdownloadbuttonsat = $showat;
237 * Sets the is_sortable variable to the given boolean, sort_default_column to
238 * the given string, and the sort_default_order to the given integer.
239 * @param bool $bool
240 * @param string $defaultcolumn
241 * @param int $defaultorder
242 * @return void
244 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
245 $this->is_sortable = $bool;
246 $this->sort_default_column = $defaultcolumn;
247 $this->sort_default_order = $defaultorder;
251 * Use text sorting functions for this column (required for text columns with Oracle).
252 * Be warned that you cannot use this with column aliases. You can only do this
253 * with real columns. See MDL-40481 for an example.
254 * @param string column name
256 function text_sorting($column) {
257 $this->column_textsort[] = $column;
261 * Do not sort using this column
262 * @param string column name
264 function no_sorting($column) {
265 $this->column_nosort[] = $column;
269 * Is the column sortable?
270 * @param string column name, null means table
271 * @return bool
273 function is_sortable($column = null) {
274 if (empty($column)) {
275 return $this->is_sortable;
277 if (!$this->is_sortable) {
278 return false;
280 return !in_array($column, $this->column_nosort);
284 * Sets the is_collapsible variable to the given boolean.
285 * @param bool $bool
286 * @return void
288 function collapsible($bool) {
289 $this->is_collapsible = $bool;
293 * Sets the use_pages variable to the given boolean.
294 * @param bool $bool
295 * @return void
297 function pageable($bool) {
298 $this->use_pages = $bool;
302 * Sets the use_initials variable to the given boolean.
303 * @param bool $bool
304 * @return void
306 function initialbars($bool) {
307 $this->use_initials = $bool;
311 * Sets the pagesize variable to the given integer, the totalrows variable
312 * to the given integer, and the use_pages variable to true.
313 * @param int $perpage
314 * @param int $total
315 * @return void
317 function pagesize($perpage, $total) {
318 $this->pagesize = $perpage;
319 $this->totalrows = $total;
320 $this->use_pages = true;
324 * Assigns each given variable in the array to the corresponding index
325 * in the request class variable.
326 * @param array $variables
327 * @return void
329 function set_control_variables($variables) {
330 foreach ($variables as $what => $variable) {
331 if (isset($this->request[$what])) {
332 $this->request[$what] = $variable;
338 * Gives the given $value to the $attribute index of $this->attributes.
339 * @param string $attribute
340 * @param mixed $value
341 * @return void
343 function set_attribute($attribute, $value) {
344 $this->attributes[$attribute] = $value;
348 * What this method does is set the column so that if the same data appears in
349 * consecutive rows, then it is not repeated.
351 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
352 * that when one student has made multiple attempts, their name is only printed in the row
353 * for their first attempt.
354 * @param int $column the index of a column.
356 function column_suppress($column) {
357 if (isset($this->column_suppress[$column])) {
358 $this->column_suppress[$column] = true;
363 * Sets the given $column index to the given $classname in $this->column_class.
364 * @param int $column
365 * @param string $classname
366 * @return void
368 function column_class($column, $classname) {
369 if (isset($this->column_class[$column])) {
370 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
375 * Sets the given $column index and $property index to the given $value in $this->column_style.
376 * @param int $column
377 * @param string $property
378 * @param mixed $value
379 * @return void
381 function column_style($column, $property, $value) {
382 if (isset($this->column_style[$column])) {
383 $this->column_style[$column][$property] = $value;
388 * Sets all columns' $propertys to the given $value in $this->column_style.
389 * @param int $property
390 * @param string $value
391 * @return void
393 function column_style_all($property, $value) {
394 foreach (array_keys($this->columns) as $column) {
395 $this->column_style[$column][$property] = $value;
400 * Sets $this->baseurl.
401 * @param moodle_url|string $url the url with params needed to call up this page
403 function define_baseurl($url) {
404 $this->baseurl = new moodle_url($url);
408 * @param array $columns an array of identifying names for columns. If
409 * columns are sorted then column names must correspond to a field in sql.
411 function define_columns($columns) {
412 $this->columns = array();
413 $this->column_style = array();
414 $this->column_class = array();
415 $colnum = 0;
417 foreach ($columns as $column) {
418 $this->columns[$column] = $colnum++;
419 $this->column_style[$column] = array();
420 $this->column_class[$column] = '';
421 $this->column_suppress[$column] = false;
426 * @param array $headers numerical keyed array of displayed string titles
427 * for each column.
429 function define_headers($headers) {
430 $this->headers = $headers;
434 * Defines a help icon for the header
436 * Always use this function if you need to create header with sorting and help icon.
438 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
440 public function define_help_for_headers($helpicons) {
441 $this->helpforheaders = $helpicons;
445 * Must be called after table is defined. Use methods above first. Cannot
446 * use functions below till after calling this method.
447 * @return type?
449 function setup() {
450 global $SESSION;
452 if (empty($this->columns) || empty($this->uniqueid)) {
453 return false;
456 // Load any existing user preferences.
457 if ($this->persistent) {
458 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
459 } else if (isset($SESSION->flextable[$this->uniqueid])) {
460 $this->prefs = $SESSION->flextable[$this->uniqueid];
463 // Set up default preferences if needed.
464 if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
465 $this->prefs = array(
466 'collapse' => array(),
467 'sortby' => array(),
468 'i_first' => '',
469 'i_last' => '',
470 'textsort' => $this->column_textsort,
473 $oldprefs = $this->prefs;
475 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
476 isset($this->columns[$showcol])) {
477 $this->prefs['collapse'][$showcol] = false;
479 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
480 isset($this->columns[$hidecol])) {
481 $this->prefs['collapse'][$hidecol] = true;
482 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
483 unset($this->prefs['sortby'][$hidecol]);
487 // Now, update the column attributes for collapsed columns
488 foreach (array_keys($this->columns) as $column) {
489 if (!empty($this->prefs['collapse'][$column])) {
490 $this->column_style[$column]['width'] = '10px';
494 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
495 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
496 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
497 && isset($this->columns['fullname']))) {
499 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
500 // This key already exists somewhere. Change its sortorder and bring it to the top.
501 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
502 unset($this->prefs['sortby'][$sortcol]);
503 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
504 } else {
505 // Key doesn't exist, so just add it to the beginning of the array, ascending order
506 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
509 // Finally, make sure that no more than $this->maxsortkeys are present into the array
510 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
513 // 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.
514 // This prevents results from being returned in a random order if the only order by column contains equal values.
515 if (!empty($this->sort_default_column)) {
516 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
517 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
518 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
522 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
523 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
524 $this->prefs['i_last'] = $ilast;
527 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
528 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
529 $this->prefs['i_first'] = $ifirst;
532 // Save user preferences if they have changed.
533 if ($this->prefs != $oldprefs) {
534 if ($this->persistent) {
535 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
536 } else {
537 $SESSION->flextable[$this->uniqueid] = $this->prefs;
540 unset($oldprefs);
542 if (empty($this->baseurl)) {
543 debugging('You should set baseurl when using flexible_table.');
544 global $PAGE;
545 $this->baseurl = $PAGE->url;
548 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
549 $this->setup = true;
551 // Always introduce the "flexible" class for the table if not specified
552 if (empty($this->attributes)) {
553 $this->attributes['class'] = 'flexible';
554 } else if (!isset($this->attributes['class'])) {
555 $this->attributes['class'] = 'flexible';
556 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
557 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
562 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
563 * @param string $uniqueid the identifier for a table.
564 * @return SQL fragment that can be used in an ORDER BY clause.
566 public static function get_sort_for_table($uniqueid) {
567 global $SESSION;
568 if (isset($SESSION->flextable[$uniqueid])) {
569 $prefs = $SESSION->flextable[$uniqueid];
570 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
571 return '';
574 if (empty($prefs['sortby'])) {
575 return '';
577 if (empty($prefs['textsort'])) {
578 $prefs['textsort'] = array();
581 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
585 * Prepare an an order by clause from the list of columns to be sorted.
586 * @param array $cols column name => SORT_ASC or SORT_DESC
587 * @return SQL fragment that can be used in an ORDER BY clause.
589 public static function construct_order_by($cols, $textsortcols=array()) {
590 global $DB;
591 $bits = array();
593 foreach ($cols as $column => $order) {
594 if (in_array($column, $textsortcols)) {
595 $column = $DB->sql_order_by_text($column);
597 if ($order == SORT_ASC) {
598 $bits[] = $column . ' ASC';
599 } else {
600 $bits[] = $column . ' DESC';
604 return implode(', ', $bits);
608 * @return SQL fragment that can be used in an ORDER BY clause.
610 public function get_sql_sort() {
611 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
615 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
616 * @return array column name => SORT_... constant.
618 public function get_sort_columns() {
619 if (!$this->setup) {
620 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
623 if (empty($this->prefs['sortby'])) {
624 return array();
627 foreach ($this->prefs['sortby'] as $column => $notused) {
628 if (isset($this->columns[$column])) {
629 continue; // This column is OK.
631 if (in_array($column, get_all_user_name_fields()) &&
632 isset($this->columns['fullname'])) {
633 continue; // This column is OK.
635 // This column is not OK.
636 unset($this->prefs['sortby'][$column]);
639 return $this->prefs['sortby'];
643 * @return int the offset for LIMIT clause of SQL
645 function get_page_start() {
646 if (!$this->use_pages) {
647 return '';
649 return $this->currpage * $this->pagesize;
653 * @return int the pagesize for LIMIT clause of SQL
655 function get_page_size() {
656 if (!$this->use_pages) {
657 return '';
659 return $this->pagesize;
663 * @return string sql to add to where statement.
665 function get_sql_where() {
666 global $DB;
668 $conditions = array();
669 $params = array();
671 if (isset($this->columns['fullname'])) {
672 static $i = 0;
673 $i++;
675 if (!empty($this->prefs['i_first'])) {
676 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
677 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
679 if (!empty($this->prefs['i_last'])) {
680 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
681 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
685 return array(implode(" AND ", $conditions), $params);
689 * Add a row of data to the table. This function takes an array or object with
690 * column names as keys or property names.
692 * It ignores any elements with keys that are not defined as columns. It
693 * puts in empty strings into the row when there is no element in the passed
694 * array corresponding to a column in the table. It puts the row elements in
695 * the proper order (internally row table data is stored by in arrays with
696 * a numerical index corresponding to the column number).
698 * @param object|array $rowwithkeys array keys or object property names are column names,
699 * as defined in call to define_columns.
700 * @param string $classname CSS class name to add to this row's tr tag.
702 function add_data_keyed($rowwithkeys, $classname = '') {
703 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
707 * Add a number of rows to the table at once. And optionally finish output after they have been added.
709 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
710 * object or array is added to table. We expect properties for the row array as would be
711 * passed to add_data_keyed.
712 * @param bool $finish
714 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
715 foreach ($rowstoadd as $row) {
716 if (is_null($row)) {
717 $this->add_separator();
718 } else {
719 $this->add_data_keyed($this->format_row($row));
722 if ($finish) {
723 $this->finish_output(!$this->is_downloading());
728 * Add a seperator line to table.
730 function add_separator() {
731 if (!$this->setup) {
732 return false;
734 $this->add_data(NULL);
738 * This method actually directly echoes the row passed to it now or adds it
739 * to the download. If this is the first row and start_output has not
740 * already been called this method also calls start_output to open the table
741 * or send headers for the downloaded.
742 * Can be used as before. print_html now calls finish_html to close table.
744 * @param array $row a numerically keyed row of data to add to the table.
745 * @param string $classname CSS class name to add to this row's tr tag.
746 * @return bool success.
748 function add_data($row, $classname = '') {
749 if (!$this->setup) {
750 return false;
752 if (!$this->started_output) {
753 $this->start_output();
755 if ($this->exportclass!==null) {
756 if ($row === null) {
757 $this->exportclass->add_seperator();
758 } else {
759 $this->exportclass->add_data($row);
761 } else {
762 $this->print_row($row, $classname);
764 return true;
768 * You should call this to finish outputting the table data after adding
769 * data to the table with add_data or add_data_keyed.
772 function finish_output($closeexportclassdoc = true) {
773 if ($this->exportclass!==null) {
774 $this->exportclass->finish_table();
775 if ($closeexportclassdoc) {
776 $this->exportclass->finish_document();
778 } else {
779 $this->finish_html();
784 * Hook that can be overridden in child classes to wrap a table in a form
785 * for example. Called only when there is data to display and not
786 * downloading.
788 function wrap_html_start() {
792 * Hook that can be overridden in child classes to wrap a table in a form
793 * for example. Called only when there is data to display and not
794 * downloading.
796 function wrap_html_finish() {
800 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
801 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
802 * displaying table as html, adding a div wrap, etc.
804 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
806 * @param array|object $row row of data from db used to make one row of the table.
807 * @return array one row for the table, added using add_data_keyed method.
809 function format_row($row) {
810 if (is_array($row)) {
811 $row = (object)$row;
813 $formattedrow = array();
814 foreach (array_keys($this->columns) as $column) {
815 $colmethodname = 'col_'.$column;
816 if (method_exists($this, $colmethodname)) {
817 $formattedcolumn = $this->$colmethodname($row);
818 } else {
819 $formattedcolumn = $this->other_cols($column, $row);
820 if ($formattedcolumn===NULL) {
821 $formattedcolumn = $row->$column;
824 $formattedrow[$column] = $formattedcolumn;
826 return $formattedrow;
830 * Fullname is treated as a special columname in tablelib and should always
831 * be treated the same as the fullname of a user.
832 * @uses $this->useridfield if the userid field is not expected to be id
833 * then you need to override $this->useridfield to point at the correct
834 * field for the user id.
836 * @param object $row the data from the db containing all fields from the
837 * users table necessary to construct the full name of the user in
838 * current language.
839 * @return string contents of cell in column 'fullname', for this row.
841 function col_fullname($row) {
842 global $COURSE;
844 $name = fullname($row);
845 if ($this->download) {
846 return $name;
849 $userid = $row->{$this->useridfield};
850 if ($COURSE->id == SITEID) {
851 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
852 } else {
853 $profileurl = new moodle_url('/user/view.php',
854 array('id' => $userid, 'course' => $COURSE->id));
856 return html_writer::link($profileurl, $name);
860 * You can override this method in a child class. See the description of
861 * build_table which calls this method.
863 function other_cols($column, $row) {
864 return NULL;
868 * Used from col_* functions when text is to be displayed. Does the
869 * right thing - either converts text to html or strips any html tags
870 * depending on if we are downloading and what is the download type. Params
871 * are the same as format_text function in weblib.php but some default
872 * options are changed.
874 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
875 if (!$this->is_downloading()) {
876 if (is_null($options)) {
877 $options = new stdClass;
879 //some sensible defaults
880 if (!isset($options->para)) {
881 $options->para = false;
883 if (!isset($options->newlines)) {
884 $options->newlines = false;
886 if (!isset($options->smiley)) {
887 $options->smiley = false;
889 if (!isset($options->filter)) {
890 $options->filter = false;
892 return format_text($text, $format, $options);
893 } else {
894 $eci = $this->export_class_instance();
895 return $eci->format_text($text, $format, $options, $courseid);
899 * This method is deprecated although the old api is still supported.
900 * @deprecated 1.9.2 - Jun 2, 2008
902 function print_html() {
903 if (!$this->setup) {
904 return false;
906 $this->finish_html();
910 * This function is not part of the public api.
911 * @return string initial of first name we are currently filtering by
913 function get_initial_first() {
914 if (!$this->use_initials) {
915 return NULL;
918 return $this->prefs['i_first'];
922 * This function is not part of the public api.
923 * @return string initial of last name we are currently filtering by
925 function get_initial_last() {
926 if (!$this->use_initials) {
927 return NULL;
930 return $this->prefs['i_last'];
934 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
935 * @param array $alpha of letters in the alphabet.
936 * @param string $current the currently selected letter.
937 * @param string $class class name to add to this initial bar.
938 * @param string $title the name to put in front of this initial bar.
939 * @param string $urlvar URL parameter name for this initial.
941 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
942 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
943 $title . ' : ';
944 if ($current) {
945 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
946 } else {
947 echo html_writer::tag('strong', get_string('all'));
950 foreach ($alpha as $letter) {
951 if ($letter === $current) {
952 echo html_writer::tag('strong', $letter);
953 } else {
954 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
958 echo html_writer::end_tag('div');
962 * This function is not part of the public api.
964 function print_initials_bar() {
965 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
966 && isset($this->columns['fullname'])) {
968 $alpha = explode(',', get_string('alphabet', 'langconfig'));
970 // Bar of first initials
971 if (!empty($this->prefs['i_first'])) {
972 $ifirst = $this->prefs['i_first'];
973 } else {
974 $ifirst = '';
976 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
977 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
979 // Bar of last initials
980 if (!empty($this->prefs['i_last'])) {
981 $ilast = $this->prefs['i_last'];
982 } else {
983 $ilast = '';
985 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
986 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
991 * This function is not part of the public api.
993 function print_nothing_to_display() {
994 global $OUTPUT;
996 // Render button to allow user to reset table preferences.
997 echo $this->render_reset_button();
999 $this->print_initials_bar();
1001 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1005 * This function is not part of the public api.
1007 function get_row_from_keyed($rowwithkeys) {
1008 if (is_object($rowwithkeys)) {
1009 $rowwithkeys = (array)$rowwithkeys;
1011 $row = array();
1012 foreach (array_keys($this->columns) as $column) {
1013 if (isset($rowwithkeys[$column])) {
1014 $row [] = $rowwithkeys[$column];
1015 } else {
1016 $row[] ='';
1019 return $row;
1022 * This function is not part of the public api.
1024 function get_download_menu() {
1025 $allclasses= get_declared_classes();
1026 $exportclasses = array();
1027 foreach ($allclasses as $class) {
1028 $matches = array();
1029 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
1030 $type = $matches[1];
1031 $exportclasses[$type]= get_string("download$type", 'table');
1034 return $exportclasses;
1038 * This function is not part of the public api.
1040 function download_buttons() {
1041 if ($this->is_downloadable() && !$this->is_downloading()) {
1042 $downloadoptions = $this->get_download_menu();
1044 $downloadelements = new stdClass();
1045 $downloadelements->formatsmenu = html_writer::select($downloadoptions,
1046 'download', $this->defaultdownloadformat, false);
1047 $downloadelements->downloadbutton = '<input type="submit" value="'.
1048 get_string('download').'"/>';
1049 $html = '<form action="'. $this->baseurl .'" method="post">';
1050 $html .= '<div class="mdl-align">';
1051 $html .= html_writer::tag('label', get_string('downloadas', 'table', $downloadelements));
1052 $html .= '</div></form>';
1054 return $html;
1055 } else {
1056 return '';
1060 * This function is not part of the public api.
1061 * You don't normally need to call this. It is called automatically when
1062 * needed when you start adding data to the table.
1065 function start_output() {
1066 $this->started_output = true;
1067 if ($this->exportclass!==null) {
1068 $this->exportclass->start_table($this->sheettitle);
1069 $this->exportclass->output_headers($this->headers);
1070 } else {
1071 $this->start_html();
1072 $this->print_headers();
1073 echo html_writer::start_tag('tbody');
1078 * This function is not part of the public api.
1080 function print_row($row, $classname = '') {
1081 echo $this->get_row_html($row, $classname);
1085 * Generate html code for the passed row.
1087 * @param array $row Row data.
1088 * @param string $classname classes to add.
1090 * @return string $html html code for the row passed.
1092 public function get_row_html($row, $classname = '') {
1093 static $suppress_lastrow = NULL;
1094 $rowclasses = array();
1096 if ($classname) {
1097 $rowclasses[] = $classname;
1100 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1101 $html = '';
1103 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1105 // If we have a separator, print it
1106 if ($row === NULL) {
1107 $colcount = count($this->columns);
1108 $html .= html_writer::tag('td', html_writer::tag('div', '',
1109 array('class' => 'tabledivider')), array('colspan' => $colcount));
1111 } else {
1112 $colbyindex = array_flip($this->columns);
1113 foreach ($row as $index => $data) {
1114 $column = $colbyindex[$index];
1116 if (empty($this->prefs['collapse'][$column])) {
1117 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1118 $content = '&nbsp;';
1119 } else {
1120 $content = $data;
1122 } else {
1123 $content = '&nbsp;';
1126 $html .= html_writer::tag('td', $content, array(
1127 'class' => 'cell c' . $index . $this->column_class[$column],
1128 'id' => $rowid . '_c' . $index,
1129 'style' => $this->make_styles_string($this->column_style[$column])));
1133 $html .= html_writer::end_tag('tr');
1135 $suppress_enabled = array_sum($this->column_suppress);
1136 if ($suppress_enabled) {
1137 $suppress_lastrow = $row;
1139 $this->currentrow++;
1140 return $html;
1144 * This function is not part of the public api.
1146 function finish_html() {
1147 global $OUTPUT;
1148 if (!$this->started_output) {
1149 //no data has been added to the table.
1150 $this->print_nothing_to_display();
1152 } else {
1153 // Print empty rows to fill the table to the current pagesize.
1154 // This is done so the header aria-controls attributes do not point to
1155 // non existant elements.
1156 $emptyrow = array_fill(0, count($this->columns), '');
1157 while ($this->currentrow < $this->pagesize) {
1158 $this->print_row($emptyrow, 'emptyrow');
1161 echo html_writer::end_tag('tbody');
1162 echo html_writer::end_tag('table');
1163 echo html_writer::end_tag('div');
1164 $this->wrap_html_finish();
1166 // Paging bar
1167 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1168 echo $this->download_buttons();
1171 if($this->use_pages) {
1172 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1173 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1174 echo $OUTPUT->render($pagingbar);
1180 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1181 * used by {@link print_headers()}.
1182 * @param string $column the column name, index into various names.
1183 * @param int $index numerical index of the column.
1184 * @return string HTML fragment.
1186 protected function show_hide_link($column, $index) {
1187 global $OUTPUT;
1188 // Some headers contain <br /> tags, do not include in title, hence the
1189 // strip tags.
1191 $ariacontrols = '';
1192 for ($i = 0; $i < $this->pagesize; $i++) {
1193 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1196 $ariacontrols = trim($ariacontrols);
1198 if (!empty($this->prefs['collapse'][$column])) {
1199 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1200 'aria-expanded' => 'false',
1201 'aria-controls' => $ariacontrols);
1202 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1203 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1204 $linkattributes);
1206 } else if ($this->headers[$index] !== NULL) {
1207 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1208 'aria-expanded' => 'true',
1209 'aria-controls' => $ariacontrols);
1210 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1211 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1212 $linkattributes);
1217 * This function is not part of the public api.
1219 function print_headers() {
1220 global $CFG, $OUTPUT;
1222 echo html_writer::start_tag('thead');
1223 echo html_writer::start_tag('tr');
1224 foreach ($this->columns as $column => $index) {
1226 $icon_hide = '';
1227 if ($this->is_collapsible) {
1228 $icon_hide = $this->show_hide_link($column, $index);
1231 $primarysortcolumn = '';
1232 $primarysortorder = '';
1233 if (reset($this->prefs['sortby'])) {
1234 $primarysortcolumn = key($this->prefs['sortby']);
1235 $primarysortorder = current($this->prefs['sortby']);
1238 switch ($column) {
1240 case 'fullname':
1241 // Check the full name display for sortable fields.
1242 $nameformat = $CFG->fullnamedisplay;
1243 if ($nameformat == 'language') {
1244 $nameformat = get_string('fullnamedisplay');
1246 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1248 if (!empty($requirednames)) {
1249 if ($this->is_sortable($column)) {
1250 // Done this way for the possibility of more than two sortable full name display fields.
1251 $this->headers[$index] = '';
1252 foreach ($requirednames as $name) {
1253 $sortname = $this->sort_link(get_string($name),
1254 $name, $primarysortcolumn === $name, $primarysortorder);
1255 $this->headers[$index] .= $sortname . ' / ';
1257 $helpicon = '';
1258 if (isset($this->helpforheaders[$index])) {
1259 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1261 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1264 break;
1266 case 'userpic':
1267 // do nothing, do not display sortable links
1268 break;
1270 default:
1271 if ($this->is_sortable($column)) {
1272 $helpicon = '';
1273 if (isset($this->helpforheaders[$index])) {
1274 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1276 $this->headers[$index] = $this->sort_link($this->headers[$index],
1277 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1281 $attributes = array(
1282 'class' => 'header c' . $index . $this->column_class[$column],
1283 'scope' => 'col',
1285 if ($this->headers[$index] === NULL) {
1286 $content = '&nbsp;';
1287 } else if (!empty($this->prefs['collapse'][$column])) {
1288 $content = $icon_hide;
1289 } else {
1290 if (is_array($this->column_style[$column])) {
1291 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1293 $helpicon = '';
1294 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1295 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1297 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1298 $icon_hide, array('class' => 'commands'));
1300 echo html_writer::tag('th', $content, $attributes);
1303 echo html_writer::end_tag('tr');
1304 echo html_writer::end_tag('thead');
1308 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1309 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1310 * @param int $order SORT_ASC or SORT_DESC
1311 * @return string HTML fragment.
1313 protected function sort_icon($isprimary, $order) {
1314 global $OUTPUT;
1316 if (!$isprimary) {
1317 return '';
1320 if ($order == SORT_ASC) {
1321 return html_writer::empty_tag('img',
1322 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1323 } else {
1324 return html_writer::empty_tag('img',
1325 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1330 * Generate the correct tool tip for changing the sort order. This is a
1331 * helper method used by {@link sort_link()}.
1332 * @param bool $isprimary whether the is column is the current primary sort column.
1333 * @param int $order SORT_ASC or SORT_DESC
1334 * @return string the correct title.
1336 protected function sort_order_name($isprimary, $order) {
1337 if ($isprimary && $order != SORT_ASC) {
1338 return get_string('desc');
1339 } else {
1340 return get_string('asc');
1345 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1346 * @param string $text the text for the link.
1347 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1348 * @param bool $isprimary whether the is column is the current primary sort column.
1349 * @param int $order SORT_ASC or SORT_DESC
1350 * @return string HTML fragment.
1352 protected function sort_link($text, $column, $isprimary, $order) {
1353 return html_writer::link($this->baseurl->out(false,
1354 array($this->request[TABLE_VAR_SORT] => $column)),
1355 $text . get_accesshide(get_string('sortby') . ' ' .
1356 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1357 $this->sort_icon($isprimary, $order);
1361 * This function is not part of the public api.
1363 function start_html() {
1364 global $OUTPUT;
1366 // Render button to allow user to reset table preferences.
1367 echo $this->render_reset_button();
1369 // Do we need to print initial bars?
1370 $this->print_initials_bar();
1372 // Paging bar
1373 if ($this->use_pages) {
1374 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1375 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1376 echo $OUTPUT->render($pagingbar);
1379 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1380 echo $this->download_buttons();
1383 $this->wrap_html_start();
1384 // Start of main data table
1386 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1387 echo html_writer::start_tag('table', $this->attributes);
1392 * This function is not part of the public api.
1393 * @param array $styles CSS-property => value
1394 * @return string values suitably to go in a style="" attribute in HTML.
1396 function make_styles_string($styles) {
1397 if (empty($styles)) {
1398 return null;
1401 $string = '';
1402 foreach($styles as $property => $value) {
1403 $string .= $property . ':' . $value . ';';
1405 return $string;
1409 * Generate the HTML for the table preferences reset button.
1411 * @return string HTML fragment, empty string if no need to reset
1413 protected function render_reset_button() {
1415 if (!$this->can_be_reset()) {
1416 return '';
1419 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1421 $html = html_writer::start_div('resettable mdl-right');
1422 $html .= html_writer::link($url, get_string('resettable'));
1423 $html .= html_writer::end_div();
1425 return $html;
1429 * Are there some table preferences that can be reset?
1431 * If true, then the "reset table preferences" widget should be displayed.
1433 * @return bool
1435 protected function can_be_reset() {
1437 // Loop through preferences and make sure they are empty or set to the default value.
1438 foreach ($this->prefs as $prefname => $prefval) {
1440 if ($prefname === 'sortby' and !empty($this->sort_default_column)) {
1441 // Check if the actual sorting differs from the default one.
1442 if (empty($prefval) or $prefval !== array($this->sort_default_column => $this->sort_default_order)) {
1443 return true;
1446 } else if ($prefname === 'collapse' and !empty($prefval)) {
1447 // Check if there are some collapsed columns (all are expanded by default).
1448 foreach ($prefval as $columnname => $iscollapsed) {
1449 if ($iscollapsed) {
1450 return true;
1454 } else if (!empty($prefval)) {
1455 // For all other cases, we just check if some preference is set.
1456 return true;
1460 return false;
1466 * @package moodlecore
1467 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1470 class table_sql extends flexible_table {
1472 public $countsql = NULL;
1473 public $countparams = NULL;
1475 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1477 public $sql = NULL;
1479 * @var array|\Traversable Data fetched from the db.
1481 public $rawdata = NULL;
1484 * @var bool Overriding default for this.
1486 public $is_sortable = true;
1488 * @var bool Overriding default for this.
1490 public $is_collapsible = true;
1493 * @param string $uniqueid a string identifying this table.Used as a key in
1494 * session vars.
1496 function __construct($uniqueid) {
1497 parent::__construct($uniqueid);
1498 // some sensible defaults
1499 $this->set_attribute('cellspacing', '0');
1500 $this->set_attribute('class', 'generaltable generalbox');
1504 * Take the data returned from the db_query and go through all the rows
1505 * processing each col using either col_{columnname} method or other_cols
1506 * method or if other_cols returns NULL then put the data straight into the
1507 * table.
1509 * @return void
1511 function build_table() {
1513 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1514 return;
1516 if (!$this->rawdata) {
1517 return;
1520 foreach ($this->rawdata as $row) {
1521 $formattedrow = $this->format_row($row);
1522 $this->add_data_keyed($formattedrow,
1523 $this->get_row_class($row));
1526 if ($this->rawdata instanceof \core\dml\recordset_walk ||
1527 $this->rawdata instanceof moodle_recordset) {
1528 $this->rawdata->close();
1533 * Get any extra classes names to add to this row in the HTML.
1534 * @param $row array the data for this row.
1535 * @return string added to the class="" attribute of the tr.
1537 function get_row_class($row) {
1538 return '';
1542 * This is only needed if you want to use different sql to count rows.
1543 * Used for example when perhaps all db JOINS are not needed when counting
1544 * records. You don't need to call this function the count_sql
1545 * will be generated automatically.
1547 * We need to count rows returned by the db seperately to the query itself
1548 * as we need to know how many pages of data we have to display.
1550 function set_count_sql($sql, array $params = NULL) {
1551 $this->countsql = $sql;
1552 $this->countparams = $params;
1556 * Set the sql to query the db. Query will be :
1557 * SELECT $fields FROM $from WHERE $where
1558 * Of course you can use sub-queries, JOINS etc. by putting them in the
1559 * appropriate clause of the query.
1561 function set_sql($fields, $from, $where, array $params = NULL) {
1562 $this->sql = new stdClass();
1563 $this->sql->fields = $fields;
1564 $this->sql->from = $from;
1565 $this->sql->where = $where;
1566 $this->sql->params = $params;
1570 * Query the db. Store results in the table object for use by build_table.
1572 * @param int $pagesize size of page for paginated displayed table.
1573 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1574 * will only be used if there is a fullname column defined for the table.
1576 function query_db($pagesize, $useinitialsbar=true) {
1577 global $DB;
1578 if (!$this->is_downloading()) {
1579 if ($this->countsql === NULL) {
1580 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1581 $this->countparams = $this->sql->params;
1583 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1584 if ($useinitialsbar && !$this->is_downloading()) {
1585 $this->initialbars($grandtotal > $pagesize);
1588 list($wsql, $wparams) = $this->get_sql_where();
1589 if ($wsql) {
1590 $this->countsql .= ' AND '.$wsql;
1591 $this->countparams = array_merge($this->countparams, $wparams);
1593 $this->sql->where .= ' AND '.$wsql;
1594 $this->sql->params = array_merge($this->sql->params, $wparams);
1596 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1597 } else {
1598 $total = $grandtotal;
1601 $this->pagesize($pagesize, $total);
1604 // Fetch the attempts
1605 $sort = $this->get_sql_sort();
1606 if ($sort) {
1607 $sort = "ORDER BY $sort";
1609 $sql = "SELECT
1610 {$this->sql->fields}
1611 FROM {$this->sql->from}
1612 WHERE {$this->sql->where}
1613 {$sort}";
1615 if (!$this->is_downloading()) {
1616 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1617 } else {
1618 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1623 * Convenience method to call a number of methods for you to display the
1624 * table.
1626 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1627 global $DB;
1628 if (!$this->columns) {
1629 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1630 //if columns is not set then define columns as the keys of the rows returned
1631 //from the db.
1632 $this->define_columns(array_keys((array)$onerow));
1633 $this->define_headers(array_keys((array)$onerow));
1635 $this->setup();
1636 $this->query_db($pagesize, $useinitialsbar);
1637 $this->build_table();
1638 $this->finish_output();
1644 * @package moodlecore
1645 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1648 class table_default_export_format_parent {
1650 * @var flexible_table or child class reference pointing to table class
1651 * object from which to export data.
1653 var $table;
1656 * @var bool output started. Keeps track of whether any output has been
1657 * started yet.
1659 var $documentstarted = false;
1662 * Constructor
1664 * @param flexible_table $table
1666 public function __construct(&$table) {
1667 $this->table =& $table;
1671 * Old syntax of class constructor. Deprecated in PHP7.
1673 * @deprecated since Moodle 3.1
1675 public function table_default_export_format_parent(&$table) {
1676 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1677 self::__construct($table);
1680 function set_table(&$table) {
1681 $this->table =& $table;
1684 function add_data($row) {
1685 return false;
1688 function add_seperator() {
1689 return false;
1692 function document_started() {
1693 return $this->documentstarted;
1696 * Given text in a variety of format codings, this function returns
1697 * the text as safe HTML or as plain text dependent on what is appropriate
1698 * for the download format. The default removes all tags.
1700 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1701 //use some whitespace to indicate where there was some line spacing.
1702 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1703 return strip_tags($text);
1709 * @package moodlecore
1710 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1713 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1714 var $currentrow;
1715 var $workbook;
1716 var $worksheet;
1718 * @var object format object - format for normal table cells
1720 var $formatnormal;
1722 * @var object format object - format for header table cells
1724 var $formatheaders;
1727 * should be overriden in child class.
1729 var $fileextension;
1732 * This method will be overridden in the child class.
1734 function define_workbook() {
1737 function start_document($filename) {
1738 $filename = $filename.'.'.$this->fileextension;
1739 $this->define_workbook();
1740 // format types
1741 $this->formatnormal = $this->workbook->add_format();
1742 $this->formatnormal->set_bold(0);
1743 $this->formatheaders = $this->workbook->add_format();
1744 $this->formatheaders->set_bold(1);
1745 $this->formatheaders->set_align('center');
1746 // Sending HTTP headers
1747 $this->workbook->send($filename);
1748 $this->documentstarted = true;
1751 function start_table($sheettitle) {
1752 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1753 $this->currentrow=0;
1756 function output_headers($headers) {
1757 $colnum = 0;
1758 foreach ($headers as $item) {
1759 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1760 $colnum++;
1762 $this->currentrow++;
1765 function add_data($row) {
1766 $colnum = 0;
1767 foreach ($row as $item) {
1768 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1769 $colnum++;
1771 $this->currentrow++;
1772 return true;
1775 function add_seperator() {
1776 $this->currentrow++;
1777 return true;
1780 function finish_table() {
1783 function finish_document() {
1784 $this->workbook->close();
1785 exit;
1791 * @package moodlecore
1792 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1793 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1795 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1796 var $fileextension = 'xls';
1798 function define_workbook() {
1799 global $CFG;
1800 require_once("$CFG->libdir/excellib.class.php");
1801 // Creating a workbook
1802 $this->workbook = new MoodleExcelWorkbook("-");
1809 * @package moodlecore
1810 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1813 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1814 var $fileextension = 'ods';
1815 function define_workbook() {
1816 global $CFG;
1817 require_once("$CFG->libdir/odslib.class.php");
1818 // Creating a workbook
1819 $this->workbook = new MoodleODSWorkbook("-");
1825 * @package moodlecore
1826 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1829 class table_text_export_format_parent extends table_default_export_format_parent {
1830 protected $seperator = "tab";
1831 protected $mimetype = 'text/tab-separated-values';
1832 protected $ext = '.txt';
1833 protected $myexporter;
1835 public function __construct() {
1836 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1839 public function start_document($filename) {
1840 $this->filename = $filename;
1841 $this->documentstarted = true;
1842 $this->myexporter->set_filename($filename, $this->ext);
1845 public function start_table($sheettitle) {
1846 //nothing to do here
1849 public function output_headers($headers) {
1850 $this->myexporter->add_data($headers);
1853 public function add_data($row) {
1854 $this->myexporter->add_data($row);
1855 return true;
1858 public function finish_table() {
1859 //nothing to do here
1862 public function finish_document() {
1863 $this->myexporter->download_file();
1864 exit;
1868 * Format a row of data.
1869 * @param array $data
1871 protected function format_row($data) {
1872 $escapeddata = array();
1873 foreach ($data as $value) {
1874 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1876 return implode($this->seperator, $escapeddata) . "\n";
1882 * @package moodlecore
1883 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1884 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1886 class table_tsv_export_format extends table_text_export_format_parent {
1887 protected $seperator = "tab";
1888 protected $mimetype = 'text/tab-separated-values';
1889 protected $ext = '.txt';
1892 require_once($CFG->libdir . '/csvlib.class.php');
1894 * @package moodlecore
1895 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1898 class table_csv_export_format extends table_text_export_format_parent {
1899 protected $seperator = "comma";
1900 protected $mimetype = 'text/csv';
1901 protected $ext = '.csv';
1905 * @package moodlecore
1906 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1907 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1909 class table_xhtml_export_format extends table_default_export_format_parent {
1910 function start_document($filename) {
1911 header("Content-Type: application/download\n");
1912 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1913 header("Expires: 0");
1914 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1915 header("Pragma: public");
1916 //html headers
1917 echo <<<EOF
1918 <?xml version="1.0" encoding="UTF-8"?>
1919 <!DOCTYPE html
1920 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1921 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1923 <html xmlns="http://www.w3.org/1999/xhtml"
1924 xml:lang="en" lang="en">
1925 <head>
1926 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1927 <style type="text/css">/*<![CDATA[*/
1929 .flexible th {
1930 white-space:normal;
1932 th.header, td.header, div.header {
1933 border-color:#DDDDDD;
1934 background-color:lightGrey;
1936 .flexible th {
1937 white-space:nowrap;
1939 th {
1940 font-weight:bold;
1943 .generaltable {
1944 border-style:solid;
1946 .generalbox {
1947 border-style:solid;
1949 body, table, td, th {
1950 font-family:Arial,Verdana,Helvetica,sans-serif;
1951 font-size:100%;
1953 td {
1954 border-style:solid;
1955 border-width:1pt;
1957 table {
1958 border-collapse:collapse;
1959 border-spacing:0pt;
1960 width:80%;
1961 margin:auto;
1964 h1, h2 {
1965 text-align:center;
1967 .bold {
1968 font-weight:bold;
1970 .mdl-align {
1971 text-align:center;
1973 /*]]>*/</style>
1974 <title>$filename</title>
1975 </head>
1976 <body>
1977 EOF;
1978 $this->documentstarted = true;
1981 function start_table($sheettitle) {
1982 $this->table->sortable(false);
1983 $this->table->collapsible(false);
1984 echo "<h2>{$sheettitle}</h2>";
1985 $this->table->start_html();
1988 function output_headers($headers) {
1989 $this->table->print_headers();
1990 echo html_writer::start_tag('tbody');
1993 function add_data($row) {
1994 $this->table->print_row($row);
1995 return true;
1998 function add_seperator() {
1999 $this->table->print_row(NULL);
2000 return true;
2003 function finish_table() {
2004 $this->table->finish_html();
2007 function finish_document() {
2008 echo "</body>\n</html>";
2009 exit;
2012 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
2013 if (is_null($options)) {
2014 $options = new stdClass;
2016 //some sensible defaults
2017 if (!isset($options->para)) {
2018 $options->para = false;
2020 if (!isset($options->newlines)) {
2021 $options->newlines = false;
2023 if (!isset($options->smiley)) {
2024 $options->smiley = false;
2026 if (!isset($options->filter)) {
2027 $options->filter = false;
2029 return format_text($text, $format, $options);