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