PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/tablelib.php

http://github.com/moodle/moodle
PHP | 2203 lines | 1181 code | 281 blank | 741 comment | 228 complexity | d7a2ea1aeb34906e44e5fccb63e02536 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

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. use core_table\local\filter\filterset;
  43. /**
  44. * @package moodlecore
  45. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  46. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  47. */
  48. class flexible_table {
  49. var $uniqueid = NULL;
  50. var $attributes = array();
  51. var $headers = array();
  52. /**
  53. * @var string A column which should be considered as a header column.
  54. */
  55. protected $headercolumn = null;
  56. /**
  57. * @var string For create header with help icon.
  58. */
  59. private $helpforheaders = array();
  60. var $columns = array();
  61. var $column_style = array();
  62. var $column_class = array();
  63. var $column_suppress = array();
  64. var $column_nosort = array('userpic');
  65. private $column_textsort = array();
  66. /** @var boolean Stores if setup has already been called on this flixible table. */
  67. var $setup = false;
  68. var $baseurl = NULL;
  69. var $request = array();
  70. /**
  71. * @var bool Whether or not to store table properties in the user_preferences table.
  72. */
  73. private $persistent = false;
  74. var $is_collapsible = false;
  75. var $is_sortable = false;
  76. /**
  77. * @var string The field name to sort by.
  78. */
  79. protected $sortby;
  80. /**
  81. * @var string $sortorder The direction for sorting.
  82. */
  83. protected $sortorder;
  84. /** @var string The manually set first name initial preference */
  85. protected $ifirst;
  86. /** @var string The manually set last name initial preference */
  87. protected $ilast;
  88. var $use_pages = false;
  89. var $use_initials = false;
  90. var $maxsortkeys = 2;
  91. var $pagesize = 30;
  92. var $currpage = 0;
  93. var $totalrows = 0;
  94. var $currentrow = 0;
  95. var $sort_default_column = NULL;
  96. var $sort_default_order = SORT_ASC;
  97. /**
  98. * Array of positions in which to display download controls.
  99. */
  100. var $showdownloadbuttonsat= array(TABLE_P_TOP);
  101. /**
  102. * @var string Key of field returned by db query that is the id field of the
  103. * user table or equivalent.
  104. */
  105. public $useridfield = 'id';
  106. /**
  107. * @var string which download plugin to use. Default '' means none - print
  108. * html table with paging. Property set by is_downloading which typically
  109. * passes in cleaned data from $
  110. */
  111. var $download = '';
  112. /**
  113. * @var bool whether data is downloadable from table. Determines whether
  114. * to display download buttons. Set by method downloadable().
  115. */
  116. var $downloadable = false;
  117. /**
  118. * @var bool Has start output been called yet?
  119. */
  120. var $started_output = false;
  121. var $exportclass = null;
  122. /**
  123. * @var array For storing user-customised table properties in the user_preferences db table.
  124. */
  125. private $prefs = array();
  126. /** @var $sheettitle */
  127. protected $sheettitle;
  128. /** @var $filename */
  129. protected $filename;
  130. /** @var array $hiddencolumns List of hidden columns. */
  131. protected $hiddencolumns;
  132. /** @var $resetting bool Whether the table preferences is resetting. */
  133. protected $resetting;
  134. /**
  135. * @var filterset The currently applied filerset
  136. * This is required for dynamic tables, but can be used by other tables too if desired.
  137. */
  138. protected $filterset = null;
  139. /**
  140. * Constructor
  141. * @param string $uniqueid all tables have to have a unique id, this is used
  142. * as a key when storing table properties like sort order in the session.
  143. */
  144. function __construct($uniqueid) {
  145. $this->uniqueid = $uniqueid;
  146. $this->request = array(
  147. TABLE_VAR_SORT => 'tsort',
  148. TABLE_VAR_HIDE => 'thide',
  149. TABLE_VAR_SHOW => 'tshow',
  150. TABLE_VAR_IFIRST => 'tifirst',
  151. TABLE_VAR_ILAST => 'tilast',
  152. TABLE_VAR_PAGE => 'page',
  153. TABLE_VAR_RESET => 'treset',
  154. TABLE_VAR_DIR => 'tdir',
  155. );
  156. }
  157. /**
  158. * Call this to pass the download type. Use :
  159. * $download = optional_param('download', '', PARAM_ALPHA);
  160. * To get the download type. We assume that if you call this function with
  161. * params that this table's data is downloadable, so we call is_downloadable
  162. * for you (even if the param is '', which means no download this time.
  163. * Also you can call this method with no params to get the current set
  164. * download type.
  165. * @param string $download dataformat type. One of csv, xhtml, ods, etc
  166. * @param string $filename filename for downloads without file extension.
  167. * @param string $sheettitle title for downloaded data.
  168. * @return string download dataformat type. One of csv, xhtml, ods, etc
  169. */
  170. function is_downloading($download = null, $filename='', $sheettitle='') {
  171. if ($download!==null) {
  172. $this->sheettitle = $sheettitle;
  173. $this->is_downloadable(true);
  174. $this->download = $download;
  175. $this->filename = clean_filename($filename);
  176. $this->export_class_instance();
  177. }
  178. return $this->download;
  179. }
  180. /**
  181. * Get, and optionally set, the export class.
  182. * @param $exportclass (optional) if passed, set the table to use this export class.
  183. * @return table_default_export_format_parent the export class in use (after any set).
  184. */
  185. function export_class_instance($exportclass = null) {
  186. if (!is_null($exportclass)) {
  187. $this->started_output = true;
  188. $this->exportclass = $exportclass;
  189. $this->exportclass->table = $this;
  190. } else if (is_null($this->exportclass) && !empty($this->download)) {
  191. $this->exportclass = new table_dataformat_export_format($this, $this->download);
  192. if (!$this->exportclass->document_started()) {
  193. $this->exportclass->start_document($this->filename, $this->sheettitle);
  194. }
  195. }
  196. return $this->exportclass;
  197. }
  198. /**
  199. * Probably don't need to call this directly. Calling is_downloading with a
  200. * param automatically sets table as downloadable.
  201. *
  202. * @param bool $downloadable optional param to set whether data from
  203. * table is downloadable. If ommitted this function can be used to get
  204. * current state of table.
  205. * @return bool whether table data is set to be downloadable.
  206. */
  207. function is_downloadable($downloadable = null) {
  208. if ($downloadable !== null) {
  209. $this->downloadable = $downloadable;
  210. }
  211. return $this->downloadable;
  212. }
  213. /**
  214. * Call with boolean true to store table layout changes in the user_preferences table.
  215. * Note: user_preferences.value has a maximum length of 1333 characters.
  216. * Call with no parameter to get current state of table persistence.
  217. *
  218. * @param bool $persistent Optional parameter to set table layout persistence.
  219. * @return bool Whether or not the table layout preferences will persist.
  220. */
  221. public function is_persistent($persistent = null) {
  222. if ($persistent == true) {
  223. $this->persistent = true;
  224. }
  225. return $this->persistent;
  226. }
  227. /**
  228. * Where to show download buttons.
  229. * @param array $showat array of postions in which to show download buttons.
  230. * Containing TABLE_P_TOP and/or TABLE_P_BOTTOM
  231. */
  232. function show_download_buttons_at($showat) {
  233. $this->showdownloadbuttonsat = $showat;
  234. }
  235. /**
  236. * Sets the is_sortable variable to the given boolean, sort_default_column to
  237. * the given string, and the sort_default_order to the given integer.
  238. * @param bool $bool
  239. * @param string $defaultcolumn
  240. * @param int $defaultorder
  241. * @return void
  242. */
  243. function sortable($bool, $defaultcolumn = NULL, $defaultorder = SORT_ASC) {
  244. $this->is_sortable = $bool;
  245. $this->sort_default_column = $defaultcolumn;
  246. $this->sort_default_order = $defaultorder;
  247. }
  248. /**
  249. * Use text sorting functions for this column (required for text columns with Oracle).
  250. * Be warned that you cannot use this with column aliases. You can only do this
  251. * with real columns. See MDL-40481 for an example.
  252. * @param string column name
  253. */
  254. function text_sorting($column) {
  255. $this->column_textsort[] = $column;
  256. }
  257. /**
  258. * Do not sort using this column
  259. * @param string column name
  260. */
  261. function no_sorting($column) {
  262. $this->column_nosort[] = $column;
  263. }
  264. /**
  265. * Is the column sortable?
  266. * @param string column name, null means table
  267. * @return bool
  268. */
  269. function is_sortable($column = null) {
  270. if (empty($column)) {
  271. return $this->is_sortable;
  272. }
  273. if (!$this->is_sortable) {
  274. return false;
  275. }
  276. return !in_array($column, $this->column_nosort);
  277. }
  278. /**
  279. * Sets the is_collapsible variable to the given boolean.
  280. * @param bool $bool
  281. * @return void
  282. */
  283. function collapsible($bool) {
  284. $this->is_collapsible = $bool;
  285. }
  286. /**
  287. * Sets the use_pages variable to the given boolean.
  288. * @param bool $bool
  289. * @return void
  290. */
  291. function pageable($bool) {
  292. $this->use_pages = $bool;
  293. }
  294. /**
  295. * Sets the use_initials variable to the given boolean.
  296. * @param bool $bool
  297. * @return void
  298. */
  299. function initialbars($bool) {
  300. $this->use_initials = $bool;
  301. }
  302. /**
  303. * Sets the pagesize variable to the given integer, the totalrows variable
  304. * to the given integer, and the use_pages variable to true.
  305. * @param int $perpage
  306. * @param int $total
  307. * @return void
  308. */
  309. function pagesize($perpage, $total) {
  310. $this->pagesize = $perpage;
  311. $this->totalrows = $total;
  312. $this->use_pages = true;
  313. }
  314. /**
  315. * Assigns each given variable in the array to the corresponding index
  316. * in the request class variable.
  317. * @param array $variables
  318. * @return void
  319. */
  320. function set_control_variables($variables) {
  321. foreach ($variables as $what => $variable) {
  322. if (isset($this->request[$what])) {
  323. $this->request[$what] = $variable;
  324. }
  325. }
  326. }
  327. /**
  328. * Gives the given $value to the $attribute index of $this->attributes.
  329. * @param string $attribute
  330. * @param mixed $value
  331. * @return void
  332. */
  333. function set_attribute($attribute, $value) {
  334. $this->attributes[$attribute] = $value;
  335. }
  336. /**
  337. * What this method does is set the column so that if the same data appears in
  338. * consecutive rows, then it is not repeated.
  339. *
  340. * For example, in the quiz overview report, the fullname column is set to be suppressed, so
  341. * that when one student has made multiple attempts, their name is only printed in the row
  342. * for their first attempt.
  343. * @param int $column the index of a column.
  344. */
  345. function column_suppress($column) {
  346. if (isset($this->column_suppress[$column])) {
  347. $this->column_suppress[$column] = true;
  348. }
  349. }
  350. /**
  351. * Sets the given $column index to the given $classname in $this->column_class.
  352. * @param int $column
  353. * @param string $classname
  354. * @return void
  355. */
  356. function column_class($column, $classname) {
  357. if (isset($this->column_class[$column])) {
  358. $this->column_class[$column] = ' '.$classname; // This space needed so that classnames don't run together in the HTML
  359. }
  360. }
  361. /**
  362. * Sets the given $column index and $property index to the given $value in $this->column_style.
  363. * @param int $column
  364. * @param string $property
  365. * @param mixed $value
  366. * @return void
  367. */
  368. function column_style($column, $property, $value) {
  369. if (isset($this->column_style[$column])) {
  370. $this->column_style[$column][$property] = $value;
  371. }
  372. }
  373. /**
  374. * Sets all columns' $propertys to the given $value in $this->column_style.
  375. * @param int $property
  376. * @param string $value
  377. * @return void
  378. */
  379. function column_style_all($property, $value) {
  380. foreach (array_keys($this->columns) as $column) {
  381. $this->column_style[$column][$property] = $value;
  382. }
  383. }
  384. /**
  385. * Sets $this->baseurl.
  386. * @param moodle_url|string $url the url with params needed to call up this page
  387. */
  388. function define_baseurl($url) {
  389. $this->baseurl = new moodle_url($url);
  390. }
  391. /**
  392. * @param array $columns an array of identifying names for columns. If
  393. * columns are sorted then column names must correspond to a field in sql.
  394. */
  395. function define_columns($columns) {
  396. $this->columns = array();
  397. $this->column_style = array();
  398. $this->column_class = array();
  399. $colnum = 0;
  400. foreach ($columns as $column) {
  401. $this->columns[$column] = $colnum++;
  402. $this->column_style[$column] = array();
  403. $this->column_class[$column] = '';
  404. $this->column_suppress[$column] = false;
  405. }
  406. }
  407. /**
  408. * @param array $headers numerical keyed array of displayed string titles
  409. * for each column.
  410. */
  411. function define_headers($headers) {
  412. $this->headers = $headers;
  413. }
  414. /**
  415. * Mark a specific column as being a table header using the column name defined in define_columns.
  416. *
  417. * Note: Only one column can be a header, and it will be rendered using a th tag.
  418. *
  419. * @param string $column
  420. */
  421. public function define_header_column(string $column) {
  422. $this->headercolumn = $column;
  423. }
  424. /**
  425. * Defines a help icon for the header
  426. *
  427. * Always use this function if you need to create header with sorting and help icon.
  428. *
  429. * @param renderable[] $helpicons An array of renderable objects to be used as help icons
  430. */
  431. public function define_help_for_headers($helpicons) {
  432. $this->helpforheaders = $helpicons;
  433. }
  434. /**
  435. * Mark the table preferences to be reset.
  436. */
  437. public function mark_table_to_reset(): void {
  438. $this->resetting = true;
  439. }
  440. /**
  441. * Is the table marked for reset preferences?
  442. *
  443. * @return bool True if the table is marked to reset, false otherwise.
  444. */
  445. protected function is_resetting_preferences(): bool {
  446. if ($this->resetting === null) {
  447. $this->resetting = optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL);
  448. }
  449. return $this->resetting;
  450. }
  451. /**
  452. * Must be called after table is defined. Use methods above first. Cannot
  453. * use functions below till after calling this method.
  454. * @return type?
  455. */
  456. function setup() {
  457. if (empty($this->columns) || empty($this->uniqueid)) {
  458. return false;
  459. }
  460. $this->initialise_table_preferences();
  461. if (empty($this->baseurl)) {
  462. debugging('You should set baseurl when using flexible_table.');
  463. global $PAGE;
  464. $this->baseurl = $PAGE->url;
  465. }
  466. if ($this->currpage == null) {
  467. $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
  468. }
  469. $this->setup = true;
  470. // Always introduce the "flexible" class for the table if not specified
  471. if (empty($this->attributes)) {
  472. $this->attributes['class'] = 'flexible table table-striped table-hover';
  473. } else if (!isset($this->attributes['class'])) {
  474. $this->attributes['class'] = 'flexible table table-striped table-hover';
  475. } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
  476. $this->attributes['class'] = trim('flexible table table-striped table-hover ' . $this->attributes['class']);
  477. }
  478. }
  479. /**
  480. * Get the order by clause from the session or user preferences, for the table with id $uniqueid.
  481. * @param string $uniqueid the identifier for a table.
  482. * @return SQL fragment that can be used in an ORDER BY clause.
  483. */
  484. public static function get_sort_for_table($uniqueid) {
  485. global $SESSION;
  486. if (isset($SESSION->flextable[$uniqueid])) {
  487. $prefs = $SESSION->flextable[$uniqueid];
  488. } else if (!$prefs = json_decode(get_user_preferences('flextable_' . $uniqueid), true)) {
  489. return '';
  490. }
  491. if (empty($prefs['sortby'])) {
  492. return '';
  493. }
  494. if (empty($prefs['textsort'])) {
  495. $prefs['textsort'] = array();
  496. }
  497. return self::construct_order_by($prefs['sortby'], $prefs['textsort']);
  498. }
  499. /**
  500. * Prepare an an order by clause from the list of columns to be sorted.
  501. * @param array $cols column name => SORT_ASC or SORT_DESC
  502. * @return SQL fragment that can be used in an ORDER BY clause.
  503. */
  504. public static function construct_order_by($cols, $textsortcols=array()) {
  505. global $DB;
  506. $bits = array();
  507. foreach ($cols as $column => $order) {
  508. if (in_array($column, $textsortcols)) {
  509. $column = $DB->sql_order_by_text($column);
  510. }
  511. if ($order == SORT_ASC) {
  512. $bits[] = $column . ' ASC';
  513. } else {
  514. $bits[] = $column . ' DESC';
  515. }
  516. }
  517. return implode(', ', $bits);
  518. }
  519. /**
  520. * @return SQL fragment that can be used in an ORDER BY clause.
  521. */
  522. public function get_sql_sort() {
  523. return self::construct_order_by($this->get_sort_columns(), $this->column_textsort);
  524. }
  525. /**
  526. * Get the columns to sort by, in the form required by {@link construct_order_by()}.
  527. * @return array column name => SORT_... constant.
  528. */
  529. public function get_sort_columns() {
  530. if (!$this->setup) {
  531. throw new coding_exception('Cannot call get_sort_columns until you have called setup.');
  532. }
  533. if (empty($this->prefs['sortby'])) {
  534. return array();
  535. }
  536. foreach ($this->prefs['sortby'] as $column => $notused) {
  537. if (isset($this->columns[$column])) {
  538. continue; // This column is OK.
  539. }
  540. if (in_array($column, get_all_user_name_fields()) &&
  541. isset($this->columns['fullname'])) {
  542. continue; // This column is OK.
  543. }
  544. // This column is not OK.
  545. unset($this->prefs['sortby'][$column]);
  546. }
  547. return $this->prefs['sortby'];
  548. }
  549. /**
  550. * @return int the offset for LIMIT clause of SQL
  551. */
  552. function get_page_start() {
  553. if (!$this->use_pages) {
  554. return '';
  555. }
  556. return $this->currpage * $this->pagesize;
  557. }
  558. /**
  559. * @return int the pagesize for LIMIT clause of SQL
  560. */
  561. function get_page_size() {
  562. if (!$this->use_pages) {
  563. return '';
  564. }
  565. return $this->pagesize;
  566. }
  567. /**
  568. * @return string sql to add to where statement.
  569. */
  570. function get_sql_where() {
  571. global $DB;
  572. $conditions = array();
  573. $params = array();
  574. if (isset($this->columns['fullname'])) {
  575. static $i = 0;
  576. $i++;
  577. if (!empty($this->prefs['i_first'])) {
  578. $conditions[] = $DB->sql_like('firstname', ':ifirstc'.$i, false, false);
  579. $params['ifirstc'.$i] = $this->prefs['i_first'].'%';
  580. }
  581. if (!empty($this->prefs['i_last'])) {
  582. $conditions[] = $DB->sql_like('lastname', ':ilastc'.$i, false, false);
  583. $params['ilastc'.$i] = $this->prefs['i_last'].'%';
  584. }
  585. }
  586. return array(implode(" AND ", $conditions), $params);
  587. }
  588. /**
  589. * Add a row of data to the table. This function takes an array or object with
  590. * column names as keys or property names.
  591. *
  592. * It ignores any elements with keys that are not defined as columns. It
  593. * puts in empty strings into the row when there is no element in the passed
  594. * array corresponding to a column in the table. It puts the row elements in
  595. * the proper order (internally row table data is stored by in arrays with
  596. * a numerical index corresponding to the column number).
  597. *
  598. * @param object|array $rowwithkeys array keys or object property names are column names,
  599. * as defined in call to define_columns.
  600. * @param string $classname CSS class name to add to this row's tr tag.
  601. */
  602. function add_data_keyed($rowwithkeys, $classname = '') {
  603. $this->add_data($this->get_row_from_keyed($rowwithkeys), $classname);
  604. }
  605. /**
  606. * Add a number of rows to the table at once. And optionally finish output after they have been added.
  607. *
  608. * @param (object|array|null)[] $rowstoadd Array of rows to add to table, a null value in array adds a separator row. Or a
  609. * object or array is added to table. We expect properties for the row array as would be
  610. * passed to add_data_keyed.
  611. * @param bool $finish
  612. */
  613. public function format_and_add_array_of_rows($rowstoadd, $finish = true) {
  614. foreach ($rowstoadd as $row) {
  615. if (is_null($row)) {
  616. $this->add_separator();
  617. } else {
  618. $this->add_data_keyed($this->format_row($row));
  619. }
  620. }
  621. if ($finish) {
  622. $this->finish_output(!$this->is_downloading());
  623. }
  624. }
  625. /**
  626. * Add a seperator line to table.
  627. */
  628. function add_separator() {
  629. if (!$this->setup) {
  630. return false;
  631. }
  632. $this->add_data(NULL);
  633. }
  634. /**
  635. * This method actually directly echoes the row passed to it now or adds it
  636. * to the download. If this is the first row and start_output has not
  637. * already been called this method also calls start_output to open the table
  638. * or send headers for the downloaded.
  639. * Can be used as before. print_html now calls finish_html to close table.
  640. *
  641. * @param array $row a numerically keyed row of data to add to the table.
  642. * @param string $classname CSS class name to add to this row's tr tag.
  643. * @return bool success.
  644. */
  645. function add_data($row, $classname = '') {
  646. if (!$this->setup) {
  647. return false;
  648. }
  649. if (!$this->started_output) {
  650. $this->start_output();
  651. }
  652. if ($this->exportclass!==null) {
  653. if ($row === null) {
  654. $this->exportclass->add_seperator();
  655. } else {
  656. $this->exportclass->add_data($row);
  657. }
  658. } else {
  659. $this->print_row($row, $classname);
  660. }
  661. return true;
  662. }
  663. /**
  664. * You should call this to finish outputting the table data after adding
  665. * data to the table with add_data or add_data_keyed.
  666. *
  667. */
  668. function finish_output($closeexportclassdoc = true) {
  669. if ($this->exportclass!==null) {
  670. $this->exportclass->finish_table();
  671. if ($closeexportclassdoc) {
  672. $this->exportclass->finish_document();
  673. }
  674. } else {
  675. $this->finish_html();
  676. }
  677. }
  678. /**
  679. * Hook that can be overridden in child classes to wrap a table in a form
  680. * for example. Called only when there is data to display and not
  681. * downloading.
  682. */
  683. function wrap_html_start() {
  684. }
  685. /**
  686. * Hook that can be overridden in child classes to wrap a table in a form
  687. * for example. Called only when there is data to display and not
  688. * downloading.
  689. */
  690. function wrap_html_finish() {
  691. }
  692. /**
  693. * Call appropriate methods on this table class to perform any processing on values before displaying in table.
  694. * Takes raw data from the database and process it into human readable format, perhaps also adding html linking when
  695. * displaying table as html, adding a div wrap, etc.
  696. *
  697. * See for example col_fullname below which will be called for a column whose name is 'fullname'.
  698. *
  699. * @param array|object $row row of data from db used to make one row of the table.
  700. * @return array one row for the table, added using add_data_keyed method.
  701. */
  702. function format_row($row) {
  703. if (is_array($row)) {
  704. $row = (object)$row;
  705. }
  706. $formattedrow = array();
  707. foreach (array_keys($this->columns) as $column) {
  708. $colmethodname = 'col_'.$column;
  709. if (method_exists($this, $colmethodname)) {
  710. $formattedcolumn = $this->$colmethodname($row);
  711. } else {
  712. $formattedcolumn = $this->other_cols($column, $row);
  713. if ($formattedcolumn===NULL) {
  714. $formattedcolumn = $row->$column;
  715. }
  716. }
  717. $formattedrow[$column] = $formattedcolumn;
  718. }
  719. return $formattedrow;
  720. }
  721. /**
  722. * Fullname is treated as a special columname in tablelib and should always
  723. * be treated the same as the fullname of a user.
  724. * @uses $this->useridfield if the userid field is not expected to be id
  725. * then you need to override $this->useridfield to point at the correct
  726. * field for the user id.
  727. *
  728. * @param object $row the data from the db containing all fields from the
  729. * users table necessary to construct the full name of the user in
  730. * current language.
  731. * @return string contents of cell in column 'fullname', for this row.
  732. */
  733. function col_fullname($row) {
  734. global $COURSE;
  735. $name = fullname($row, has_capability('moodle/site:viewfullnames', $this->get_context()));
  736. if ($this->download) {
  737. return $name;
  738. }
  739. $userid = $row->{$this->useridfield};
  740. if ($COURSE->id == SITEID) {
  741. $profileurl = new moodle_url('/user/profile.php', array('id' => $userid));
  742. } else {
  743. $profileurl = new moodle_url('/user/view.php',
  744. array('id' => $userid, 'course' => $COURSE->id));
  745. }
  746. return html_writer::link($profileurl, $name);
  747. }
  748. /**
  749. * You can override this method in a child class. See the description of
  750. * build_table which calls this method.
  751. */
  752. function other_cols($column, $row) {
  753. return NULL;
  754. }
  755. /**
  756. * Used from col_* functions when text is to be displayed. Does the
  757. * right thing - either converts text to html or strips any html tags
  758. * depending on if we are downloading and what is the download type. Params
  759. * are the same as format_text function in weblib.php but some default
  760. * options are changed.
  761. */
  762. function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL) {
  763. if (!$this->is_downloading()) {
  764. if (is_null($options)) {
  765. $options = new stdClass;
  766. }
  767. //some sensible defaults
  768. if (!isset($options->para)) {
  769. $options->para = false;
  770. }
  771. if (!isset($options->newlines)) {
  772. $options->newlines = false;
  773. }
  774. if (!isset($options->smiley)) {
  775. $options->smiley = false;
  776. }
  777. if (!isset($options->filter)) {
  778. $options->filter = false;
  779. }
  780. return format_text($text, $format, $options);
  781. } else {
  782. $eci = $this->export_class_instance();
  783. return $eci->format_text($text, $format, $options, $courseid);
  784. }
  785. }
  786. /**
  787. * This method is deprecated although the old api is still supported.
  788. * @deprecated 1.9.2 - Jun 2, 2008
  789. */
  790. function print_html() {
  791. if (!$this->setup) {
  792. return false;
  793. }
  794. $this->finish_html();
  795. }
  796. /**
  797. * This function is not part of the public api.
  798. * @return string initial of first name we are currently filtering by
  799. */
  800. function get_initial_first() {
  801. if (!$this->use_initials) {
  802. return NULL;
  803. }
  804. return $this->prefs['i_first'];
  805. }
  806. /**
  807. * This function is not part of the public api.
  808. * @return string initial of last name we are currently filtering by
  809. */
  810. function get_initial_last() {
  811. if (!$this->use_initials) {
  812. return NULL;
  813. }
  814. return $this->prefs['i_last'];
  815. }
  816. /**
  817. * Helper function, used by {@link print_initials_bar()} to output one initial bar.
  818. * @param array $alpha of letters in the alphabet.
  819. * @param string $current the currently selected letter.
  820. * @param string $class class name to add to this initial bar.
  821. * @param string $title the name to put in front of this initial bar.
  822. * @param string $urlvar URL parameter name for this initial.
  823. *
  824. * @deprecated since Moodle 3.3
  825. */
  826. protected function print_one_initials_bar($alpha, $current, $class, $title, $urlvar) {
  827. debugging('Method print_one_initials_bar() is no longer used and has been deprecated, ' .
  828. 'to print initials bar call print_initials_bar()', DEBUG_DEVELOPER);
  829. echo html_writer::start_tag('div', array('class' => 'initialbar ' . $class)) .
  830. $title . ' : ';
  831. if ($current) {
  832. echo html_writer::link($this->baseurl->out(false, array($urlvar => '')), get_string('all'));
  833. } else {
  834. echo html_writer::tag('strong', get_string('all'));
  835. }
  836. foreach ($alpha as $letter) {
  837. if ($letter === $current) {
  838. echo html_writer::tag('strong', $letter);
  839. } else {
  840. echo html_writer::link($this->baseurl->out(false, array($urlvar => $letter)), $letter);
  841. }
  842. }
  843. echo html_writer::end_tag('div');
  844. }
  845. /**
  846. * This function is not part of the public api.
  847. */
  848. function print_initials_bar() {
  849. global $OUTPUT;
  850. $ifirst = $this->get_initial_first();
  851. $ilast = $this->get_initial_last();
  852. if (is_null($ifirst)) {
  853. $ifirst = '';
  854. }
  855. if (is_null($ilast)) {
  856. $ilast = '';
  857. }
  858. if ((!empty($ifirst) || !empty($ilast) ||$this->use_initials)
  859. && isset($this->columns['fullname'])) {
  860. $prefixfirst = $this->request[TABLE_VAR_IFIRST];
  861. $prefixlast = $this->request[TABLE_VAR_ILAST];
  862. echo $OUTPUT->initials_bar($ifirst, 'firstinitial', get_string('firstname'), $prefixfirst, $this->baseurl);
  863. echo $OUTPUT->initials_bar($ilast, 'lastinitial', get_string('lastname'), $prefixlast, $this->baseurl);
  864. }
  865. }
  866. /**
  867. * This function is not part of the public api.
  868. */
  869. function print_nothing_to_display() {
  870. global $OUTPUT;
  871. // Render the dynamic table header.
  872. echo $this->get_dynamic_table_html_start();
  873. // Render button to allow user to reset table preferences.
  874. echo $this->render_reset_button();
  875. $this->print_initials_bar();
  876. echo $OUTPUT->heading(get_string('nothingtodisplay'));
  877. // Render the dynamic table footer.
  878. echo $this->get_dynamic_table_html_end();
  879. }
  880. /**
  881. * This function is not part of the public api.
  882. */
  883. function get_row_from_keyed($rowwithkeys) {
  884. if (is_object($rowwithkeys)) {
  885. $rowwithkeys = (array)$rowwithkeys;
  886. }
  887. $row = array();
  888. foreach (array_keys($this->columns) as $column) {
  889. if (isset($rowwithkeys[$column])) {
  890. $row [] = $rowwithkeys[$column];
  891. } else {
  892. $row[] ='';
  893. }
  894. }
  895. return $row;
  896. }
  897. /**
  898. * Get the html for the download buttons
  899. *
  900. * Usually only use internally
  901. */
  902. public function download_buttons() {
  903. global $OUTPUT;
  904. if ($this->is_downloadable() && !$this->is_downloading()) {
  905. return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
  906. $this->baseurl->out_omit_querystring(), 'download', $this->baseurl->params());
  907. } else {
  908. return '';
  909. }
  910. }
  911. /**
  912. * This function is not part of the public api.
  913. * You don't normally need to call this. It is called automatically when
  914. * needed when you start adding data to the table.
  915. *
  916. */
  917. function start_output() {
  918. $this->started_output = true;
  919. if ($this->exportclass!==null) {
  920. $this->exportclass->start_table($this->sheettitle);
  921. $this->exportclass->output_headers($this->headers);
  922. } else {
  923. $this->start_html();
  924. $this->print_headers();
  925. echo html_writer::start_tag('tbody');
  926. }
  927. }
  928. /**
  929. * This function is not part of the public api.
  930. */
  931. function print_row($row, $classname = '') {
  932. echo $this->get_row_html($row, $classname);
  933. }
  934. /**
  935. * Generate html code for the passed row.
  936. *
  937. * @param array $row Row data.
  938. * @param string $classname classes to add.
  939. *
  940. * @return string $html html code for the row passed.
  941. */
  942. public function get_row_html($row, $classname = '') {
  943. static $suppress_lastrow = NULL;
  944. $rowclasses = array();
  945. if ($classname) {
  946. $rowclasses[] = $classname;
  947. }
  948. $rowid = $this->uniqueid . '_r' . $this->currentrow;
  949. $html = '';
  950. $html .= html_writer::start_tag('tr', array('class' => implode(' ', $rowclasses), 'id' => $rowid));
  951. // If we have a separator, print it
  952. if ($row === NULL) {
  953. $colcount = count($this->columns);
  954. $html .= html_writer::tag('td', html_writer::tag('div', '',
  955. array('class' => 'tabledivider')), array('colspan' => $colcount));
  956. } else {
  957. $colbyindex = array_flip($this->columns);
  958. foreach ($row as $index => $data) {
  959. $column = $colbyindex[$index];
  960. $attributes = [
  961. 'class' => "cell c{$index}" . $this->column_class[$column],
  962. 'id' => "{$rowid}_c{$index}",
  963. 'style' => $this->make_styles_string($this->column_style[$column]),
  964. ];
  965. $celltype = 'td';
  966. if ($this->headercolumn && $column == $this->headercolumn) {
  967. $celltype = 'th';
  968. $attributes['scope'] = 'row';
  969. }
  970. if (empty($this->prefs['collapse'][$column])) {
  971. if ($this->column_suppress[$column] && $suppress_lastrow !== NULL && $suppress_lastrow[$index] === $data) {
  972. $content = '&nbsp;';
  973. } else {
  974. $content = $data;
  975. }
  976. } else {
  977. $content = '&nbsp;';
  978. }
  979. $html .= html_writer::tag($celltype, $content, $attributes);
  980. }
  981. }
  982. $html .= html_writer::end_tag('tr');
  983. $suppress_enabled = array_sum($this->column_suppress);
  984. if ($suppress_enabled) {
  985. $suppress_lastrow = $row;
  986. }
  987. $this->currentrow++;
  988. return $html;
  989. }
  990. /**
  991. * This function is not part of the public api.
  992. */
  993. function finish_html() {
  994. global $OUTPUT, $PAGE;
  995. if (!$this->started_output) {
  996. //no data has been added to the table.
  997. $this->print_nothing_to_display();
  998. } else {
  999. // Print empty rows to fill the table to the current pagesize.
  1000. // This is done so the header aria-controls attributes do not point to
  1001. // non existant elements.
  1002. $emptyrow = array_fill(0, count($this->columns), '');
  1003. while ($this->currentrow < $this->pagesize) {
  1004. $this->print_row($emptyrow, 'emptyrow');
  1005. }
  1006. echo html_writer::end_tag('tbody');
  1007. echo html_writer::end_tag('table');
  1008. echo html_writer::end_tag('div');
  1009. $this->wrap_html_finish();
  1010. // Paging bar
  1011. if(in_array(TABLE_P_BOTTOM, $this->showdownloadbuttonsat)) {
  1012. echo $this->download_buttons();
  1013. }
  1014. if($this->use_pages) {
  1015. $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
  1016. $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
  1017. echo $OUTPUT->render($pagingbar);
  1018. }
  1019. // Render the dynamic table footer.
  1020. echo $this->get_dynamic_table_html_end();
  1021. }
  1022. }
  1023. /**
  1024. * Generate the HTML for the collapse/uncollapse icon. This is a helper method
  1025. * used by {@link print_headers()}.
  1026. * @param string $column the column name, index into various names.
  1027. * @param int $index numerical index of the column.
  1028. * @return string HTML fragment.
  1029. */
  1030. protected function show_hide_link($column, $index) {
  1031. global $OUTPUT;
  1032. // Some headers contain <br /> tags, do not include in title, hence the
  1033. // strip tags.
  1034. $ariacontrols = '';
  1035. for ($i = 0; $i < $this->pagesize; $i++) {
  1036. $ariacontrols .= $this->uniqueid . '_r' . $i . '_c' . $index . ' ';
  1037. }
  1038. $ariacontrols = trim($ariacontrols);
  1039. if (!empty($this->prefs['collapse'][$column])) {
  1040. $linkattributes = array('title' => get_string('show') . ' ' . strip_tags($this->headers[$index]),
  1041. 'aria-expanded' => 'false',
  1042. 'aria-controls' => $ariacontrols,
  1043. 'data-action' => 'show',
  1044. 'data-column' => $column);
  1045. return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_SHOW] => $column)),
  1046. $OUTPUT->pix_icon('t/switch_plus', get_string('show')), $linkattributes);
  1047. } else if ($this->headers[$index] !== NULL) {
  1048. $linkattributes = array('title' => get_string('hide') . ' ' . strip_tags($this->headers[$index]),
  1049. 'aria-expanded' => 'true',
  1050. 'aria-controls' => $ariacontrols,
  1051. 'data-action' => 'hide',
  1052. 'data-column' => $column);
  1053. return html_writer::link($this->baseurl->out(false, array($this->request[TABLE_VAR_HIDE] => $column)),
  1054. $OUTPUT->pix_icon('t/switch_minus', get_string('hide')), $linkattributes);
  1055. }
  1056. }
  1057. /**
  1058. * This function is not part of the public api.
  1059. */
  1060. function print_headers() {
  1061. global $CFG, $OUTPUT;
  1062. echo html_writer::start_tag('thead');
  1063. echo html_writer::start_tag('tr');
  1064. foreach ($this->columns as $column => $index) {
  1065. $icon_hide = '';
  1066. if ($this->is_collapsible) {
  1067. $icon_hide = $this->show_hide_link($column, $index);
  1068. }
  1069. $primarysortcolumn = '';
  1070. $primarysortorder = '';
  1071. if (reset($this->prefs['sortby'])) {
  1072. $primarysortcolumn = key($this->prefs['sortby']);
  1073. $primarysortorder = current($this->prefs['sortby']);
  1074. }
  1075. switch ($column) {
  1076. case 'fullname':
  1077. // Check the full name display for sortable fields.
  1078. if (has_capability('moodle/site:viewfullnames', $this->get_context())) {
  1079. $nameformat = $CFG->alternativefullnameformat;
  1080. } else {
  1081. $nameformat = $CFG->fullnamedisplay;
  1082. }
  1083. if ($nameformat == 'language') {
  1084. $nameformat = get_string('fullnamedisplay');
  1085. }
  1086. $requirednames = order_in_string(get_all_user_name_fields(), $nameformat);
  1087. if (!empty($requirednames)) {
  1088. if ($this->is_sortable($column)) {
  1089. // Done this way for the possibility of more than two sortable full name display fields.
  1090. $this->headers[$index] = '';
  1091. foreach ($requirednames as $name) {
  1092. $sortname = $this->sort_link(get_string($name),
  1093. $name, $primarysortcolumn === $name, $primarysortorder);
  1094. $this->headers[$index] .= $sortname . ' / ';
  1095. }
  1096. $helpicon = '';
  1097. if (isset($this->helpforheaders[$index])) {
  1098. $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
  1099. }
  1100. $this->headers[$index] = substr($this->headers[$index], 0, -3). $helpicon;
  1101. }
  1102. }
  1103. break;
  1104. case 'userpic':
  1105. // do nothing, do not display sortable links
  1106. break;
  1107. default:
  1108. if ($this->is_sortable($column)) {
  1109. $helpicon = '';
  1110. if (isset($this->helpforheaders[$index])) {
  1111. $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
  1112. }
  1113. $this->headers[$index] = $this->sort_link($this->headers[$index],
  1114. $column, $primarysortcolumn == $column, $primarysortorder) . $helpicon;
  1115. }
  1116. }
  1117. $attributes = array(
  1118. 'class' => 'header c' . $index . $this->column_class[$column],
  1119. 'scope' => 'col',
  1120. );
  1121. if ($this->headers[$index] === NULL) {
  1122. $content = '&nbsp;';
  1123. } else if (!empty($this->prefs['collapse'][$column])) {
  1124. $content = $icon_hide;
  1125. } else {
  1126. if (is_array($this->column_style[$column])) {
  1127. $attributes['style'] = $this->make_styles_string($this->column_style[$column]);
  1128. }
  1129. $helpicon = '';
  1130. if (isset($this->helpforheaders[$index]) && !$this->is_sortable($column)) {
  1131. $helpicon = $OUTPUT->render($this->helpforheaders[$index]);
  1132. }
  1133. $content = $this->headers[$index] . $helpicon . html_writer::tag('div',
  1134. $icon_hide, array('class' => 'commands'));
  1135. }
  1136. echo html_writer::tag('th', $content, $attributes);
  1137. }
  1138. echo html_writer::end_tag('tr');
  1139. echo html_writer::end_tag('thead');
  1140. }
  1141. /**
  1142. * Calculate the preferences for sort order based on user-supplied values and get params.
  1143. */
  1144. protected function set_sorting_preferences(): void {
  1145. $sortorder = $this->sortorder;
  1146. $sortby = $this->sortby;
  1147. if ($sortorder === null || $sortby === null) {
  1148. $sortorder = optional_param($this->request[TABLE_VAR_DIR], $this->sort_default_order, PARAM_INT);
  1149. $sortby = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT);
  1150. }
  1151. $isvalidsort = $sortby && $this->is_sortable($sortby);
  1152. $isvalidsort = $isvalidsort && empty($this->prefs['collapse'][$sortby]);
  1153. $isrealcolumn = isset($this->columns[$sortby]);
  1154. $isfullnamefield = isset($this->columns['fullname']) && in_array($sortby, get_all_user_name_fields());
  1155. if ($isvalidsort && ($isrealcolumn || $isfullnamefield)) {
  1156. if (array_key_exists($sortby, $this->prefs['sortby'])) {
  1157. // This key already exists somewhere. Change its sortorder and bring it to the top.
  1158. $sortorder = $this->prefs['sortby'][$sortby] = $sortorder;
  1159. unset($this->prefs['sortby'][$sortby]);
  1160. $this->prefs['sortby'] = array_merge(array($sortby => $sortorder), $this->prefs['sortby']);
  1161. } else {
  1162. // Key doesn't exist, so just add it to the beginning of the array, ascending order.
  1163. $this->prefs['sortby'] = array_merge(array($sortby => $sortorder), $this->prefs['sortby']);
  1164. }
  1165. // Finally, make sure that no more than $this->maxsortkeys are present into the array.
  1166. $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
  1167. }
  1168. // If a default order is defined and it is not in the current list of order by columns, add it at the end.
  1169. // This prevents results from being returned in a random order if the only order by column contains equal values.
  1170. if (!empty($this->sort_default_column) && !array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
  1171. $defaultsort = array($this->sort_default_column => $this->sort_default_order);
  1172. $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
  1173. }
  1174. }
  1175. /**
  1176. * Fill in the preferences for the initials bar.
  1177. */
  1178. protected function set_initials_preferences(): void {
  1179. $ifirst = $this->ifirst;
  1180. $ilast = $this->ilast;
  1181. if ($ifirst === null) {
  1182. $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
  1183. }
  1184. if ($ilast === null) {
  1185. $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
  1186. }
  1187. if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
  1188. $this->prefs['i_first'] = $ifirst;
  1189. }
  1190. if (!is_null($ilast) && ($ilast === '' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
  1191. $this->prefs['i_last'] = $ilast;
  1192. }
  1193. }
  1194. /**
  1195. * Set hide and show preferences.
  1196. */
  1197. protected function set_hide_show_preferences(): void {
  1198. if ($this->hiddencolumns !== null) {
  1199. $this->prefs['collapse'] = array_fill_keys(array_filter($this->hiddencolumns, function($column) {
  1200. return array_key_exists($column, $this->columns);
  1201. }), true);
  1202. } else {
  1203. if ($column = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) {
  1204. if (isset($this->columns[$column])) {
  1205. $this->prefs['collapse'][$column] = true;
  1206. }
  1207. }
  1208. }
  1209. if ($column = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) {
  1210. unset($this->prefs['collapse'][$column]);
  1211. }
  1212. foreach (array_keys($this->prefs['collapse']) as $column) {
  1213. if (array_key_exists($column, $this->prefs['sortby'])) {
  1214. unset($this->prefs['sortby'][$column]);
  1215. }
  1216. }
  1217. }
  1218. /**
  1219. * Set the list of hidden columns.
  1220. *
  1221. * @param array $columns The list of hidden columns.
  1222. */
  1223. public function set_hidden_columns(array $columns): void {
  1224. $this->hiddencolumns = $columns;
  1225. }
  1226. /**
  1227. * Initialise table preferences.
  1228. */
  1229. protected function initialise_table_preferences(): void {
  1230. global $SESSION;
  1231. // Load any existing user preferences.
  1232. if ($this->persistent) {
  1233. $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
  1234. $oldprefs = $this->prefs;
  1235. } else if (isset($SESSION->flextable[$this->uniqueid])) {
  1236. $this->prefs = $SESSION->flextable[$this->uniqueid];
  1237. $oldprefs = $this->prefs;
  1238. }
  1239. // Set up default preferences if needed.
  1240. if (!$this->prefs || $this->is_resetting_preferences()) {
  1241. $this->prefs = [
  1242. 'collapse' => [],
  1243. 'sortby' => [],
  1244. 'i_first' => '',
  1245. 'i_last' => '',
  1246. 'textsort' => $this->column_textsort,
  1247. ];
  1248. }
  1249. if (!isset($oldprefs)) {
  1250. $oldprefs = $this->prefs;
  1251. }
  1252. // Save user preferences if they have ch…

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