PageRenderTime 64ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/tablelib.php

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