MDL-26425 tablelib change print_initials_bar to remove duplication, and to use html_w...
[moodle.git] / lib / tablelib.php
CommitLineData
72fb21b6 1<?php
2
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.
14//
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/>.
17
18/**
78bfb562
PS
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
72fb21b6 23 */
24
9683db71 25
78bfb562
PS
26defined('MOODLE_INTERNAL') || die();
27
4b7079c1
TH
28/**#@+
29 * These constants relate to the table's handling of URL parameters.
30 */
e2ba85e9 31define('TABLE_VAR_SORT', 1);
32define('TABLE_VAR_HIDE', 2);
33define('TABLE_VAR_SHOW', 3);
34define('TABLE_VAR_IFIRST', 4);
35define('TABLE_VAR_ILAST', 5);
36define('TABLE_VAR_PAGE', 6);
4b7079c1 37/**#@-*/
e2ba85e9 38
4b7079c1
TH
39/**#@+
40 * Constants that indicate whether the paging bar for the table
41 * appears above or below the table.
42 */
43define('TABLE_P_TOP', 1);
44define('TABLE_P_BOTTOM', 2);
45/**#@-*/
20e1f1c0 46
9683db71 47
72fb21b6 48/**
49 * @package moodlecore
50 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
51 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 */
7270d81f 53class flexible_table {
54
55 var $uniqueid = NULL;
56 var $attributes = array();
57 var $headers = array();
58 var $columns = array();
59 var $column_style = array();
554906f6 60 var $column_class = array();
7270d81f 61 var $column_suppress = array();
353f3f20 62 var $column_nosort = array('userpic');
7270d81f 63 var $setup = false;
64 var $sess = NULL;
65 var $baseurl = NULL;
e2ba85e9 66 var $request = array();
7270d81f 67
68 var $is_collapsible = false;
69 var $is_sortable = false;
70 var $use_pages = false;
71 var $use_initials = false;
72
73e4f589 73 var $maxsortkeys = 2;
74 var $pagesize = 30;
75 var $currpage = 0;
76 var $totalrows = 0;
a5a3f48a 77 var $sort_default_column = NULL;
78 var $sort_default_order = SORT_ASC;
9cf4a18b 79
20e1f1c0 80 /**
81 * Array of positions in which to display download controls.
82 */
83 var $showdownloadbuttonsat= array(TABLE_P_TOP);
84
1f9ca535 85 /**
86 * @var string Key of field returned by db query that is the id field of the
87 * user table or equivalent.
88 */
89 public $useridfield = 'id';
90
20e1f1c0 91 /**
92 * @var string which download plugin to use. Default '' means none - print
93 * html table with paging. Property set by is_downloading which typically
94 * passes in cleaned data from $
95 */
96 var $download = '';
9cf4a18b 97
20e1f1c0 98 /**
99 * @var boolean whether data is downloadable from table. Determines whether
100 * to display download buttons. Set by method downloadable().
101 */
102 var $downloadable = false;
9cf4a18b 103
20e1f1c0 104 /**
105 * @var string which download plugin to use. Default '' means none - print
106 * html table with paging.
107 */
108 var $defaultdownloadformat = 'csv';
9cf4a18b 109
20e1f1c0 110 /**
111 * @var boolean Has start output been called yet?
112 */
113 var $started_output = false;
9cf4a18b 114
20e1f1c0 115 var $exportclass = null;
9cf4a18b 116
561d406b 117 /**
118 * Constructor
119 * @param int $uniqueid
120 * @todo Document properly
121 */
a49c17b4 122 function __construct($uniqueid) {
7270d81f 123 $this->uniqueid = $uniqueid;
e2ba85e9 124 $this->request = array(
125 TABLE_VAR_SORT => 'tsort',
126 TABLE_VAR_HIDE => 'thide',
127 TABLE_VAR_SHOW => 'tshow',
128 TABLE_VAR_IFIRST => 'tifirst',
129 TABLE_VAR_ILAST => 'tilast',
130 TABLE_VAR_PAGE => 'page'
131 );
7270d81f 132 }
20e1f1c0 133
a49c17b4
TH
134 /**
135 * Backwards-compatible constructor, so that legacy code subclassing
136 * flexible_table does not break.
137 * @deprecated since Moodle 2.0. Will be removed in Moodle 2.1.
138 */
139 function flexible_table($uniqueid) {
140 debugging('Please update your code to user PHP5-style parent::__construct(...), ' .
141 'not parent::flexible_table(...).');
142 $this->__construct($uniqueid);
143 }
144
20e1f1c0 145 /**
146 * Call this to pass the download type. Use :
147 * $download = optional_param('download', '', PARAM_ALPHA);
148 * To get the download type. We assume that if you call this function with
149 * params that this table's data is downloadable, so we call is_downloadable
150 * for you (even if the param is '', which means no download this time.
151 * Also you can call this method with no params to get the current set
152 * download type.
153 * @param string $download download type. One of csv, tsv, xhtml, ods, etc
154 * @param string $filename filename for downloads without file extension.
155 * @param string $sheettitle title for downloaded data.
156 * @return string download type. One of csv, tsv, xhtml, ods, etc
157 */
9683db71
TH
158 function is_downloading($download = null, $filename='', $sheettitle='') {
159 if ($download!==null) {
20e1f1c0 160 $this->sheettitle = $sheettitle;
161 $this->is_downloadable(true);
162 $this->download = $download;
43ec99aa 163 $this->filename = clean_filename($filename);
164 $this->export_class_instance();
20e1f1c0 165 }
166 return $this->download;
167 }
117bd748 168
9683db71
TH
169 function export_class_instance(&$exportclass=null) {
170 if (!is_null($exportclass)) {
869309b8 171 $this->started_output = true;
172 $this->exportclass =& $exportclass;
173 $this->exportclass->table =& $this;
9683db71 174 } elseif (is_null($this->exportclass) && !empty($this->download)) {
43ec99aa 175 $classname = 'table_'.$this->download.'_export_format';
176 $this->exportclass = new $classname($this);
9683db71 177 if (!$this->exportclass->document_started()) {
43ec99aa 178 $this->exportclass->start_document($this->filename);
179 }
180 }
181 return $this->exportclass;
182 }
117bd748 183
20e1f1c0 184 /**
185 * Probably don't need to call this directly. Calling is_downloading with a
186 * param automatically sets table as downloadable.
9cf4a18b 187 *
20e1f1c0 188 * @param boolean $downloadable optional param to set whether data from
189 * table is downloadable. If ommitted this function can be used to get
190 * current state of table.
191 * @return boolean whether table data is set to be downloadable.
192 */
9683db71
TH
193 function is_downloadable($downloadable = null) {
194 if ($downloadable !== null) {
20e1f1c0 195 $this->downloadable = $downloadable;
196 }
197 return $this->downloadable;
198 }
9cf4a18b 199
20e1f1c0 200 /**
201 * Where to show download buttons.
202 * @param array $showat array of postions in which to show download buttons.
203 * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
204 */
9683db71 205 function show_download_buttons_at($showat) {
20e1f1c0 206 $this->showdownloadbuttonsat = $showat;
207 }
9cf4a18b 208
561d406b 209 /**
9cf4a18b 210 * Sets the is_sortable variable to the given boolean, sort_default_column to
561d406b 211 * the given string, and the sort_default_order to the given integer.
212 * @param bool $bool
213 * @param string $defaultcolumn
214 * @param int $defaultorder
215 * @return void
216 */
a5a3f48a 217 function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
7270d81f 218 $this->is_sortable = $bool;
a5a3f48a 219 $this->sort_default_column = $defaultcolumn;
220 $this->sort_default_order = $defaultorder;
7270d81f 221 }
222
353f3f20 223 /**
224 * Do not sort using this column
225 * @param string column name
226 */
227 function no_sorting($column) {
228 $this->column_nosort[] = $column;
229 }
230
231 /**
232 * Is the column sortable?
233 * @param string column name, null means table
234 * @return bool
235 */
9683db71 236 function is_sortable($column = null) {
353f3f20 237 if (empty($column)) {
238 return $this->is_sortable;
239 }
240 if (!$this->is_sortable) {
241 return false;
242 }
243 return !in_array($column, $this->column_nosort);
244 }
9683db71 245
561d406b 246 /**
247 * Sets the is_collapsible variable to the given boolean.
248 * @param bool $bool
249 * @return void
250 */
7270d81f 251 function collapsible($bool) {
252 $this->is_collapsible = $bool;
253 }
254
561d406b 255 /**
256 * Sets the use_pages variable to the given boolean.
257 * @param bool $bool
258 * @return void
259 */
7270d81f 260 function pageable($bool) {
261 $this->use_pages = $bool;
262 }
263
561d406b 264 /**
265 * Sets the use_initials variable to the given boolean.
266 * @param bool $bool
267 * @return void
268 */
7270d81f 269 function initialbars($bool) {
270 $this->use_initials = $bool;
271 }
272
561d406b 273 /**
274 * Sets the pagesize variable to the given integer, the totalrows variable
275 * to the given integer, and the use_pages variable to true.
276 * @param int $perpage
277 * @param int $total
278 * @return void
279 */
7270d81f 280 function pagesize($perpage, $total) {
281 $this->pagesize = $perpage;
282 $this->totalrows = $total;
283 $this->use_pages = true;
284 }
285
561d406b 286 /**
287 * Assigns each given variable in the array to the corresponding index
288 * in the request class variable.
289 * @param array $variables
290 * @return void
291 */
e2ba85e9 292 function set_control_variables($variables) {
9683db71
TH
293 foreach ($variables as $what => $variable) {
294 if (isset($this->request[$what])) {
e2ba85e9 295 $this->request[$what] = $variable;
296 }
297 }
298 }
299
561d406b 300 /**
301 * Gives the given $value to the $attribute index of $this->attributes.
302 * @param string $attribute
303 * @param mixed $value
304 * @return void
305 */
7270d81f 306 function set_attribute($attribute, $value) {
307 $this->attributes[$attribute] = $value;
308 }
309
561d406b 310 /**
9cf4a18b 311 * What this method does is set the column so that if the same data appears in
901e25d4 312 * consecutive rows, then it is not repeated.
9cf4a18b 313 *
901e25d4 314 * For example, in the quiz overview report, the fullname column is set to be suppressed, so
315 * that when one student has made multiple attempts, their name is only printed in the row
316 * for their first attempt.
317 * @param integer $column the index of a column.
561d406b 318 */
7270d81f 319 function column_suppress($column) {
9683db71 320 if (isset($this->column_suppress[$column])) {
7270d81f 321 $this->column_suppress[$column] = true;
322 }
323 }
324
561d406b 325 /**
326 * Sets the given $column index to the given $classname in $this->column_class.
327 * @param integer $column
328 * @param string $classname
329 * @return void
330 */
554906f6 331 function column_class($column, $classname) {
9683db71 332 if (isset($this->column_class[$column])) {
554906f6 333 $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
334 }
335 }
336
561d406b 337 /**
338 * Sets the given $column index and $property index to the given $value in $this->column_style.
339 * @param integer $column
340 * @param string $property
341 * @param mixed $value
342 * @return void
343 */
7270d81f 344 function column_style($column, $property, $value) {
9683db71 345 if (isset($this->column_style[$column])) {
7270d81f 346 $this->column_style[$column][$property] = $value;
347 }
348 }
349
561d406b 350 /**
20e1f1c0 351 * Sets all columns' $propertys to the given $value in $this->column_style.
561d406b 352 * @param integer $property
353 * @param string $value
354 * @return void
355 */
7270d81f 356 function column_style_all($property, $value) {
9683db71 357 foreach (array_keys($this->columns) as $column) {
7270d81f 358 $this->column_style[$column][$property] = $value;
359 }
360 }
361
561d406b 362 /**
59f392b3
TH
363 * Sets $this->baseurl.
364 * @param moodle_url|string $url the url with params needed to call up this page
561d406b 365 */
7270d81f 366 function define_baseurl($url) {
59f392b3 367 $this->baseurl = new moodle_url($url);
7270d81f 368 }
369
561d406b 370 /**
20e1f1c0 371 * @param array $columns an array of identifying names for columns. If
372 * columns are sorted then column names must correspond to a field in sql.
561d406b 373 */
7270d81f 374 function define_columns($columns) {
375 $this->columns = array();
376 $this->column_style = array();
554906f6 377 $this->column_class = array();
7270d81f 378 $colnum = 0;
379
9683db71 380 foreach ($columns as $column) {
7270d81f 381 $this->columns[$column] = $colnum++;
382 $this->column_style[$column] = array();
554906f6 383 $this->column_class[$column] = '';
7270d81f 384 $this->column_suppress[$column] = false;
385 }
386 }
387
561d406b 388 /**
20e1f1c0 389 * @param array $headers numerical keyed array of displayed string titles
390 * for each column.
561d406b 391 */
7270d81f 392 function define_headers($headers) {
393 $this->headers = $headers;
394 }
9cf4a18b 395
561d406b 396 /**
20e1f1c0 397 * Must be called after table is defined. Use methods above first. Cannot
398 * use functions below till after calling this method.
561d406b 399 * @return type?
400 */
7270d81f 401 function setup() {
402 global $SESSION, $CFG;
403
9683db71 404 if (empty($this->columns) || empty($this->uniqueid)) {
7270d81f 405 return false;
406 }
1e42af27 407
0ce8ba58 408 if (!isset($SESSION->flextable)) {
409 $SESSION->flextable = array();
7270d81f 410 }
1e42af27 411
9683db71 412 if (!isset($SESSION->flextable[$this->uniqueid])) {
0ce8ba58 413 $SESSION->flextable[$this->uniqueid] = new stdClass;
414 $SESSION->flextable[$this->uniqueid]->uniqueid = $this->uniqueid;
415 $SESSION->flextable[$this->uniqueid]->collapse = array();
416 $SESSION->flextable[$this->uniqueid]->sortby = array();
417 $SESSION->flextable[$this->uniqueid]->i_first = '';
418 $SESSION->flextable[$this->uniqueid]->i_last = '';
419 }
420
421 $this->sess = &$SESSION->flextable[$this->uniqueid];
7270d81f 422
59f392b3
TH
423 if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
424 isset($this->columns[$showcol])) {
425 $this->sess->collapse[$showcol] = false;
426
427 } else if (($hidecol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
428 isset($this->columns[$hidecol])) {
429 $this->sess->collapse[$hidecol] = true;
430 if (array_key_exists($hidecol, $this->sess->sortby)) {
431 unset($this->sess->sortby[$hidecol]);
7270d81f 432 }
433 }
1e42af27 434
7270d81f 435 // Now, update the column attributes for collapsed columns
9683db71
TH
436 foreach (array_keys($this->columns) as $column) {
437 if (!empty($this->sess->collapse[$column])) {
7270d81f 438 $this->column_style[$column]['width'] = '10px';
439 }
440 }
441
59f392b3
TH
442 if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
443 $this->is_sortable($sortcol) && empty($this->sess->collapse[$sortcol]) &&
444 (isset($this->columns[$sortcol]) || in_array($sortcol, array('firstname', 'lastname')) && isset($this->columns['fullname']))) {
445
446 if (array_key_exists($sortcol, $this->sess->sortby)) {
447 // This key already exists somewhere. Change its sortorder and bring it to the top.
448 $sortorder = $this->sess->sortby[$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
449 unset($this->sess->sortby[$sortcol]);
450 $this->sess->sortby = array_merge(array($sortcol => $sortorder), $this->sess->sortby);
451 } else {
452 // Key doesn't exist, so just add it to the beginning of the array, ascending order
453 $this->sess->sortby = array_merge(array($sortcol => SORT_ASC), $this->sess->sortby);
7270d81f 454 }
59f392b3
TH
455
456 // Finally, make sure that no more than $this->maxsortkeys are present into the array
457 $this->sess->sortby = array_slice($this->sess->sortby, 0, $this->maxsortkeys);
7270d81f 458 }
459
a5a3f48a 460 // If we didn't sort just now, then use the default sort order if one is defined and the column exists
9683db71 461 if (empty($this->sess->sortby) && !empty($this->sort_default_column)) {
a5a3f48a 462 $this->sess->sortby = array ($this->sort_default_column => ($this->sort_default_order == SORT_DESC ? SORT_DESC : SORT_ASC));
463 }
464
59f392b3
TH
465 $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
466 if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
467 $this->sess->i_last = $ilast;
7270d81f 468 }
469
59f392b3
TH
470 $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
471 if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
472 $this->sess->i_first = $ifirst;
7270d81f 473 }
474
9683db71 475 if (empty($this->baseurl)) {
59f392b3
TH
476 debugging('You should set baseurl when using flexible_table.');
477 global $PAGE;
478 $this->baseurl = $PAGE->url;
7270d81f 479 }
480
92ebcabe 481 $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
7270d81f 482 $this->setup = true;
d1b523b7 483
59f392b3 484 // Always introduce the "flexible" class for the table if not specified
d1b523b7 485 if (empty($this->attributes)) {
486 $this->attributes['class'] = 'flexible';
d1b523b7 487 } else if (!isset($this->attributes['class'])) {
488 $this->attributes['class'] = 'flexible';
d1b523b7 489 } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
490 $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
491 }
9baf2670
TH
492 }
493
494 /**
495 * Get the order by clause from the session, for the table with id $uniqueid.
496 * @param string $uniqueid the identifier for a table.
497 * @return SQL fragment that can be used in an ORDER BY clause.
498 */
499 public static function get_sort_for_table($uniqueid) {
500 global $SESSION;
9683db71 501 if (empty($SESSION->flextable[$uniqueid])) {
9baf2670
TH
502 return '';
503 }
d1b523b7 504
9baf2670
TH
505 $sess = &$SESSION->flextable[$uniqueid];
506 if (empty($sess->sortby)) {
507 return '';
508 }
509
510 return self::construct_order_by($sess->sortby);
7270d81f 511 }
512
561d406b 513 /**
9baf2670
TH
514 * Prepare an an order by clause from the list of columns to be sorted.
515 * @param array $cols column name => SORT_ASC or SORT_DESC
516 * @return SQL fragment that can be used in an ORDER BY clause.
561d406b 517 */
9baf2670
TH
518 public static function construct_order_by($cols) {
519 $bits = array();
520
9683db71 521 foreach ($cols as $column => $order) {
9baf2670
TH
522 if ($order == SORT_ASC) {
523 $bits[] = $column . ' ASC';
524 } else {
525 $bits[] = $column . ' DESC';
9013e4ad 526 }
9013e4ad 527 }
9baf2670
TH
528
529 return implode(', ', $bits);
530 }
531
532 /**
533 * @return SQL fragment that can be used in an ORDER BY clause.
534 */
535 public function get_sql_sort() {
536 return self::construct_order_by($this->get_sort_columns());
537 }
538
539 /**
540 * Get the columns to sort by, in the form required by {@link construct_order_by()}.
541 * @return array column name => SORT_... constant.
542 */
543 public function get_sort_columns() {
544 if (!$this->setup) {
545 throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
7270d81f 546 }
9013e4ad 547
9baf2670
TH
548 if (empty($this->sess->sortby)) {
549 return array();
7270d81f 550 }
9baf2670 551
e81eed54
TH
552 foreach ($this->sess->sortby as $column => $notused) {
553 if (isset($this->columns[$column])) {
554 continue; // This column is OK.
555 }
556 if (in_array($column, array('firstname', 'lastname')) &&
557 isset($this->columns['fullname'])) {
558 continue; // This column is OK.
559 }
560 // This column is not OK.
561 unset($this->sess->sortby[$column]);
562 }
563
9baf2670 564 return $this->sess->sortby;
7270d81f 565 }
566
561d406b 567 /**
20e1f1c0 568 * @return integer the offset for LIMIT clause of SQL
561d406b 569 */
7270d81f 570 function get_page_start() {
9683db71 571 if (!$this->use_pages) {
7270d81f 572 return '';
573 }
574 return $this->currpage * $this->pagesize;
575 }
576
561d406b 577 /**
20e1f1c0 578 * @return integer the pagesize for LIMIT clause of SQL
561d406b 579 */
7270d81f 580 function get_page_size() {
9683db71 581 if (!$this->use_pages) {
7270d81f 582 return '';
583 }
584 return $this->pagesize;
585 }
586
561d406b 587 /**
e81eed54 588 * @return string sql to add to where statement.
561d406b 589 */
7270d81f 590 function get_sql_where() {
7e60297f 591 global $DB;
7270d81f 592
20a79b43
PS
593 $conditions = array();
594 $params = array();
595
ee70439a
PS
596 if (isset($this->columns['fullname'])) {
597 static $i = 0;
598 $i++;
599
600 if (!empty($this->sess->i_first)) {
601 $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
602 $params['ifirstc'.$i] = $this->sess->i_first.'%';
603 }
604 if (!empty($this->sess->i_last)) {
605 $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
606 $params['ilastc'.$i] = $this->sess->i_last.'%';
607 }
7270d81f 608 }
609
20a79b43 610 return array(implode(" AND ", $conditions), $params);
7270d81f 611 }
612
561d406b 613 /**
9cf4a18b 614 * Add a row of data to the table. This function takes an array with
615 * column names as keys.
20e1f1c0 616 * It ignores any elements with keys that are not defined as columns. It
617 * puts in empty strings into the row when there is no element in the passed
618 * array corresponding to a column in the table. It puts the row elements in
619 * the proper order.
620 * @param $rowwithkeys array
c7ecf78e 621 * @param string $classname CSS class name to add to this row's tr tag.
20e1f1c0 622 */
9683db71 623 function add_data_keyed($rowwithkeys, $classname = '') {
c7ecf78e 624 $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
20e1f1c0 625 }
9cf4a18b 626
20e1f1c0 627 /**
628 * Add a seperator line to table.
629 */
630 function add_separator() {
9683db71 631 if (!$this->setup) {
20e1f1c0 632 return false;
633 }
634 $this->add_data(NULL);
635 }
9cf4a18b 636
20e1f1c0 637 /**
638 * This method actually directly echoes the row passed to it now or adds it
639 * to the download. If this is the first row and start_output has not
640 * already been called this method also calls start_output to open the table
641 * or send headers for the downloaded.
642 * Can be used as before. print_html now calls finish_html to close table.
9cf4a18b 643 *
20e1f1c0 644 * @param array $row a numerically keyed row of data to add to the table.
c7ecf78e 645 * @param string $classname CSS class name to add to this row's tr tag.
20e1f1c0 646 * @return boolean success.
647 */
c7ecf78e 648 function add_data($row, $classname = '') {
9683db71 649 if (!$this->setup) {
20e1f1c0 650 return false;
651 }
9683db71 652 if (!$this->started_output) {
20e1f1c0 653 $this->start_output();
654 }
9683db71
TH
655 if ($this->exportclass!==null) {
656 if ($row === null) {
20e1f1c0 657 $this->exportclass->add_seperator();
658 } else {
659 $this->exportclass->add_data($row);
660 }
661 } else {
c7ecf78e 662 $this->print_row($row, $classname);
20e1f1c0 663 }
664 return true;
665 }
666
20e1f1c0 667 /**
668 * You should call this to finish outputting the table data after adding
669 * data to the table with add_data or add_data_keyed.
9cf4a18b 670 *
20e1f1c0 671 */
9683db71
TH
672 function finish_output($closeexportclassdoc = true) {
673 if ($this->exportclass!==null) {
43ec99aa 674 $this->exportclass->finish_table();
9683db71 675 if ($closeexportclassdoc) {
43ec99aa 676 $this->exportclass->finish_document();
677 }
9683db71 678 } else {
20e1f1c0 679 $this->finish_html();
680 }
681 }
9cf4a18b 682
20e1f1c0 683 /**
684 * Hook that can be overridden in child classes to wrap a table in a form
685 * for example. Called only when there is data to display and not
686 * downloading.
687 */
9683db71 688 function wrap_html_start() {
20e1f1c0 689 }
690
691 /**
692 * Hook that can be overridden in child classes to wrap a table in a form
693 * for example. Called only when there is data to display and not
694 * downloading.
695 */
9683db71 696 function wrap_html_finish() {
20e1f1c0 697 }
9cf4a18b 698
1f9ca535 699 /**
700 *
701 * @param array $row row of data from db used to make one row of the table.
702 * @return array one row for the table, added using add_data_keyed method.
703 */
9683db71 704 function format_row($row) {
1f9ca535 705 $formattedrow = array();
9683db71 706 foreach (array_keys($this->columns) as $column) {
1f9ca535 707 $colmethodname = 'col_'.$column;
9683db71 708 if (method_exists($this, $colmethodname)) {
1f9ca535 709 $formattedcolumn = $this->$colmethodname($row);
710 } else {
711 $formattedcolumn = $this->other_cols($column, $row);
9683db71 712 if ($formattedcolumn===NULL) {
1f9ca535 713 $formattedcolumn = $row->$column;
714 }
715 }
716 $formattedrow[$column] = $formattedcolumn;
717 }
718 return $formattedrow;
719 }
720
721 /**
722 * Fullname is treated as a special columname in tablelib and should always
723 * be treated the same as the fullname of a user.
724 * @uses $this->useridfield if the userid field is not expected to be id
725 * then you need to override $this->useridfield to point at the correct
726 * field for the user id.
727 *
728 */
9683db71 729 function col_fullname($row) {
1f9ca535 730 global $COURSE, $CFG;
1f9ca535 731
9683db71 732 if (!$this->download) {
abf72969
TH
733 $profileurl = new moodle_url('/user/profile.php', array('id' => $row->{$this->useridfield}));
734 if ($COURSE->id != SITEID) {
735 $profileurl->param('course', $COURSE->id);
03d9401e 736 }
abf72969
TH
737 return html_writer::link($profileurl, fullname($row));
738
1f9ca535 739 } else {
740 return fullname($row);
741 }
742 }
743
744 /**
745 * You can override this method in a child class. See the description of
746 * build_table which calls this method.
747 */
9683db71 748 function other_cols($column, $row) {
1f9ca535 749 return NULL;
750 }
751
ef27e742 752 /**
753 * Used from col_* functions when text is to be displayed. Does the
754 * right thing - either converts text to html or strips any html tags
755 * depending on if we are downloading and what is the download type. Params
756 * are the same as format_text function in weblib.php but some default
757 * options are changed.
758 */
9683db71
TH
759 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
760 if (!$this->is_downloading()) {
761 if (is_null($options)) {
ef27e742 762 $options = new stdClass;
763 }
764 //some sensible defaults
9683db71 765 if (!isset($options->para)) {
ef27e742 766 $options->para = false;
767 }
9683db71 768 if (!isset($options->newlines)) {
ef27e742 769 $options->newlines = false;
770 }
771 if (!isset($options->smiley)) {
772 $options->smiley = false;
773 }
774 if (!isset($options->filter)) {
775 $options->filter = false;
776 }
777 return format_text($text, $format, $options);
778 } else {
779 $eci =& $this->export_class_instance();
780 return $eci->format_text($text, $format, $options, $courseid);
781 }
782 }
20e1f1c0 783 /**
784 * This method is deprecated although the old api is still supported.
785 * @deprecated 1.9.2 - Jun 2, 2008
786 */
787 function print_html() {
9683db71 788 if (!$this->setup) {
20e1f1c0 789 return false;
790 }
791 $this->finish_html();
792 }
793
794 /**
795 * This function is not part of the public api.
796 * @return string initial of first name we are currently filtering by
561d406b 797 */
91bb59f4 798 function get_initial_first() {
9683db71 799 if (!$this->use_initials) {
91bb59f4 800 return NULL;
801 }
802
803 return $this->sess->i_first;
804 }
805
561d406b 806 /**
20e1f1c0 807 * This function is not part of the public api.
808 * @return string initial of last name we are currently filtering by
561d406b 809 */
91bb59f4 810 function get_initial_last() {
9683db71 811 if (!$this->use_initials) {
91bb59f4 812 return NULL;
813 }
814
815 return $this->sess->i_last;
816 }
9cf4a18b 817
6f0d3480
TH
818 protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
819 echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
820 $title . ' : ';
821 if ($current) {
822 echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
823 } else {
824 echo html_writer::tag('strong', get_string('all'));
825 }
826
827 foreach ($alpha as $letter) {
828 if ($letter === $current) {
829 echo html_writer::tag('strong', $letter);
830 } else {
831 echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
832 }
833 }
834
835 echo html_writer::end_tag('div');
836 }
837
561d406b 838 /**
20e1f1c0 839 * This function is not part of the public api.
561d406b 840 */
9683db71 841 function print_initials_bar() {
6f0d3480 842 if ((!empty($this->sess->i_last) || !empty($this->sess->i_first) ||$this->use_initials)
db16ac50 843 && isset($this->columns['fullname'])) {
9cf4a18b 844
61bb07c2 845 $alpha = explode(',', get_string('alphabet', 'langconfig'));
9cf4a18b 846
7270d81f 847 // Bar of first initials
9683db71 848 if (!empty($this->sess->i_first)) {
6f0d3480 849 $ifirst = $this->sess->i_first;
7270d81f 850 } else {
6f0d3480 851 $ifirst = '';
7270d81f 852 }
6f0d3480
TH
853 $this->print_one_initials_bar($alpha, $ifirst, 'firstinitial',
854 get_string('firstname'), $this->request[TABLE_VAR_IFIRST]);
9cf4a18b 855
7270d81f 856 // Bar of last initials
9683db71 857 if (!empty($this->sess->i_last)) {
6f0d3480 858 $ilast = $this->sess->i_last;
7270d81f 859 } else {
6f0d3480 860 $ilast = '';
7270d81f 861 }
6f0d3480
TH
862 $this->print_one_initials_bar($alpha, $ilast, 'lastinitial',
863 get_string('lastname'), $this->request[TABLE_VAR_ILAST]);
20e1f1c0 864 }
865 }
7270d81f 866
20e1f1c0 867 /**
868 * This function is not part of the public api.
869 */
9683db71 870 function print_nothing_to_display() {
3c159385 871 global $OUTPUT;
db16ac50 872 $this->print_initials_bar();
7270d81f 873
3c159385 874 echo $OUTPUT->heading(get_string('nothingtodisplay'));
20e1f1c0 875 }
7270d81f 876
20e1f1c0 877 /**
878 * This function is not part of the public api.
879 */
9683db71
TH
880 function get_row_from_keyed($rowwithkeys) {
881 if (is_object($rowwithkeys)) {
20e1f1c0 882 $rowwithkeys = (array)$rowwithkeys;
7270d81f 883 }
f36a3308 884 $row = array();
9683db71
TH
885 foreach (array_keys($this->columns) as $column) {
886 if (isset($rowwithkeys[$column])) {
20e1f1c0 887 $row [] = $rowwithkeys[$column];
888 } else {
889 $row[] ='';
890 }
7270d81f 891 }
20e1f1c0 892 return $row;
893 }
894 /**
895 * This function is not part of the public api.
896 */
9683db71 897 function get_download_menu() {
20e1f1c0 898 $allclasses= get_declared_classes();
899 $exportclasses = array();
9683db71 900 foreach ($allclasses as $class) {
20e1f1c0 901 $matches = array();
9683db71 902 if (preg_match('/^table\_([a-z]+)\_export\_format$/', $class, $matches)) {
20e1f1c0 903 $type = $matches[1];
904 $exportclasses[$type]= get_string("download$type", 'table');
905 }
906 }
907 return $exportclasses;
908 }
9cf4a18b 909
20e1f1c0 910 /**
911 * This function is not part of the public api.
912 */
9683db71 913 function download_buttons() {
9683db71 914 if ($this->is_downloadable() && !$this->is_downloading()) {
20e1f1c0 915 $downloadoptions = $this->get_download_menu();
916 $html = '<form action="'. $this->baseurl .'" method="post">';
917 $html .= '<div class="mdl-align">';
918 $html .= '<input type="submit" value="'.get_string('downloadas', 'table').'"/>';
d776d59e 919 $html .= html_writer::select($downloadoptions, 'download', $this->defaultdownloadformat, false);
20e1f1c0 920 $html .= '</div></form>';
921
922 return $html;
923 } else {
924 return '';
925 }
926 }
927 /**
928 * This function is not part of the public api.
929 * You don't normally need to call this. It is called automatically when
930 * needed when you start adding data to the table.
9cf4a18b 931 *
20e1f1c0 932 */
9683db71 933 function start_output() {
20e1f1c0 934 $this->started_output = true;
9683db71 935 if ($this->exportclass!==null) {
43ec99aa 936 $this->exportclass->start_table($this->sheettitle);
20e1f1c0 937 $this->exportclass->output_headers($this->headers);
938 } else {
939 $this->start_html();
940 $this->print_headers();
941 }
942 }
7270d81f 943
20e1f1c0 944 /**
945 * This function is not part of the public api.
946 */
c7ecf78e 947 function print_row($row, $classname = '') {
20e1f1c0 948 static $suppress_lastrow = NULL;
949 static $oddeven = 1;
c7ecf78e 950 $rowclasses = array('r' . $oddeven);
951 $oddeven = $oddeven ? 0 : 1;
952
953 if ($classname) {
954 $rowclasses[] = $classname;
955 }
956
957 echo '<tr class="' . implode(' ', $rowclasses) . '">';
7270d81f 958
20e1f1c0 959 // If we have a separator, print it
eba40bfe 960 if ($row === NULL) {
c7ecf78e 961 $colcount = count($this->columns);
20e1f1c0 962 echo '<td colspan="'.$colcount.'"><div class="tabledivider"></div></td>';
c7ecf78e 963 } else {
964 $colbyindex = array_flip($this->columns);
965 foreach ($row as $index => $data) {
20e1f1c0 966 $column = $colbyindex[$index];
967 echo '<td class="cell c'.$index.$this->column_class[$column].'"'.$this->make_styles_string($this->column_style[$column]).'>';
c7ecf78e 968 if (empty($this->sess->collapse[$column])) {
969 if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
20e1f1c0 970 echo '&nbsp;';
c7ecf78e 971 } else {
20e1f1c0 972 echo $data;
973 }
c7ecf78e 974 } else {
20e1f1c0 975 echo '&nbsp;';
976 }
977 echo '</td>';
978 }
979 }
c7ecf78e 980
20e1f1c0 981 echo '</tr>';
c7ecf78e 982
7270d81f 983 $suppress_enabled = array_sum($this->column_suppress);
c7ecf78e 984 if ($suppress_enabled) {
20e1f1c0 985 $suppress_lastrow = $row;
986 }
987 }
9683db71 988
20e1f1c0 989 /**
990 * This function is not part of the public api.
991 */
9683db71 992 function finish_html() {
25911860 993 global $OUTPUT;
20e1f1c0 994 if (!$this->started_output) {
995 //no data has been added to the table.
996 $this->print_nothing_to_display();
997 } else {
998 echo '</table>';
f4136193 999 echo html_writer::end_tag('div');
20e1f1c0 1000 $this->wrap_html_finish();
1001 // Paging bar
9683db71 1002 if (in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
20e1f1c0 1003 echo $this->download_buttons();
1004 }
9683db71 1005 if ($this->use_pages) {
929d7a83 1006 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
b28c784f 1007 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
929d7a83 1008 echo $OUTPUT->render($pagingbar);
20e1f1c0 1009 }
1010 }
9cf4a18b 1011 }
20e1f1c0 1012 /**
1013 * This function is not part of the public api.
1014 */
9683db71 1015 function print_headers() {
f2a1963c 1016 global $CFG, $OUTPUT;
7270d81f 1017
1018 echo '<tr>';
9683db71 1019 foreach ($this->columns as $column => $index) {
7270d81f 1020 $icon_hide = '';
1021 $icon_sort = '';
1022
9683db71
TH
1023 if ($this->is_collapsible) {
1024 if (!empty($this->sess->collapse[$column])) {
b2603953 1025 // some headers contain < br/> tags, do not include in title
b5d0cafc 1026 $icon_hide = ' <a href="'.$this->baseurl.$this->request[TABLE_VAR_SHOW].'='.$column.'"><img src="'.$OUTPUT->pix_url('t/switch_plus') . '" title="'.get_string('show').' '.strip_tags($this->headers[$index]).'" alt="'.get_string('show').'" /></a>';
9683db71 1027 } else if($this->headers[$index] !== NULL) {
b2603953 1028 // some headers contain < br/> tags, do not include in title
b5d0cafc 1029 $icon_hide = ' <a href="'.$this->baseurl.$this->request[TABLE_VAR_HIDE].'='.$column.'"><img src="'.$OUTPUT->pix_url('t/switch_minus') . '" title="'.get_string('hide').' '.strip_tags($this->headers[$index]).'" alt="'.get_string('hide').'" /></a>';
7270d81f 1030 }
1031 }
1032
73e4f589 1033 $primary_sort_column = '';
1034 $primary_sort_order = '';
9683db71 1035 if (reset($this->sess->sortby)) {
73e4f589 1036 $primary_sort_column = key($this->sess->sortby);
1037 $primary_sort_order = current($this->sess->sortby);
1038 }
1039
9683db71 1040 switch ($column) {
7270d81f 1041
1042 case 'fullname':
9683db71 1043 if ($this->is_sortable($column)) {
7270d81f 1044 $icon_sort_first = $icon_sort_last = '';
9683db71 1045 if ($primary_sort_column == 'firstname') {
49108746 1046 $lsortorder = get_string('asc');
9683db71 1047 if ($primary_sort_order == SORT_ASC) {
b5d0cafc 1048 $icon_sort_first = ' <img src="'.$OUTPUT->pix_url('t/down') . '" alt="'.get_string('asc').'" />';
49108746 1049 $fsortorder = get_string('asc');
9683db71 1050 } else {
b5d0cafc 1051 $icon_sort_first = ' <img src="'.$OUTPUT->pix_url('t/up') . '" alt="'.get_string('desc').'" />';
49108746 1052 $fsortorder = get_string('desc');
7270d81f 1053 }
9683db71 1054 } else if($primary_sort_column == 'lastname') {
49108746 1055 $fsortorder = get_string('asc');
9683db71 1056 if ($primary_sort_order == SORT_ASC) {
b5d0cafc 1057 $icon_sort_last = ' <img src="'.$OUTPUT->pix_url('t/down') . '" alt="'.get_string('asc').'" />';
49108746 1058 $lsortorder = get_string('asc');
9683db71 1059 } else {
b5d0cafc 1060 $icon_sort_last = ' <img src="'.$OUTPUT->pix_url('t/up') . '" alt="'.get_string('desc').'" />';
49108746 1061 $lsortorder = get_string('desc');
7270d81f 1062 }
49108746 1063 } else {
1064 $fsortorder = get_string('asc');
1065 $lsortorder = get_string('asc');
7270d81f 1066 }
78bfb562 1067
365a5941 1068 $override = new stdClass();
4eb95309
RW
1069 $override->firstname = 'firstname';
1070 $override->lastname = 'lastname';
1071 $fullnamelanguage = get_string('fullnamedisplay', '', $override);
1072
1073 if (($CFG->fullnamedisplay == 'firstname lastname') or
1074 ($CFG->fullnamedisplay == 'firstname') or
1075 ($CFG->fullnamedisplay == 'language' and $fullnamelanguage == 'firstname lastname' )) {
1076 $this->headers[$index] = '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT].'=firstname">'.get_string('firstname').get_accesshide(get_string('sortby').' '.get_string('firstname').' '.$fsortorder).'</a> '.$icon_sort_first.' / '.
1077 '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT].'=lastname">'.get_string('lastname').get_accesshide(get_string('sortby').' '.get_string('lastname').' '.$lsortorder).'</a> '.$icon_sort_last;
1078 } else {
1079 $this->headers[$index] = '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT].'=lastname">'.get_string('lastname').get_accesshide(get_string('sortby').' '.get_string('lastname').' '.$lsortorder).'</a> '.$icon_sort_last.' / '.
1080 '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT].'=firstname">'.get_string('firstname').get_accesshide(get_string('sortby').' '.get_string('firstname').' '.$fsortorder).'</a> '.$icon_sort_first;
78bfb562 1081 }
7270d81f 1082 }
1083 break;
1084
1d40c70b 1085 case 'userpic':
9cf4a18b 1086 // do nothing, do not display sortable links
1d40c70b 1087 break;
1088
7270d81f 1089 default:
9683db71
TH
1090 if ($this->is_sortable($column)) {
1091 if ($primary_sort_column == $column) {
1092 if ($primary_sort_order == SORT_ASC) {
b5d0cafc 1093 $icon_sort = ' <img src="'.$OUTPUT->pix_url('t/down') . '" alt="'.get_string('asc').'" />';
49108746 1094 $localsortorder = get_string('asc');
9683db71 1095 } else {
b5d0cafc 1096 $icon_sort = ' <img src="'.$OUTPUT->pix_url('t/up') . '" alt="'.get_string('desc').'" />';
49108746 1097 $localsortorder = get_string('desc');
7270d81f 1098 }
49108746 1099 } else {
9cf4a18b 1100 $localsortorder = get_string('asc');
7270d81f 1101 }
f79f2494 1102 $this->headers[$index] = '<a href="'.$this->baseurl.$this->request[TABLE_VAR_SORT].'='.$column.'">'.$this->headers[$index].get_accesshide(get_string('sortby').' '.$this->headers[$index].' '.$localsortorder).'</a>';
7270d81f 1103 }
1104 }
1e42af27 1105
9683db71 1106 if ($this->headers[$index] === NULL) {
8dc9a211 1107 echo '<th class="header c'.$index.$this->column_class[$column].'" scope="col">&nbsp;</th>';
9683db71 1108 } else if(!empty($this->sess->collapse[$column])) {
8dc9a211 1109 echo '<th class="header c'.$index.$this->column_class[$column].'" scope="col">'.$icon_hide.'</th>';
9683db71 1110 } else {
d9cb14b8 1111 // took out nowrap for accessibility, might need replacement
6e291bc6 1112 if (!is_array($this->column_style[$column])) {
1113 // $usestyles = array('white-space:nowrap');
1114 $usestyles = '';
82b9f43e 1115 } else {
6e291bc6 1116 // $usestyles = $this->column_style[$column]+array('white-space'=>'nowrap');
1117 $usestyles = $this->column_style[$column];
1118 }
82b9f43e 1119 echo '<th class="header c'.$index.$this->column_class[$column].'" '.$this->make_styles_string($usestyles).' scope="col">'.$this->headers[$index].$icon_sort.'<div class="commands">'.$icon_hide.'</div></th>';
7270d81f 1120 }
1121
1122 }
1123 echo '</tr>';
20e1f1c0 1124 }
9cf4a18b 1125
20e1f1c0 1126 /**
1127 * This function is not part of the public api.
1128 */
9683db71 1129 function start_html() {
b28c784f 1130 global $OUTPUT;
20e1f1c0 1131 // Do we need to print initial bars?
1132 $this->print_initials_bar();
7270d81f 1133
1e42af27 1134 // Paging bar
9683db71 1135 if ($this->use_pages) {
929d7a83 1136 $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
b28c784f 1137 $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
929d7a83 1138 echo $OUTPUT->render($pagingbar);
1e42af27 1139 }
9cf4a18b 1140
9683db71 1141 if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
20e1f1c0 1142 echo $this->download_buttons();
1143 }
9cf4a18b 1144
20e1f1c0 1145 $this->wrap_html_start();
1146 // Start of main data table
1147
367a75fa 1148 echo html_writer::start_tag('div', array('class'=>'no-overflow'));
20e1f1c0 1149 echo '<table'.$this->make_attributes_string($this->attributes).'>';
9cf4a18b 1150
7270d81f 1151 }
1152
561d406b 1153 /**
20e1f1c0 1154 * This function is not part of the public api.
561d406b 1155 * @todo Document
1156 * @return type?
1157 */
20e1f1c0 1158 function make_styles_string(&$styles) {
9683db71 1159 if (empty($styles)) {
20e1f1c0 1160 return '';
1161 }
1162
1163 $string = ' style="';
9683db71 1164 foreach ($styles as $property => $value) {
20e1f1c0 1165 $string .= $property.':'.$value.';';
7270d81f 1166 }
20e1f1c0 1167 $string .= '"';
1168 return $string;
7270d81f 1169 }
1170
561d406b 1171 /**
20e1f1c0 1172 * This function is not part of the public api.
561d406b 1173 * @todo Document
1174 * @return type?
1175 */
20e1f1c0 1176 function make_attributes_string(&$attributes) {
9683db71 1177 if (empty($attributes)) {
20e1f1c0 1178 return '';
1179 }
1180
1181 $string = ' ';
9683db71 1182 foreach ($attributes as $attr => $value) {
20e1f1c0 1183 $string .= ($attr.'="'.$value.'" ');
7270d81f 1184 }
20e1f1c0 1185
1186 return $string;
1187 }
1188}
1189
9683db71 1190
72fb21b6 1191/**
1192 * @package moodlecore
1193 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1194 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1195 */
9683db71 1196class table_sql extends flexible_table {
9cf4a18b 1197
1198 public $countsql = NULL;
1199 public $countparams = NULL;
20e1f1c0 1200 /**
9cf4a18b 1201 * @var object sql for querying db. Has fields 'fields', 'from', 'where', 'params'.
20e1f1c0 1202 */
9cf4a18b 1203 public $sql = NULL;
20e1f1c0 1204 /**
1205 * @var array Data fetched from the db.
1206 */
9cf4a18b 1207 public $rawdata = NULL;
1208
20e1f1c0 1209 /**
1210 * @var boolean Overriding default for this.
1211 */
9cf4a18b 1212 public $is_sortable = true;
20e1f1c0 1213 /**
1214 * @var boolean Overriding default for this.
1215 */
9cf4a18b 1216 public $is_collapsible = true;
1217
20e1f1c0 1218 /**
1219 * @param string $uniqueid a string identifying this table.Used as a key in
1220 * session vars.
1221 */
a49c17b4
TH
1222 function __construct($uniqueid) {
1223 parent::__construct($uniqueid);
20e1f1c0 1224 // some sensible defaults
1225 $this->set_attribute('cellspacing', '0');
1226 $this->set_attribute('class', 'generaltable generalbox');
7270d81f 1227 }
9cf4a18b 1228
a49c17b4
TH
1229 /**
1230 * Backwards-compatible constructor, so that legacy code subclassing
1231 * table_sql does not break.
1232 * @deprecated since Moodle 2.0. Will be removed in Moodle 2.1.
1233 */
1234 function table_sql($uniqueid) {
1235 debugging('Please update your code to user PHP5-style parent::__construct(...), ' .
1236 'not parent::table_sql(...).');
1237 $this->__construct($uniqueid);
1238 }
1239
20e1f1c0 1240 /**
1241 * Take the data returned from the db_query and go through all the rows
1242 * processing each col using either col_{columnname} method or other_cols
1243 * method or if other_cols returns NULL then put the data straight into the
1244 * table.
1245 */
9683db71
TH
1246 function build_table() {
1247 if ($this->rawdata) {
1248 foreach ($this->rawdata as $row) {
20e1f1c0 1249 $formattedrow = $this->format_row($row);
b08fb128
TH
1250 $this->add_data_keyed($formattedrow,
1251 $this->get_row_class($row));
20e1f1c0 1252 }
1253 }
1254 }
1255
b08fb128
TH
1256 /**
1257 * Get any extra classes names to add to this row in the HTML.
1258 * @param $row array the data for this row.
1259 * @return string added to the class="" attribute of the tr.
1260 */
1261 function get_row_class($row) {
1262 return '';
1263 }
1264
20e1f1c0 1265 /**
1266 * This is only needed if you want to use different sql to count rows.
1267 * Used for example when perhaps all db JOINS are not needed when counting
1268 * records. You don't need to call this function the count_sql
1269 * will be generated automatically.
9cf4a18b 1270 *
20e1f1c0 1271 * We need to count rows returned by the db seperately to the query itself
1272 * as we need to know how many pages of data we have to display.
1273 */
9683db71 1274 function set_count_sql($sql, array $params = NULL) {
20e1f1c0 1275 $this->countsql = $sql;
9cf4a18b 1276 $this->countparams = $params;
20e1f1c0 1277 }
9cf4a18b 1278
20e1f1c0 1279 /**
1280 * Set the sql to query the db. Query will be :
1281 * SELECT $fields FROM $from WHERE $where
1282 * Of course you can use sub-queries, JOINS etc. by putting them in the
1283 * appropriate clause of the query.
1284 */
9683db71 1285 function set_sql($fields, $from, $where, array $params = NULL) {
365a5941 1286 $this->sql = new stdClass();
20e1f1c0 1287 $this->sql->fields = $fields;
1288 $this->sql->from = $from;
1289 $this->sql->where = $where;
9cf4a18b 1290 $this->sql->params = $params;
20e1f1c0 1291 }
9cf4a18b 1292
20e1f1c0 1293 /**
1294 * Query the db. Store results in the table object for use by build_table.
9cf4a18b 1295 *
20e1f1c0 1296 * @param integer $pagesize size of page for paginated displayed table.
1297 * @param boolean $useinitialsbar do you want to use the initials bar. Bar
1298 * will only be used if there is a fullname column defined for the table.
1299 */
9683db71 1300 function query_db($pagesize, $useinitialsbar=true) {
9cf4a18b 1301 global $DB;
20e1f1c0 1302 if (!$this->is_downloading()) {
9683db71 1303 if ($this->countsql === NULL) {
20e1f1c0 1304 $this->countsql = 'SELECT COUNT(1) FROM '.$this->sql->from.' WHERE '.$this->sql->where;
1305 }
1306 if ($useinitialsbar && !$this->is_downloading()) {
9cf4a18b 1307 $totalinitials = $DB->count_records_sql($this->countsql, $this->countparams);
20e1f1c0 1308 $this->initialbars($totalinitials>$pagesize);
1309 }
9cf4a18b 1310
20a79b43
PS
1311 list($wsql, $wparams) = $this->get_sql_where();
1312 if ($wsql) {
1313 $this->countsql .= ' AND '.$wsql;
23040521 1314 $this->countparams = array_merge($this->countparams, $wparams);
20a79b43
PS
1315
1316 $this->sql->where .= ' AND '.$wsql;
1317 $this->sql->params = array_merge($this->sql->params, $wparams);
1318
0fa4107d 1319 $total = $DB->count_records_sql($this->countsql, $this->countparams);
1320 } else {
1321 $total = $totalinitials;
20e1f1c0 1322 }
20e1f1c0 1323
20e1f1c0 1324 $this->pagesize($pagesize, $total);
1325 }
1326
1327 // Fetch the attempts
1328 $sort = $this->get_sql_sort();
e81eed54
TH
1329 if ($sort) {
1330 $sort = "ORDER BY $sort";
1331 }
1332 $sql = "SELECT
1333 {$this->sql->fields}
1334 FROM {$this->sql->from}
1335 WHERE {$this->sql->where}
1336 {$sort}";
1337
20e1f1c0 1338 if (!$this->is_downloading()) {
9cf4a18b 1339 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
20e1f1c0 1340 } else {
9cf4a18b 1341 $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
20e1f1c0 1342 }
1343 }
9cf4a18b 1344
20e1f1c0 1345 /**
1346 * Convenience method to call a number of methods for you to display the
1347 * table.
1348 */
9683db71 1349 function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
9cf4a18b 1350 global $DB;
9683db71 1351 if (!$this->columns) {
9cf4a18b 1352 $onerow = $DB->get_record_sql("SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}", $this->sql->params);
20e1f1c0 1353 //if columns is not set then define columns as the keys of the rows returned
1354 //from the db.
1355 $this->define_columns(array_keys((array)$onerow));
1356 $this->define_headers(array_keys((array)$onerow));
1357 }
1358 $this->setup();
1359 $this->query_db($pagesize, $useinitialsbar);
1360 $this->build_table();
1361 $this->finish_output();
1362 }
1363}
1364
9683db71 1365
72fb21b6 1366/**
1367 * @package moodlecore
1368 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1370 */
9683db71 1371class table_default_export_format_parent {
20e1f1c0 1372 /**
1373 * @var flexible_table or child class reference pointing to table class
1374 * object from which to export data.
1375 */
1376 var $table;
117bd748 1377
43ec99aa 1378 /**
1379 * @var boolean output started. Keeps track of whether any output has been
1380 * started yet.
1381 */
1382 var $documentstarted = false;
9683db71 1383 function table_default_export_format_parent(&$table) {
20e1f1c0 1384 $this->table =& $table;
1385 }
117bd748 1386
9683db71 1387 function set_table(&$table) {
43ec99aa 1388 $this->table =& $table;
1389 }
20e1f1c0 1390
1391 function add_data($row) {
1392 return false;
1393 }
9683db71 1394
20e1f1c0 1395 function add_seperator() {
1396 return false;
1397 }
9683db71
TH
1398
1399 function document_started() {
43ec99aa 1400 return $this->documentstarted;
20e1f1c0 1401 }
ef27e742 1402 /**
1403 * Given text in a variety of format codings, this function returns
1404 * the text as safe HTML or as plain text dependent on what is appropriate
1405 * for the download format. The default removes all tags.
1406 */
9683db71 1407 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
ef27e742 1408 //use some whitespace to indicate where there was some line spacing.
1409 $text = str_replace(array('</p>', "\n", "\r"), ' ', $text);
1410 return strip_tags($text);
1411 }
7270d81f 1412}
1413
9683db71 1414
72fb21b6 1415/**
1416 * @package moodlecore
1417 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1419 */
9683db71 1420class table_spreadsheet_export_format_parent extends table_default_export_format_parent {
20e1f1c0 1421 var $rownum;
1422 var $workbook;
1423 var $worksheet;
1424 /**
1425 * @var object format object - format for normal table cells
1426 */
1427 var $formatnormal;
1428 /**
1429 * @var object format object - format for header table cells
1430 */
1431 var $formatheaders;
1432
9cf4a18b 1433 /**
20e1f1c0 1434 * should be overriden in child class.
1435 */
1436 var $fileextension;
9cf4a18b 1437
20e1f1c0 1438 /**
1439 * This method will be overridden in the child class.
1440 */
9683db71 1441 function define_workbook() {
20e1f1c0 1442 }
9683db71
TH
1443
1444 function start_document($filename) {
43ec99aa 1445 $filename = $filename.'.'.$this->fileextension;
20e1f1c0 1446 $this->define_workbook();
20e1f1c0 1447 // format types
1448 $this->formatnormal =& $this->workbook->add_format();
1449 $this->formatnormal->set_bold(0);
1450 $this->formatheaders =& $this->workbook->add_format();
1451 $this->formatheaders->set_bold(1);
1452 $this->formatheaders->set_align('center');
20e1f1c0 1453 // Sending HTTP headers
43ec99aa 1454 $this->workbook->send($filename);
1455 $this->documentstarted = true;
1456 }
9683db71
TH
1457
1458 function start_table($sheettitle) {
43ec99aa 1459 $this->worksheet =& $this->workbook->add_worksheet($sheettitle);
20e1f1c0 1460 $this->rownum=0;
1461 }
9683db71
TH
1462
1463 function output_headers($headers) {
20e1f1c0 1464 $colnum = 0;
1465 foreach ($headers as $item) {
1466 $this->worksheet->write($this->rownum,$colnum,$item,$this->formatheaders);
1467 $colnum++;
1468 }
1469 $this->rownum++;
1470 }
9683db71
TH
1471
1472 function add_data($row) {
20e1f1c0 1473 $colnum = 0;
9683db71 1474 foreach ($row as $item) {
20e1f1c0 1475 $this->worksheet->write($this->rownum,$colnum,$item,$this->formatnormal);
1476 $colnum++;
1477 }
1478 $this->rownum++;
1479 return true;
1480 }
9683db71 1481
20e1f1c0 1482 function add_seperator() {
1483 $this->rownum++;
1484 return true;
1485 }
43ec99aa 1486
9683db71 1487 function finish_table() {
43ec99aa 1488 }
9683db71
TH
1489
1490 function finish_document() {
20e1f1c0 1491 $this->workbook->close();
1492 exit;
1493 }
1494}
1495
9683db71 1496
72fb21b6 1497/**
1498 * @package moodlecore
1499 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1501 */
9683db71 1502class table_excel_export_format extends table_spreadsheet_export_format_parent {
20e1f1c0 1503 var $fileextension = 'xls';
1504
9683db71 1505 function define_workbook() {
20e1f1c0 1506 global $CFG;
1507 require_once("$CFG->libdir/excellib.class.php");
1508 // Creating a workbook
1509 $this->workbook = new MoodleExcelWorkbook("-");
1510 }
1511
1512}
1513
9683db71 1514
72fb21b6 1515/**
1516 * @package moodlecore
1517 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1518 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1519 */
9683db71 1520class table_ods_export_format extends table_spreadsheet_export_format_parent {
20e1f1c0 1521 var $fileextension = 'ods';
9683db71 1522 function define_workbook() {
20e1f1c0 1523 global $CFG;
1524 require_once("$CFG->libdir/odslib.class.php");
1525 // Creating a workbook
1526 $this->workbook = new MoodleODSWorkbook("-");
1527 }
1528}
1529
9683db71 1530
72fb21b6 1531/**
1532 * @package moodlecore
1533 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1535 */
6944b5e4
TH
1536class table_text_export_format_parent extends table_default_export_format_parent {
1537 protected $seperator = "\t";
1538 protected $mimetype = 'text/tab-separated-values';
1539 protected $ext = '.txt';
1540
1541 public function start_document($filename) {
1542 $this->filename = $filename . $this->ext;
1543 header('Content-Type: ' . $this->mimetype . '; charset=UTF-8');
1544 header('Content-Disposition: attachment; filename="' . $this->filename . '"');
1545 header('Expires: 0');
1546 header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
1547 header('Pragma: public');
43ec99aa 1548 $this->documentstarted = true;
1549 }
6944b5e4
TH
1550
1551 public function start_table($sheettitle) {
43ec99aa 1552 //nothing to do here
20e1f1c0 1553 }
6944b5e4
TH
1554
1555 public function output_headers($headers) {
1556 echo $this->format_row($headers);
20e1f1c0 1557 }
6944b5e4
TH
1558
1559 public function add_data($row) {
1560 echo $this->format_row($row);
20e1f1c0 1561 return true;
1562 }
6944b5e4
TH
1563
1564 public function finish_table() {
43ec99aa 1565 echo "\n\n";
1566 }
6944b5e4
TH
1567
1568 public function finish_document() {
20e1f1c0 1569 exit;
1570 }
6944b5e4
TH
1571
1572 /**
1573 * Format a row of data.
1574 * @param array $data
1575 */
1576 protected function format_row($data) {
1577 $escapeddata = array();
1578 foreach ($data as $value) {
1579 $escapeddata[] = '"' . str_replace('"', '""', $value) . '"';
1580 }
1581 return implode($this->seperator, $escapeddata) . "\n";
1582 }
20e1f1c0 1583}
1584
9683db71 1585
72fb21b6 1586/**
1587 * @package moodlecore
1588 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1590 */
9683db71 1591class table_tsv_export_format extends table_text_export_format_parent {
6944b5e4
TH
1592 protected $seperator = "\t";
1593 protected $mimetype = 'text/tab-separated-values';
1594 protected $ext = '.txt';
20e1f1c0 1595}
1596
9683db71 1597
72fb21b6 1598/**
1599 * @package moodlecore
1600 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1602 */
9683db71 1603class table_csv_export_format extends table_text_export_format_parent {
6944b5e4
TH
1604 protected $seperator = ",";
1605 protected $mimetype = 'text/csv';
1606 protected $ext = '.csv';
20e1f1c0 1607}
1608
9683db71 1609
72fb21b6 1610/**
1611 * @package moodlecore
1612 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
1613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1614 */
9683db71
TH
1615class table_xhtml_export_format extends table_default_export_format_parent {
1616 function start_document($filename) {
20e1f1c0 1617 header("Content-Type: application/download\n");
43ec99aa 1618 header("Content-Disposition: attachment; filename=\"$filename.html\"");
20e1f1c0 1619 header("Expires: 0");
1620 header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
1621 header("Pragma: public");
20e1f1c0 1622 //html headers
20e1f1c0 1623 echo <<<EOF
1624<?xml version="1.0" encoding="UTF-8"?>
1625<!DOCTYPE html
1626 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
9cf4a18b 1627 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
20e1f1c0 1628
9cf4a18b 1629<html xmlns="http://www.w3.org/1999/xhtml"
20e1f1c0 1630 xml:lang="en" lang="en">
869309b8 1631<head>
20e1f1c0 1632<style type="text/css">/*<![CDATA[*/
1633
1634.flexible th {
1635white-space:normal;
1636}
1637th.header, td.header, div.header {
1638border-color:#DDDDDD;
1639background-color:lightGrey;
1640}
1641.flexible th {
1642white-space:nowrap;
1643}
1644th {
1645font-weight:bold;
1646}
1647
1648.generaltable {
1649border-style:solid;
1650}
1651.generalbox {
1652border-style:solid;
1653}
1654body, table, td, th {
1655font-family:Arial,Verdana,Helvetica,sans-serif;
1656font-size:100%;
1657}
1658td {
1659 border-style:solid;
1660 border-width:1pt;
1661}
1662table {
1663 border-collapse:collapse;
1664 border-spacing:0pt;
1665 width:80%;
1666 margin:auto;
1667}
1668
9683db71 1669h1, h2 {
20e1f1c0 1670 text-align:center;
1671}
1672.bold {
1673font-weight:bold;
1674}
869309b8 1675.mdl-align {
1676 text-align:center;
1677}
20e1f1c0 1678/*]]>*/</style>
869309b8 1679<title>$filename</title>
1680</head>
20e1f1c0 1681<body>
20e1f1c0 1682EOF;
43ec99aa 1683 $this->documentstarted = true;
1684 }
9683db71
TH
1685
1686 function start_table($sheettitle) {
43ec99aa 1687 $this->table->sortable(false);
1688 $this->table->collapsible(false);
1689 echo "<h2>{$sheettitle}</h2>";
20e1f1c0 1690 $this->table->start_html();
1691 }
43ec99aa 1692
9683db71 1693 function output_headers($headers) {
20e1f1c0 1694 $this->table->print_headers();
1695 }
9683db71
TH
1696
1697 function add_data($row) {
20e1f1c0 1698 $this->table->print_row($row);
1699 return true;
1700 }
9683db71 1701
20e1f1c0 1702 function add_seperator() {
1703 $this->table->print_row(NULL);
1704 return true;
1705 }
9683db71
TH
1706
1707 function finish_table() {
20e1f1c0 1708 $this->table->finish_html();
43ec99aa 1709 }
9683db71
TH
1710
1711 function finish_document() {
869309b8 1712 echo "</body>\n</html>";
20e1f1c0 1713 exit;
1714 }
9683db71
TH
1715
1716 function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
1717 if (is_null($options)) {
ef27e742 1718 $options = new stdClass;
1719 }
1720 //some sensible defaults
9683db71 1721 if (!isset($options->para)) {
ef27e742 1722 $options->para = false;
1723 }
9683db71 1724 if (!isset($options->newlines)) {
ef27e742 1725 $options->newlines = false;
1726 }
1727 if (!isset($options->smiley)) {
1728 $options->smiley = false;
1729 }
1730 if (!isset($options->filter)) {
1731 $options->filter = false;
1732 }
1733 return format_text($text, $format, $options);
1734 }
20e1f1c0 1735}