PageRenderTime 67ms CodeModel.GetById 23ms 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

Large files files are truncated, but you can click here to view the full file

  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 …

Large files files are truncated, but you can click here to view the full file