Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]

   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  declare(strict_types=1);
  18  
  19  namespace core_reportbuilder\table;
  20  
  21  use action_menu;
  22  use core_table\local\filter\filterset;
  23  use html_writer;
  24  use moodle_exception;
  25  use stdClass;
  26  use core_reportbuilder\manager;
  27  use core_reportbuilder\local\models\report;
  28  use core_reportbuilder\local\report\action;
  29  use core_reportbuilder\local\report\column;
  30  
  31  defined('MOODLE_INTERNAL') || die;
  32  
  33  /**
  34   * System report dynamic table class
  35   *
  36   * @package     core_reportbuilder
  37   * @copyright   2020 Paul Holden <paulh@moodle.com>
  38   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39   */
  40  class system_report_table extends base_report_table {
  41  
  42      /** @var string Unique ID prefix for the table */
  43      private const UNIQUEID_PREFIX = 'system-report-table-';
  44  
  45      /**
  46       * Table constructor. Note that the passed unique ID value must match the pattern "system-report-table-(\d+)" so that
  47       * dynamic updates continue to load the same report
  48       *
  49       * @param string $uniqueid
  50       * @param array $parameters
  51       * @throws moodle_exception For invalid unique ID
  52       */
  53      public function __construct(string $uniqueid, array $parameters = []) {
  54          if (!preg_match('/^' . self::UNIQUEID_PREFIX . '(?<id>\d+)$/', $uniqueid, $matches)) {
  55              throw new moodle_exception('invalidsystemreportid', 'core_reportbuilder', '', null, $uniqueid);
  56          }
  57  
  58          parent::__construct($uniqueid);
  59  
  60          // If we are loading via a dynamic table AJAX request, defer the report loading until the filterset is added to
  61          // the table, as it is used to populate the report $parameters during construction.
  62          $serviceinfo = optional_param('info', null, PARAM_RAW);
  63          if ($serviceinfo !== 'core_table_get_dynamic_table_content') {
  64              $this->load_report_instance((int) $matches['id'], $parameters);
  65          }
  66      }
  67  
  68      /**
  69       * Load the report persistent, and accompanying system report instance.
  70       *
  71       * @param int $reportid
  72       * @param array $parameters
  73       */
  74      private function load_report_instance(int $reportid, array $parameters): void {
  75          $this->persistent = new report($reportid);
  76          $this->report = manager::get_report_from_persistent($this->persistent, $parameters);
  77  
  78          $fields = $this->report->get_base_fields();
  79          $maintable = $this->report->get_main_table();
  80          $maintablealias = $this->report->get_main_table_alias();
  81          $joins = $this->report->get_joins();
  82          [$where, $params] = $this->report->get_base_condition();
  83  
  84          $this->set_attribute('data-region', 'reportbuilder-table');
  85          $this->set_attribute('class', $this->attributes['class'] . ' reportbuilder-table');
  86  
  87          // Download options.
  88          $this->showdownloadbuttonsat = [TABLE_P_BOTTOM];
  89          $this->is_downloading($parameters['download'] ?? null, $this->report->get_downloadfilename());
  90  
  91          // Retrieve all report columns. If we are downloading the report, remove as required.
  92          $columns = $this->report->get_columns();
  93          if ($this->is_downloading()) {
  94              $columns = array_diff_key($columns,
  95                  array_flip($this->report->get_exclude_columns_for_download()));
  96          }
  97  
  98          $columnheaders = $columnsattributes = [];
  99          $columnindex = 1;
 100          foreach ($columns as $identifier => $column) {
 101              $column->set_index($columnindex++);
 102  
 103              $columnheaders[$column->get_column_alias()] = $column->get_title();
 104  
 105              // Specify whether column should behave as a user fullname column unless the column has a custom title set.
 106              if (preg_match('/^user:fullname.*$/', $column->get_unique_identifier()) && !$column->has_custom_title()) {
 107                  $this->userfullnamecolumns[] = $column->get_column_alias();
 108              }
 109  
 110              // Add each columns fields, joins and params to our report.
 111              $fields = array_merge($fields, $column->get_fields());
 112              $joins = array_merge($joins, $column->get_joins());
 113              $params = array_merge($params, $column->get_params());
 114  
 115              // Disable sorting for some columns.
 116              if (!$column->get_is_sortable()) {
 117                  $this->no_sorting($column->get_column_alias());
 118              }
 119  
 120              // Generate column attributes to be included in each cell.
 121              $columnsattributes[$column->get_column_alias()] = $column->get_attributes();
 122          }
 123  
 124          // If the report has any actions then append appropriate column, note that actions are excluded during download.
 125          if ($this->report->has_actions() && !$this->is_downloading()) {
 126              $columnheaders['actions'] = html_writer::tag('span', get_string('actions', 'core_reportbuilder'), [
 127                  'class' => 'sr-only',
 128              ]);
 129              $this->no_sorting('actions');
 130          }
 131  
 132          $this->define_columns(array_keys($columnheaders));
 133          $this->define_headers(array_values($columnheaders));
 134  
 135          // Add column attributes to the table.
 136          $this->set_columnsattributes($columnsattributes);
 137  
 138          // Initial table sort column.
 139          if ($sortcolumn = $this->report->get_initial_sort_column()) {
 140              $this->sortable(true, $sortcolumn->get_column_alias(), $this->report->get_initial_sort_direction());
 141          }
 142  
 143          // Table configuration.
 144          $this->initialbars(false);
 145          $this->collapsible(false);
 146          $this->pageable(true);
 147          $this->set_default_per_page($this->report->get_default_per_page());
 148  
 149          // Initialise table SQL properties.
 150          $fieldsql = implode(', ', $fields);
 151          $this->init_sql($fieldsql, "{{$maintable}} {$maintablealias}", $joins, $where, $params);
 152      }
 153  
 154      /**
 155       * Return a new instance of the class for given report ID. We include report parameters here so they are present during
 156       * initialisation
 157       *
 158       * @param int $reportid
 159       * @param array $parameters
 160       * @return static
 161       */
 162      public static function create(int $reportid, array $parameters): self {
 163          return new static(self::UNIQUEID_PREFIX . $reportid, $parameters);
 164      }
 165  
 166      /**
 167       * Set the filterset in the table class. We set the report parameters here so that they are persisted while paging
 168       *
 169       * @param filterset $filterset
 170       */
 171      public function set_filterset(filterset $filterset): void {
 172          $reportid = $filterset->get_filter('reportid')->current();
 173          $parameters = $filterset->get_filter('parameters')->current();
 174  
 175          $this->load_report_instance($reportid, json_decode($parameters, true));
 176  
 177          parent::set_filterset($filterset);
 178      }
 179  
 180      /**
 181       * Override parent method for retrieving row class with that defined by the system report
 182       *
 183       * @param array|stdClass $row
 184       * @return string
 185       */
 186      public function get_row_class($row) {
 187          return $this->report->get_row_class((object) $row);
 188      }
 189  
 190      /**
 191       * Format each row of returned data, executing defined callbacks for the row and each column
 192       *
 193       * @param array|stdClass $row
 194       * @return array
 195       */
 196      public function format_row($row) {
 197          $this->report->row_callback((object) $row);
 198  
 199          // Walk over the row, and for any key that matches one of our column aliases, call that columns format method.
 200          $columnsbyalias = $this->report->get_active_columns_by_alias();
 201          $row = (array) $row;
 202          array_walk($row, static function(&$value, $key) use ($columnsbyalias, $row): void {
 203              if (array_key_exists($key, $columnsbyalias)) {
 204                  $value = $columnsbyalias[$key]->format_value($row);
 205              }
 206          });
 207  
 208          if ($this->report->has_actions()) {
 209              $row['actions'] = $this->format_row_actions((object) $row);
 210          }
 211  
 212          return $row;
 213      }
 214  
 215      /**
 216       * Return formatted actions column for the row
 217       *
 218       * @param stdClass $row
 219       * @return string
 220       */
 221      private function format_row_actions(stdClass $row): string {
 222          global $OUTPUT;
 223  
 224          $menu = new action_menu();
 225          $menu->set_menu_trigger($OUTPUT->pix_icon('a/setting', get_string('actions', 'core_reportbuilder')));
 226          foreach ($this->report->get_actions() as $action) {
 227              // Ensure the action link can be displayed for the current row.
 228              $actionlink = $action->get_action_link($row);
 229              if ($actionlink) {
 230                  $menu->add($actionlink);
 231              }
 232          }
 233          return $OUTPUT->render($menu);
 234      }
 235  
 236      /**
 237       * Get the html for the download buttons
 238       *
 239       * @return string
 240       */
 241      public function download_buttons(): string {
 242          global $OUTPUT;
 243  
 244          if ($this->report->can_be_downloaded() && !$this->is_downloading()) {
 245              return $OUTPUT->download_dataformat_selector(
 246                  get_string('downloadas', 'table'),
 247                  new \moodle_url('/reportbuilder/download.php'),
 248                  'download',
 249                  [
 250                      'id' => $this->persistent->get('id'),
 251                      'parameters' => json_encode($this->report->get_parameters()),
 252                  ]
 253              );
 254          }
 255  
 256          return '';
 257      }
 258  }