Merge branch 'MDL-51434-master' of git://github.com/jleyva/moodle
[moodle.git] / lib / tablelib.php
blobc348e1fda40751244a32f3f1e1dc64de27aa5720
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 $setup = false;
71 var $baseurl = NULL;
72 var $request = array();
74 /**
75 * @var bool Whether or not to store table properties in the user_preferences table.
77 private $persistent = false;
78 var $is_collapsible = false;
79 var $is_sortable = false;
80 var $use_pages = false;
81 var $use_initials = false;
83 var $maxsortkeys = 2;
84 var $pagesize = 30;
85 var $currpage = 0;
86 var $totalrows = 0;
87 var $currentrow = 0;
88 var $sort_default_column = NULL;
89 var $sort_default_order = SORT_ASC;
91 /**
92 * Array of positions in which to display download controls.
94 var $showdownloadbuttonsat= array(TABLE_P_TOP);
96 /**
97 * @var string Key of field returned by db query that is the id field of the
98 * user table or equivalent.
100 public $useridfield = 'id';
103 * @var string which download plugin to use. Default '' means none - print
104 * html table with paging. Property set by is_downloading which typically
105 * passes in cleaned data from $
107 var $download = '';
110 * @var bool whether data is downloadable from table. Determines whether
111 * to display download buttons. Set by method downloadable().
113 var $downloadable = false;
116 * @var string which download plugin to use. Default '' means none - print
117 * html table with paging.
119 var $defaultdownloadformat = 'csv';
122 * @var bool Has start output been called yet?
124 var $started_output = false;
126 var $exportclass = null;
129 * @var array For storing user-customised table properties in the user_preferences db table.
131 private $prefs = array();
134 * Constructor
135 * @param int $uniqueid all tables have to have a unique id, this is used
136 * as a key when storing table properties like sort order in the session.
138 function __construct($uniqueid) {
139 $this->uniqueid = $uniqueid;
140 $this->request = array(
141 TABLE_VAR_SORT => 'tsort',
142 TABLE_VAR_HIDE => 'thide',
143 TABLE_VAR_SHOW => 'tshow',
144 TABLE_VAR_IFIRST => 'tifirst',
145 TABLE_VAR_ILAST => 'tilast',
146 TABLE_VAR_PAGE => 'page',
147 TABLE_VAR_RESET => 'treset'
152 * Call this to pass the download type. Use :
153 * $download = optional_param('download', '', PARAM_ALPHA);
154 * To get the download type. We assume that if you call this function with
155 * params that this table's data is downloadable, so we call is_downloadable
156 * for you (even if the param is '', which means no download this time.
157 * Also you can call this method with no params to get the current set
158 * download type.
159 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
160 * @param string $filename filename for downloads without file extension.
161 * @param string $sheettitle title for downloaded data.
162 * @return string download type. One of csv, tsv, xhtml, ods, etc
164 function is_downloading($download = null, $filename='', $sheettitle='') {
165 if ($download!==null) {
166 $this->sheettitle = $sheettitle;
167 $this->is_downloadable(true);
168 $this->download = $download;
169 $this->filename = clean_filename($filename);
170 $this->export_class_instance();
172 return $this->download;
176 * Get, and optionally set, the export class.
177 * @param $exportclass (optional) if passed, set the table to use this export class.
178 * @return table_default_export_format_parent the export class in use (after any set).
180 function export_class_instance($exportclass = null) {
181 if (!is_null($exportclass)) {
182 $this->started_output = true;
183 $this->exportclass = $exportclass;
184 $this->exportclass->table = $this;
185 } else if (is_null($this->exportclass) && !empty($this->download)) {
186 $classname = 'table_'.$this->download.'_export_format';
187 $this->exportclass = new $classname($this);
188 if (!$this->exportclass->document_started()) {
189 $this->exportclass->start_document($this->filename);
192 return $this->exportclass;
196 * Probably don't need to call this directly. Calling is_downloading with a
197 * param automatically sets table as downloadable.
199 * @param bool $downloadable optional param to set whether data from
200 * table is downloadable. If ommitted this function can be used to get
201 * current state of table.
202 * @return bool whether table data is set to be downloadable.
204 function is_downloadable($downloadable = null) {
205 if ($downloadable !== null) {
206 $this->downloadable = $downloadable;
208 return $this->downloadable;
212 * Call with boolean true to store table layout changes in the user_preferences table.
213 * Note: user_preferences.value has a maximum length of 1333 characters.
214 * Call with no parameter to get current state of table persistence.
216 * @param bool $persistent Optional parameter to set table layout persistence.
217 * @return bool Whether or not the table layout preferences will persist.
219 public function is_persistent($persistent = null) {
220 if ($persistent == true) {
221 $this->persistent = true;
223 return $this->persistent;
227 * Where to show download buttons.
228 * @param array $showat array of postions in which to show download buttons.
229 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
231 function show_download_buttons_at($showat) {
232 $this->showdownloadbuttonsat = $showat;
236 * Sets the is_sortable variable to the given boolean, sort_default_column to
237 * the given string, and the sort_default_order to the given integer.
238 * @param bool $bool
239 * @param string $defaultcolumn
240 * @param int $defaultorder
241 * @return void
243 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
244 $this->is_sortable = $bool;
245 $this->sort_default_column = $defaultcolumn;
246 $this->sort_default_order = $defaultorder;
250 * Use text sorting functions for this column (required for text columns with Oracle).
251 * Be warned that you cannot use this with column aliases. You can only do this
252 * with real columns. See MDL-40481 for an example.
253 * @param string column name
255 function text_sorting($column) {
256 $this->column_textsort[] = $column;
260 * Do not sort using this column
261 * @param string column name
263 function no_sorting($column) {
264 $this->column_nosort[] = $column;
268 * Is the column sortable?
269 * @param string column name, null means table
270 * @return bool
272 function is_sortable($column = null) {
273 if (empty($column)) {
274 return $this->is_sortable;
276 if (!$this->is_sortable) {
277 return false;
279 return !in_array($column, $this->column_nosort);
283 * Sets the is_collapsible variable to the given boolean.
284 * @param bool $bool
285 * @return void
287 function collapsible($bool) {
288 $this->is_collapsible = $bool;
292 * Sets the use_pages variable to the given boolean.
293 * @param bool $bool
294 * @return void
296 function pageable($bool) {
297 $this->use_pages = $bool;
301 * Sets the use_initials variable to the given boolean.
302 * @param bool $bool
303 * @return void
305 function initialbars($bool) {
306 $this->use_initials = $bool;
310 * Sets the pagesize variable to the given integer, the totalrows variable
311 * to the given integer, and the use_pages variable to true.
312 * @param int $perpage
313 * @param int $total
314 * @return void
316 function pagesize($perpage, $total) {
317 $this->pagesize = $perpage;
318 $this->totalrows = $total;
319 $this->use_pages = true;
323 * Assigns each given variable in the array to the corresponding index
324 * in the request class variable.
325 * @param array $variables
326 * @return void
328 function set_control_variables($variables) {
329 foreach ($variables as $what => $variable) {
330 if (isset($this->request[$what])) {
331 $this->request[$what] = $variable;
337 * Gives the given $value to the $attribute index of $this->attributes.
338 * @param string $attribute
339 * @param mixed $value
340 * @return void
342 function set_attribute($attribute, $value) {
343 $this->attributes[$attribute] = $value;
347 * What this method does is set the column so that if the same data appears in
348 * consecutive rows, then it is not repeated.
350 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
351 * that when one student has made multiple attempts, their name is only printed in the row
352 * for their first attempt.
353 * @param int $column the index of a column.
355 function column_suppress($column) {
356 if (isset($this->column_suppress[$column])) {
357 $this->column_suppress[$column] = true;
362 * Sets the given $column index to the given $classname in $this->column_class.
363 * @param int $column
364 * @param string $classname
365 * @return void
367 function column_class($column, $classname) {
368 if (isset($this->column_class[$column])) {
369 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
374 * Sets the given $column index and $property index to the given $value in $this->column_style.
375 * @param int $column
376 * @param string $property
377 * @param mixed $value
378 * @return void
380 function column_style($column, $property, $value) {
381 if (isset($this->column_style[$column])) {
382 $this->column_style[$column][$property] = $value;
387 * Sets all columns' $propertys to the given $value in $this->column_style.
388 * @param int $property
389 * @param string $value
390 * @return void
392 function column_style_all($property, $value) {
393 foreach (array_keys($this->columns) as $column) {
394 $this->column_style[$column][$property] = $value;
399 * Sets $this->baseurl.
400 * @param moodle_url|string $url the url with params needed to call up this page
402 function define_baseurl($url) {
403 $this->baseurl = new moodle_url($url);
407 * @param array $columns an array of identifying names for columns. If
408 * columns are sorted then column names must correspond to a field in sql.
410 function define_columns($columns) {
411 $this->columns = array();
412 $this->column_style = array();
413 $this->column_class = array();
414 $colnum = 0;
416 foreach ($columns as $column) {
417 $this->columns[$column] = $colnum++;
418 $this->column_style[$column] = array();
419 $this->column_class[$column] = '';
420 $this->column_suppress[$column] = false;
425 * @param array $headers numerical keyed array of displayed string titles
426 * for each column.
428 function define_headers($headers) {
429 $this->headers = $headers;
433 * Defines a help icon for the header
435 * Always use this function if you need to create header with sorting and help icon.
437 * @param renderable[] $helpicons An array of renderable objects to be used as help icons
439 public function define_help_for_headers($helpicons) {
440 $this->helpforheaders = $helpicons;
444 * Must be called after table is defined. Use methods above first. Cannot
445 * use functions below till after calling this method.
446 * @return type?
448 function setup() {
449 global $SESSION;
451 if (empty($this->columns) || empty($this->uniqueid)) {
452 return false;
455 // Load any existing user preferences.
456 if ($this->persistent) {
457 $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
458 } else if (isset($SESSION->flextable[$this->uniqueid])) {
459 $this->prefs = $SESSION->flextable[$this->uniqueid];
461 if (!$this->prefs) {
462 $this->prefs = array(
463 'collapse' => array(),
464 'sortby' => array(),
465 'i_first' => '',
466 'i_last' => '',
467 'textsort' => $this->column_textsort,
470 $oldprefs = $this->prefs;
472 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
473 isset($this->columns[$showcol])) {
474 $this->prefs['collapse'][$showcol] = false;
476 } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
477 isset($this->columns[$hidecol])) {
478 $this->prefs['collapse'][$hidecol] = true;
479 if (array_key_exists($hidecol, $this->prefs['sortby'])) {
480 unset($this->prefs['sortby'][$hidecol]);
484 // Now, update the column attributes for collapsed columns
485 foreach (array_keys($this->columns) as $column) {
486 if (!empty($this->prefs['collapse'][$column])) {
487 $this->column_style[$column]['width'] = '10px';
491 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
492 $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
493 (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
494 && isset($this->columns['fullname']))) {
496 if (array_key_exists($sortcol, $this->prefs['sortby'])) {
497 // This key already exists somewhere. Change its sortorder and bring it to the top.
498 $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
499 unset($this->prefs['sortby'][$sortcol]);
500 $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
501 } else {
502 // Key doesn't exist, so just add it to the beginning of the array, ascending order
503 $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
506 // Finally, make sure that no more than $this->maxsortkeys are present into the array
507 $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
510 // 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.
511 // This prevents results from being returned in a random order if the only order by column contains equal values.
512 if (!empty($this->sort_default_column)) {
513 if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
514 $defaultsort = array($this->sort_default_column => $this->sort_default_order);
515 $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
519 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
520 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
521 $this->prefs['i_last'] = $ilast;
524 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
525 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
526 $this->prefs['i_first'] = $ifirst;
529 // Allow user to reset table preferences.
530 if (optional_param($this->request[TABLE_VAR_RESET], 0, PARAM_BOOL) === 1) {
531 $this->prefs = array(
532 'collapse' => array(),
533 'sortby' => array(),
534 'i_first' => '',
535 'i_last' => '',
536 'textsort' => $this->column_textsort,
540 // Save user preferences if they have changed.
541 if ($this->prefs != $oldprefs) {
542 if ($this->persistent) {
543 set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
544 } else {
545 $SESSION->flextable[$this->uniqueid] = $this->prefs;
548 unset($oldprefs);
550 if (empty($this->baseurl)) {
551 debugging('You should set baseurl when using flexible_table.');
552 global $PAGE;
553 $this->baseurl = $PAGE->url;
556 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
557 $this->setup = true;
559 // Always introduce the "flexible" class for the table if not specified
560 if (empty($this->attributes)) {
561 $this->attributes['class'] = 'flexible';
562 } else if (!isset($this->attributes['class'])) {
563 $this->attributes['class'] = 'flexible';
564 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
565 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
570 * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
571 * @param string $uniqueid the identifier for a table.
572 * @return SQL fragment that can be used in an ORDER BY clause.
574 public static function get_sort_for_table($uniqueid) {
575 global $SESSION;
576 if (isset($SESSION->flextable[$uniqueid])) {
577 $prefs = $SESSION->flextable[$uniqueid];
578 } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
579 return '';
582 if (empty($prefs['sortby'])) {
583 return '';
585 if (empty($prefs['textsort'])) {
586 $prefs['textsort'] = array();
589 return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
593 * Prepare an an order by clause from the list of columns to be sorted.
594 * @param array $cols column name => SORT_ASC or SORT_DESC
595 * @return SQL fragment that can be used in an ORDER BY clause.
597 public static function construct_order_by($cols, $textsortcols=array()) {
598 global $DB;
599 $bits = array();
601 foreach ($cols as $column => $order) {
602 if (in_array($column, $textsortcols)) {
603 $column = $DB->sql_order_by_text($column);
605 if ($order == SORT_ASC) {
606 $bits[] = $column . ' ASC';
607 } else {
608 $bits[] = $column . ' DESC';
612 return implode(', ', $bits);
616 * @return SQL fragment that can be used in an ORDER BY clause.
618 public function get_sql_sort() {
619 return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
623 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
624 * @return array column name => SORT_... constant.
626 public function get_sort_columns() {
627 if (!$this->setup) {
628 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
631 if (empty($this->prefs['sortby'])) {
632 return array();
635 foreach ($this->prefs['sortby'] as $column => $notused) {
636 if (isset($this->columns[$column])) {
637 continue; // This column is OK.
639 if (in_array($column, get_all_user_name_fields()) &&
640 isset($this->columns['fullname'])) {
641 continue; // This column is OK.
643 // This column is not OK.
644 unset($this->prefs['sortby'][$column]);
647 return $this->prefs['sortby'];
651 * @return int the offset for LIMIT clause of SQL
653 function get_page_start() {
654 if (!$this->use_pages) {
655 return '';
657 return $this->currpage * $this->pagesize;
661 * @return int the pagesize for LIMIT clause of SQL
663 function get_page_size() {
664 if (!$this->use_pages) {
665 return '';
667 return $this->pagesize;
671 * @return string sql to add to where statement.
673 function get_sql_where() {
674 global $DB;
676 $conditions = array();
677 $params = array();
679 if (isset($this->columns['fullname'])) {
680 static $i = 0;
681 $i++;
683 if (!empty($this->prefs['i_first'])) {
684 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
685 $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
687 if (!empty($this->prefs['i_last'])) {
688 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
689 $params['ilastc'.$i] = $this->prefs['i_last'].'%';
693 return array(implode(" AND ", $conditions), $params);
697 * Add a row of data to the table. This function takes an array or object with
698 * column names as keys or property names.
700 * It ignores any elements with keys that are not defined as columns. It
701 * puts in empty strings into the row when there is no element in the passed
702 * array corresponding to a column in the table. It puts the row elements in
703 * the proper order (internally row table data is stored by in arrays with
704 * a numerical index corresponding to the column number).
706 * @param object|array $rowwithkeys array keys or object property names are column names,
707 * as defined in call to define_columns.
708 * @param string $classname CSS class name to add to this row's tr tag.
710 function add_data_keyed($rowwithkeys, $classname = '') {
711 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
715 * Add a number of rows to the table at once. And optionally finish output after they have been added.
717 * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
718 * object or array is added to table. We expect properties for the row array as would be
719 * passed to add_data_keyed.
720 * @param bool $finish
722 public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
723 foreach ($rowstoadd as $row) {
724 if (is_null($row)) {
725 $this->add_separator();
726 } else {
727 $this->add_data_keyed($this->format_row($row));
730 if ($finish) {
731 $this->finish_output(!$this->is_downloading());
736 * Add a seperator line to table.
738 function add_separator() {
739 if (!$this->setup) {
740 return false;
742 $this->add_data(NULL);
746 * This method actually directly echoes the row passed to it now or adds it
747 * to the download. If this is the first row and start_output has not
748 * already been called this method also calls start_output to open the table
749 * or send headers for the downloaded.
750 * Can be used as before. print_html now calls finish_html to close table.
752 * @param array $row a numerically keyed row of data to add to the table.
753 * @param string $classname CSS class name to add to this row's tr tag.
754 * @return bool success.
756 function add_data($row, $classname = '') {
757 if (!$this->setup) {
758 return false;
760 if (!$this->started_output) {
761 $this->start_output();
763 if ($this->exportclass!==null) {
764 if ($row === null) {
765 $this->exportclass->add_seperator();
766 } else {
767 $this->exportclass->add_data($row);
769 } else {
770 $this->print_row($row, $classname);
772 return true;
776 * You should call this to finish outputting the table data after adding
777 * data to the table with add_data or add_data_keyed.
780 function finish_output($closeexportclassdoc = true) {
781 if ($this->exportclass!==null) {
782 $this->exportclass->finish_table();
783 if ($closeexportclassdoc) {
784 $this->exportclass->finish_document();
786 } else {
787 $this->finish_html();
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_start() {
800 * Hook that can be overridden in child classes to wrap a table in a form
801 * for example. Called only when there is data to display and not
802 * downloading.
804 function wrap_html_finish() {
808 * Call appropriate methods on this table class to perform any processing on values before displaying in table.
809 * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
810 * displaying table as html, adding a div wrap, etc.
812 * See for example col_fullname below which will be called for a column whose name is 'fullname'.
814 * @param array|object $row row of data from db used to make one row of the table.
815 * @return array one row for the table, added using add_data_keyed method.
817 function format_row($row) {
818 if (is_array($row)) {
819 $row = (object)$row;
821 $formattedrow = array();
822 foreach (array_keys($this->columns) as $column) {
823 $colmethodname = 'col_'.$column;
824 if (method_exists($this, $colmethodname)) {
825 $formattedcolumn = $this->$colmethodname($row);
826 } else {
827 $formattedcolumn = $this->other_cols($column, $row);
828 if ($formattedcolumn===NULL) {
829 $formattedcolumn = $row->$column;
832 $formattedrow[$column] = $formattedcolumn;
834 return $formattedrow;
838 * Fullname is treated as a special columname in tablelib and should always
839 * be treated the same as the fullname of a user.
840 * @uses $this->useridfield if the userid field is not expected to be id
841 * then you need to override $this->useridfield to point at the correct
842 * field for the user id.
844 * @param object $row the data from the db containing all fields from the
845 * users table necessary to construct the full name of the user in
846 * current language.
847 * @return string contents of cell in column 'fullname', for this row.
849 function col_fullname($row) {
850 global $COURSE;
852 $name = fullname($row);
853 if ($this->download) {
854 return $name;
857 $userid = $row->{$this->useridfield};
858 if ($COURSE->id == SITEID) {
859 $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
860 } else {
861 $profileurl = new moodle_url('/user/view.php',
862 array('id' => $userid, 'course' => $COURSE->id));
864 return html_writer::link($profileurl, $name);
868 * You can override this method in a child class. See the description of
869 * build_table which calls this method.
871 function other_cols($column, $row) {
872 return NULL;
876 * Used from col_* functions when text is to be displayed. Does the
877 * right thing - either converts text to html or strips any html tags
878 * depending on if we are downloading and what is the download type. Params
879 * are the same as format_text function in weblib.php but some default
880 * options are changed.
882 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
883 if (!$this->is_downloading()) {
884 if (is_null($options)) {
885 $options = new stdClass;
887 //some sensible defaults
888 if (!isset($options->para)) {
889 $options->para = false;
891 if (!isset($options->newlines)) {
892 $options->newlines = false;
894 if (!isset($options->smiley)) {
895 $options->smiley = false;
897 if (!isset($options->filter)) {
898 $options->filter = false;
900 return format_text($text, $format, $options);
901 } else {
902 $eci = $this->export_class_instance();
903 return $eci->format_text($text, $format, $options, $courseid);
907 * This method is deprecated although the old api is still supported.
908 * @deprecated 1.9.2 - Jun 2, 2008
910 function print_html() {
911 if (!$this->setup) {
912 return false;
914 $this->finish_html();
918 * This function is not part of the public api.
919 * @return string initial of first name we are currently filtering by
921 function get_initial_first() {
922 if (!$this->use_initials) {
923 return NULL;
926 return $this->prefs['i_first'];
930 * This function is not part of the public api.
931 * @return string initial of last name we are currently filtering by
933 function get_initial_last() {
934 if (!$this->use_initials) {
935 return NULL;
938 return $this->prefs['i_last'];
942 * Helper function, used by {@link print_initials_bar()} to output one initial bar.
943 * @param array $alpha of letters in the alphabet.
944 * @param string $current the currently selected letter.
945 * @param string $class class name to add to this initial bar.
946 * @param string $title the name to put in front of this initial bar.
947 * @param string $urlvar URL parameter name for this initial.
949 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
950 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
951 $title . ' : ';
952 if ($current) {
953 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
954 } else {
955 echo html_writer::tag('strong', get_string('all'));
958 foreach ($alpha as $letter) {
959 if ($letter === $current) {
960 echo html_writer::tag('strong', $letter);
961 } else {
962 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
966 echo html_writer::end_tag('div');
970 * This function is not part of the public api.
972 function print_initials_bar() {
973 if ((!empty($this->prefs['i_last']) || !empty($this->prefs['i_first']) ||$this->use_initials)
974 && isset($this->columns['fullname'])) {
976 $alpha = explode(',', get_string('alphabet', 'langconfig'));
978 // Bar of first initials
979 if (!empty($this->prefs['i_first'])) {
980 $ifirst = $this->prefs['i_first'];
981 } else {
982 $ifirst = '';
984 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
985 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
987 // Bar of last initials
988 if (!empty($this->prefs['i_last'])) {
989 $ilast = $this->prefs['i_last'];
990 } else {
991 $ilast = '';
993 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
994 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
999 * This function is not part of the public api.
1001 function print_nothing_to_display() {
1002 global $OUTPUT;
1004 // Render button to allow user to reset table preferences.
1005 echo $this->render_reset_button();
1007 $this->print_initials_bar();
1009 echo $OUTPUT->heading(get_string('nothingtodisplay'));
1013 * This function is not part of the public api.
1015 function get_row_from_keyed($rowwithkeys) {
1016 if (is_object($rowwithkeys)) {
1017 $rowwithkeys = (array)$rowwithkeys;
1019 $row = array();
1020 foreach (array_keys($this->columns) as $column) {
1021 if (isset($rowwithkeys[$column])) {
1022 $row [] = $rowwithkeys[$column];
1023 } else {
1024 $row[] ='';
1027 return $row;
1030 * This function is not part of the public api.
1032 function get_download_menu() {
1033 $allclasses= get_declared_classes();
1034 $exportclasses = array();
1035 foreach ($allclasses as $class) {
1036 $matches = array();
1037 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
1038 $type = $matches[1];
1039 $exportclasses[$type]= get_string("download$type", 'table');
1042 return $exportclasses;
1046 * This function is not part of the public api.
1048 function download_buttons() {
1049 if ($this->is_downloadable() && !$this->is_downloading()) {
1050 $downloadoptions = $this->get_download_menu();
1052 $downloadelements = new stdClass();
1053 $downloadelements->formatsmenu = html_writer::select($downloadoptions,
1054 'download', $this->defaultdownloadformat, false);
1055 $downloadelements->downloadbutton = '<input type="submit" value="'.
1056 get_string('download').'"/>';
1057 $html = '<form action="'. $this->baseurl .'" method="post">';
1058 $html .= '<div class="mdl-align">';
1059 $html .= html_writer::tag('label', get_string('downloadas', 'table', $downloadelements));
1060 $html .= '</div></form>';
1062 return $html;
1063 } else {
1064 return '';
1068 * This function is not part of the public api.
1069 * You don't normally need to call this. It is called automatically when
1070 * needed when you start adding data to the table.
1073 function start_output() {
1074 $this->started_output = true;
1075 if ($this->exportclass!==null) {
1076 $this->exportclass->start_table($this->sheettitle);
1077 $this->exportclass->output_headers($this->headers);
1078 } else {
1079 $this->start_html();
1080 $this->print_headers();
1081 echo html_writer::start_tag('tbody');
1086 * This function is not part of the public api.
1088 function print_row($row, $classname = '') {
1089 echo $this->get_row_html($row, $classname);
1093 * Generate html code for the passed row.
1095 * @param array $row Row data.
1096 * @param string $classname classes to add.
1098 * @return string $html html code for the row passed.
1100 public function get_row_html($row, $classname = '') {
1101 static $suppress_lastrow = NULL;
1102 $rowclasses = array();
1104 if ($classname) {
1105 $rowclasses[] = $classname;
1108 $rowid = $this->uniqueid . '_r' . $this->currentrow;
1109 $html = '';
1111 $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
1113 // If we have a separator, print it
1114 if ($row === NULL) {
1115 $colcount = count($this->columns);
1116 $html .= html_writer::tag('td', html_writer::tag('div', '',
1117 array('class' => 'tabledivider')), array('colspan' => $colcount));
1119 } else {
1120 $colbyindex = array_flip($this->columns);
1121 foreach ($row as $index => $data) {
1122 $column = $colbyindex[$index];
1124 if (empty($this->prefs['collapse'][$column])) {
1125 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
1126 $content = '&nbsp;';
1127 } else {
1128 $content = $data;
1130 } else {
1131 $content = '&nbsp;';
1134 $html .= html_writer::tag('td', $content, array(
1135 'class' => 'cell c' . $index . $this->column_class[$column],
1136 'id' => $rowid . '_c' . $index,
1137 'style' => $this->make_styles_string($this->column_style[$column])));
1141 $html .= html_writer::end_tag('tr');
1143 $suppress_enabled = array_sum($this->column_suppress);
1144 if ($suppress_enabled) {
1145 $suppress_lastrow = $row;
1147 $this->currentrow++;
1148 return $html;
1152 * This function is not part of the public api.
1154 function finish_html() {
1155 global $OUTPUT;
1156 if (!$this->started_output) {
1157 //no data has been added to the table.
1158 $this->print_nothing_to_display();
1160 } else {
1161 // Print empty rows to fill the table to the current pagesize.
1162 // This is done so the header aria-controls attributes do not point to
1163 // non existant elements.
1164 $emptyrow = array_fill(0, count($this->columns), '');
1165 while ($this->currentrow < $this->pagesize) {
1166 $this->print_row($emptyrow, 'emptyrow');
1169 echo html_writer::end_tag('tbody');
1170 echo html_writer::end_tag('table');
1171 echo html_writer::end_tag('div');
1172 $this->wrap_html_finish();
1174 // Paging bar
1175 if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
1176 echo $this->download_buttons();
1179 if($this->use_pages) {
1180 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1181 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1182 echo $OUTPUT->render($pagingbar);
1188 * Generate the HTML for the collapse/uncollapse icon. This is a helper method
1189 * used by {@link print_headers()}.
1190 * @param string $column the column name, index into various names.
1191 * @param int $index numerical index of the column.
1192 * @return string HTML fragment.
1194 protected function show_hide_link($column, $index) {
1195 global $OUTPUT;
1196 // Some headers contain <br /> tags, do not include in title, hence the
1197 // strip tags.
1199 $ariacontrols = '';
1200 for ($i = 0; $i < $this->pagesize; $i++) {
1201 $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
1204 $ariacontrols = trim($ariacontrols);
1206 if (!empty($this->prefs['collapse'][$column])) {
1207 $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
1208 'aria-expanded' => 'false',
1209 'aria-controls' => $ariacontrols);
1210 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
1211 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_plus'), 'alt' => get_string('show'))),
1212 $linkattributes);
1214 } else if ($this->headers[$index] !== NULL) {
1215 $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
1216 'aria-expanded' => 'true',
1217 'aria-controls' => $ariacontrols);
1218 return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
1219 html_writer::empty_tag('img', array('src' => $OUTPUT->pix_url('t/switch_minus'), 'alt' => get_string('hide'))),
1220 $linkattributes);
1225 * This function is not part of the public api.
1227 function print_headers() {
1228 global $CFG, $OUTPUT;
1230 echo html_writer::start_tag('thead');
1231 echo html_writer::start_tag('tr');
1232 foreach ($this->columns as $column => $index) {
1234 $icon_hide = '';
1235 if ($this->is_collapsible) {
1236 $icon_hide = $this->show_hide_link($column, $index);
1239 $primarysortcolumn = '';
1240 $primarysortorder = '';
1241 if (reset($this->prefs['sortby'])) {
1242 $primarysortcolumn = key($this->prefs['sortby']);
1243 $primarysortorder = current($this->prefs['sortby']);
1246 switch ($column) {
1248 case 'fullname':
1249 // Check the full name display for sortable fields.
1250 $nameformat = $CFG->fullnamedisplay;
1251 if ($nameformat == 'language') {
1252 $nameformat = get_string('fullnamedisplay');
1254 $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
1256 if (!empty($requirednames)) {
1257 if ($this->is_sortable($column)) {
1258 // Done this way for the possibility of more than two sortable full name display fields.
1259 $this->headers[$index] = '';
1260 foreach ($requirednames as $name) {
1261 $sortname = $this->sort_link(get_string($name),
1262 $name, $primarysortcolumn === $name, $primarysortorder);
1263 $this->headers[$index] .= $sortname . ' / ';
1265 $helpicon = '';
1266 if (isset($this->helpforheaders[$index])) {
1267 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1269 $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
1272 break;
1274 case 'userpic':
1275 // do nothing, do not display sortable links
1276 break;
1278 default:
1279 if ($this->is_sortable($column)) {
1280 $helpicon = '';
1281 if (isset($this->helpforheaders[$index])) {
1282 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1284 $this->headers[$index] = $this->sort_link($this->headers[$index],
1285 $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
1289 $attributes = array(
1290 'class' => 'header c' . $index . $this->column_class[$column],
1291 'scope' => 'col',
1293 if ($this->headers[$index] === NULL) {
1294 $content = '&nbsp;';
1295 } else if (!empty($this->prefs['collapse'][$column])) {
1296 $content = $icon_hide;
1297 } else {
1298 if (is_array($this->column_style[$column])) {
1299 $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
1301 $helpicon = '';
1302 if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
1303 $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
1305 $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
1306 $icon_hide, array('class' => 'commands'));
1308 echo html_writer::tag('th', $content, $attributes);
1311 echo html_writer::end_tag('tr');
1312 echo html_writer::end_tag('thead');
1316 * Generate the HTML for the sort icon. This is a helper method used by {@link sort_link()}.
1317 * @param bool $isprimary whether an icon is needed (it is only needed for the primary sort column.)
1318 * @param int $order SORT_ASC or SORT_DESC
1319 * @return string HTML fragment.
1321 protected function sort_icon($isprimary, $order) {
1322 global $OUTPUT;
1324 if (!$isprimary) {
1325 return '';
1328 if ($order == SORT_ASC) {
1329 return html_writer::empty_tag('img',
1330 array('src' => $OUTPUT->pix_url('t/sort_asc'), 'alt' => get_string('asc'), 'class' => 'iconsort'));
1331 } else {
1332 return html_writer::empty_tag('img',
1333 array('src' => $OUTPUT->pix_url('t/sort_desc'), 'alt' => get_string('desc'), 'class' => 'iconsort'));
1338 * Generate the correct tool tip for changing the sort order. This is a
1339 * helper method used by {@link sort_link()}.
1340 * @param bool $isprimary whether the is column is the current primary sort column.
1341 * @param int $order SORT_ASC or SORT_DESC
1342 * @return string the correct title.
1344 protected function sort_order_name($isprimary, $order) {
1345 if ($isprimary && $order != SORT_ASC) {
1346 return get_string('desc');
1347 } else {
1348 return get_string('asc');
1353 * Generate the HTML for the sort link. This is a helper method used by {@link print_headers()}.
1354 * @param string $text the text for the link.
1355 * @param string $column the column name, may be a fake column like 'firstname' or a real one.
1356 * @param bool $isprimary whether the is column is the current primary sort column.
1357 * @param int $order SORT_ASC or SORT_DESC
1358 * @return string HTML fragment.
1360 protected function sort_link($text, $column, $isprimary, $order) {
1361 return html_writer::link($this->baseurl->out(false,
1362 array($this->request[TABLE_VAR_SORT] => $column)),
1363 $text . get_accesshide(get_string('sortby') . ' ' .
1364 $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' .
1365 $this->sort_icon($isprimary, $order);
1369 * This function is not part of the public api.
1371 function start_html() {
1372 global $OUTPUT;
1374 // Render button to allow user to reset table preferences.
1375 echo $this->render_reset_button();
1377 // Do we need to print initial bars?
1378 $this->print_initials_bar();
1380 // Paging bar
1381 if ($this->use_pages) {
1382 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
1383 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
1384 echo $OUTPUT->render($pagingbar);
1387 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
1388 echo $this->download_buttons();
1391 $this->wrap_html_start();
1392 // Start of main data table
1394 echo html_writer::start_tag('div', array('class' => 'no-overflow'));
1395 echo html_writer::start_tag('table', $this->attributes);
1400 * This function is not part of the public api.
1401 * @param array $styles CSS-property => value
1402 * @return string values suitably to go in a style="" attribute in HTML.
1404 function make_styles_string($styles) {
1405 if (empty($styles)) {
1406 return null;
1409 $string = '';
1410 foreach($styles as $property => $value) {
1411 $string .= $property . ':' . $value . ';';
1413 return $string;
1417 * Generate the HTML for the table preferences reset button.
1419 * @return string HTML fragment.
1421 private function render_reset_button() {
1422 $url = $this->baseurl->out(false, array($this->request[TABLE_VAR_RESET] => 1));
1424 $html = html_writer::start_div('mdl-right');
1425 $html .= html_writer::link($url, get_string('resettable'));
1426 $html .= html_writer::end_div();
1428 return $html;
1434 * @package moodlecore
1435 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1438 class table_sql extends flexible_table {
1440 public $countsql = NULL;
1441 public $countparams = NULL;
1443 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
1445 public $sql = NULL;
1447 * @var array|\Traversable Data fetched from the db.
1449 public $rawdata = NULL;
1452 * @var bool Overriding default for this.
1454 public $is_sortable = true;
1456 * @var bool Overriding default for this.
1458 public $is_collapsible = true;
1461 * @param string $uniqueid a string identifying this table.Used as a key in
1462 * session vars.
1464 function __construct($uniqueid) {
1465 parent::__construct($uniqueid);
1466 // some sensible defaults
1467 $this->set_attribute('cellspacing', '0');
1468 $this->set_attribute('class', 'generaltable generalbox');
1472 * Take the data returned from the db_query and go through all the rows
1473 * processing each col using either col_{columnname} method or other_cols
1474 * method or if other_cols returns NULL then put the data straight into the
1475 * table.
1477 * @return void
1479 function build_table() {
1481 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
1482 return;
1484 if (!$this->rawdata) {
1485 return;
1488 foreach ($this->rawdata as $row) {
1489 $formattedrow = $this->format_row($row);
1490 $this->add_data_keyed($formattedrow,
1491 $this->get_row_class($row));
1494 if ($this->rawdata instanceof \core\dml\recordset_walk ||
1495 $this->rawdata instanceof moodle_recordset) {
1496 $this->rawdata->close();
1501 * Get any extra classes names to add to this row in the HTML.
1502 * @param $row array the data for this row.
1503 * @return string added to the class="" attribute of the tr.
1505 function get_row_class($row) {
1506 return '';
1510 * This is only needed if you want to use different sql to count rows.
1511 * Used for example when perhaps all db JOINS are not needed when counting
1512 * records. You don't need to call this function the count_sql
1513 * will be generated automatically.
1515 * We need to count rows returned by the db seperately to the query itself
1516 * as we need to know how many pages of data we have to display.
1518 function set_count_sql($sql, array $params = NULL) {
1519 $this->countsql = $sql;
1520 $this->countparams = $params;
1524 * Set the sql to query the db. Query will be :
1525 * SELECT $fields FROM $from WHERE $where
1526 * Of course you can use sub-queries, JOINS etc. by putting them in the
1527 * appropriate clause of the query.
1529 function set_sql($fields, $from, $where, array $params = NULL) {
1530 $this->sql = new stdClass();
1531 $this->sql->fields = $fields;
1532 $this->sql->from = $from;
1533 $this->sql->where = $where;
1534 $this->sql->params = $params;
1538 * Query the db. Store results in the table object for use by build_table.
1540 * @param int $pagesize size of page for paginated displayed table.
1541 * @param bool $useinitialsbar do you want to use the initials bar. Bar
1542 * will only be used if there is a fullname column defined for the table.
1544 function query_db($pagesize, $useinitialsbar=true) {
1545 global $DB;
1546 if (!$this->is_downloading()) {
1547 if ($this->countsql === NULL) {
1548 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1549 $this->countparams = $this->sql->params;
1551 $grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
1552 if ($useinitialsbar && !$this->is_downloading()) {
1553 $this->initialbars($grandtotal > $pagesize);
1556 list($wsql, $wparams) = $this->get_sql_where();
1557 if ($wsql) {
1558 $this->countsql .= ' AND '.$wsql;
1559 $this->countparams = array_merge($this->countparams, $wparams);
1561 $this->sql->where .= ' AND '.$wsql;
1562 $this->sql->params = array_merge($this->sql->params, $wparams);
1564 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1565 } else {
1566 $total = $grandtotal;
1569 $this->pagesize($pagesize, $total);
1572 // Fetch the attempts
1573 $sort = $this->get_sql_sort();
1574 if ($sort) {
1575 $sort = "ORDER BY $sort";
1577 $sql = "SELECT
1578 {$this->sql->fields}
1579 FROM {$this->sql->from}
1580 WHERE {$this->sql->where}
1581 {$sort}";
1583 if (!$this->is_downloading()) {
1584 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
1585 } else {
1586 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
1591 * Convenience method to call a number of methods for you to display the
1592 * table.
1594 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
1595 global $DB;
1596 if (!$this->columns) {
1597 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
1598 //if columns is not set then define columns as the keys of the rows returned
1599 //from the db.
1600 $this->define_columns(array_keys((array)$onerow));
1601 $this->define_headers(array_keys((array)$onerow));
1603 $this->setup();
1604 $this->query_db($pagesize, $useinitialsbar);
1605 $this->build_table();
1606 $this->finish_output();
1612 * @package moodlecore
1613 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1616 class table_default_export_format_parent {
1618 * @var flexible_table or child class reference pointing to table class
1619 * object from which to export data.
1621 var $table;
1624 * @var bool output started. Keeps track of whether any output has been
1625 * started yet.
1627 var $documentstarted = false;
1628 function table_default_export_format_parent(&$table) {
1629 $this->table =& $table;
1632 function set_table(&$table) {
1633 $this->table =& $table;
1636 function add_data($row) {
1637 return false;
1640 function add_seperator() {
1641 return false;
1644 function document_started() {
1645 return $this->documentstarted;
1648 * Given text in a variety of format codings, this function returns
1649 * the text as safe HTML or as plain text dependent on what is appropriate
1650 * for the download format. The default removes all tags.
1652 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1653 //use some whitespace to indicate where there was some line spacing.
1654 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1655 return strip_tags($text);
1661 * @package moodlecore
1662 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1663 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1665 class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
1666 var $currentrow;
1667 var $workbook;
1668 var $worksheet;
1670 * @var object format object - format for normal table cells
1672 var $formatnormal;
1674 * @var object format object - format for header table cells
1676 var $formatheaders;
1679 * should be overriden in child class.
1681 var $fileextension;
1684 * This method will be overridden in the child class.
1686 function define_workbook() {
1689 function start_document($filename) {
1690 $filename = $filename.'.'.$this->fileextension;
1691 $this->define_workbook();
1692 // format types
1693 $this->formatnormal = $this->workbook->add_format();
1694 $this->formatnormal->set_bold(0);
1695 $this->formatheaders = $this->workbook->add_format();
1696 $this->formatheaders->set_bold(1);
1697 $this->formatheaders->set_align('center');
1698 // Sending HTTP headers
1699 $this->workbook->send($filename);
1700 $this->documentstarted = true;
1703 function start_table($sheettitle) {
1704 $this->worksheet = $this->workbook->add_worksheet($sheettitle);
1705 $this->currentrow=0;
1708 function output_headers($headers) {
1709 $colnum = 0;
1710 foreach ($headers as $item) {
1711 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatheaders);
1712 $colnum++;
1714 $this->currentrow++;
1717 function add_data($row) {
1718 $colnum = 0;
1719 foreach ($row as $item) {
1720 $this->worksheet->write($this->currentrow,$colnum,$item,$this->formatnormal);
1721 $colnum++;
1723 $this->currentrow++;
1724 return true;
1727 function add_seperator() {
1728 $this->currentrow++;
1729 return true;
1732 function finish_table() {
1735 function finish_document() {
1736 $this->workbook->close();
1737 exit;
1743 * @package moodlecore
1744 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1745 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1747 class table_excel_export_format extends table_spreadsheet_export_format_parent {
1748 var $fileextension = 'xls';
1750 function define_workbook() {
1751 global $CFG;
1752 require_once("$CFG->libdir/excellib.class.php");
1753 // Creating a workbook
1754 $this->workbook = new MoodleExcelWorkbook("-");
1761 * @package moodlecore
1762 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1765 class table_ods_export_format extends table_spreadsheet_export_format_parent {
1766 var $fileextension = 'ods';
1767 function define_workbook() {
1768 global $CFG;
1769 require_once("$CFG->libdir/odslib.class.php");
1770 // Creating a workbook
1771 $this->workbook = new MoodleODSWorkbook("-");
1777 * @package moodlecore
1778 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1781 class table_text_export_format_parent extends table_default_export_format_parent {
1782 protected $seperator = "tab";
1783 protected $mimetype = 'text/tab-separated-values';
1784 protected $ext = '.txt';
1785 protected $myexporter;
1787 public function __construct() {
1788 $this->myexporter = new csv_export_writer($this->seperator, '"', $this->mimetype);
1791 public function start_document($filename) {
1792 $this->filename = $filename;
1793 $this->documentstarted = true;
1794 $this->myexporter->set_filename($filename, $this->ext);
1797 public function start_table($sheettitle) {
1798 //nothing to do here
1801 public function output_headers($headers) {
1802 $this->myexporter->add_data($headers);
1805 public function add_data($row) {
1806 $this->myexporter->add_data($row);
1807 return true;
1810 public function finish_table() {
1811 //nothing to do here
1814 public function finish_document() {
1815 $this->myexporter->download_file();
1816 exit;
1820 * Format a row of data.
1821 * @param array $data
1823 protected function format_row($data) {
1824 $escapeddata = array();
1825 foreach ($data as $value) {
1826 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1828 return implode($this->seperator, $escapeddata) . "\n";
1834 * @package moodlecore
1835 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1838 class table_tsv_export_format extends table_text_export_format_parent {
1839 protected $seperator = "tab";
1840 protected $mimetype = 'text/tab-separated-values';
1841 protected $ext = '.txt';
1844 require_once($CFG->libdir . '/csvlib.class.php');
1846 * @package moodlecore
1847 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1850 class table_csv_export_format extends table_text_export_format_parent {
1851 protected $seperator = "comma";
1852 protected $mimetype = 'text/csv';
1853 protected $ext = '.csv';
1857 * @package moodlecore
1858 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1859 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1861 class table_xhtml_export_format extends table_default_export_format_parent {
1862 function start_document($filename) {
1863 header("Content-Type: application/download\n");
1864 header("Content-Disposition: attachment; filename=\"$filename.html\"");
1865 header("Expires: 0");
1866 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1867 header("Pragma: public");
1868 //html headers
1869 echo <<<EOF
1870 <?xml version="1.0" encoding="UTF-8"?>
1871 <!DOCTYPE html
1872 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1873 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1875 <html xmlns="http://www.w3.org/1999/xhtml"
1876 xml:lang="en" lang="en">
1877 <head>
1878 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
1879 <style type="text/css">/*<![CDATA[*/
1881 .flexible th {
1882 white-space:normal;
1884 th.header, td.header, div.header {
1885 border-color:#DDDDDD;
1886 background-color:lightGrey;
1888 .flexible th {
1889 white-space:nowrap;
1891 th {
1892 font-weight:bold;
1895 .generaltable {
1896 border-style:solid;
1898 .generalbox {
1899 border-style:solid;
1901 body, table, td, th {
1902 font-family:Arial,Verdana,Helvetica,sans-serif;
1903 font-size:100%;
1905 td {
1906 border-style:solid;
1907 border-width:1pt;
1909 table {
1910 border-collapse:collapse;
1911 border-spacing:0pt;
1912 width:80%;
1913 margin:auto;
1916 h1, h2 {
1917 text-align:center;
1919 .bold {
1920 font-weight:bold;
1922 .mdl-align {
1923 text-align:center;
1925 /*]]>*/</style>
1926 <title>$filename</title>
1927 </head>
1928 <body>
1929 EOF;
1930 $this->documentstarted = true;
1933 function start_table($sheettitle) {
1934 $this->table->sortable(false);
1935 $this->table->collapsible(false);
1936 echo "<h2>{$sheettitle}</h2>";
1937 $this->table->start_html();
1940 function output_headers($headers) {
1941 $this->table->print_headers();
1942 echo html_writer::start_tag('tbody');
1945 function add_data($row) {
1946 $this->table->print_row($row);
1947 return true;
1950 function add_seperator() {
1951 $this->table->print_row(NULL);
1952 return true;
1955 function finish_table() {
1956 $this->table->finish_html();
1959 function finish_document() {
1960 echo "</body>\n</html>";
1961 exit;
1964 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1965 if (is_null($options)) {
1966 $options = new stdClass;
1968 //some sensible defaults
1969 if (!isset($options->para)) {
1970 $options->para = false;
1972 if (!isset($options->newlines)) {
1973 $options->newlines = false;
1975 if (!isset($options->smiley)) {
1976 $options->smiley = false;
1978 if (!isset($options->filter)) {
1979 $options->filter = false;
1981 return format_text($text, $format, $options);