PageRenderTime 57ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/tablelib.php

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