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