[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/ -> tablelib.php (source)

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


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1