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