Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 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  /**
  18   * Contains class mod_feedback_responses_table
  19   *
  20   * @package   mod_feedback
  21   * @copyright 2016 Marina Glancy
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  global $CFG;
  28  require_once($CFG->libdir . '/tablelib.php');
  29  
  30  /**
  31   * Class mod_feedback_responses_table
  32   *
  33   * @package   mod_feedback
  34   * @copyright 2016 Marina Glancy
  35   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class mod_feedback_responses_table extends table_sql {
  38  
  39      /**
  40       * Maximum number of feedback questions to display in the "Show responses" table
  41       */
  42      const PREVIEWCOLUMNSLIMIT = 10;
  43  
  44      /**
  45       * Maximum number of feedback questions answers to retrieve in one SQL query.
  46       * Mysql has a limit of 60, we leave 1 for joining with users table.
  47       */
  48      const TABLEJOINLIMIT = 59;
  49  
  50      /**
  51       * When additional queries are needed to retrieve more than TABLEJOINLIMIT questions answers, do it in chunks every x rows.
  52       * Value too small will mean too many DB queries, value too big may cause memory overflow.
  53       */
  54      const ROWCHUNKSIZE = 100;
  55  
  56      /** @var mod_feedback_structure */
  57      protected $feedbackstructure;
  58  
  59      /** @var int */
  60      protected $grandtotal = null;
  61  
  62      /** @var bool */
  63      protected $showall = false;
  64  
  65      /** @var string */
  66      protected $showallparamname = 'showall';
  67  
  68      /** @var string */
  69      protected $downloadparamname = 'download';
  70  
  71      /** @var int number of columns that were not retrieved in the main SQL query
  72       * (no more than TABLEJOINLIMIT tables with values can be joined). */
  73      protected $hasmorecolumns = 0;
  74  
  75      /** @var bool whether we are building this table for a external function */
  76      protected $buildforexternal = false;
  77  
  78      /** @var array the data structure containing the table data for the external function */
  79      protected $dataforexternal = [];
  80  
  81      /**
  82       * Constructor
  83       *
  84       * @param mod_feedback_structure $feedbackstructure
  85       * @param int $group retrieve only users from this group (optional)
  86       */
  87      public function __construct(mod_feedback_structure $feedbackstructure, $group = 0) {
  88          $this->feedbackstructure = $feedbackstructure;
  89  
  90          parent::__construct('feedback-showentry-list-' . $feedbackstructure->get_cm()->instance);
  91  
  92          $this->showall = optional_param($this->showallparamname, 0, PARAM_BOOL);
  93          $this->define_baseurl(new moodle_url('/mod/feedback/show_entries.php',
  94              ['id' => $this->feedbackstructure->get_cm()->id]));
  95          if ($courseid = $this->feedbackstructure->get_courseid()) {
  96              $this->baseurl->param('courseid', $courseid);
  97          }
  98          if ($this->showall) {
  99              $this->baseurl->param($this->showallparamname, $this->showall);
 100          }
 101  
 102          $name = format_string($feedbackstructure->get_feedback()->name);
 103          $this->is_downloadable(true);
 104          $this->is_downloading(optional_param($this->downloadparamname, 0, PARAM_ALPHA),
 105                  $name, get_string('responses', 'feedback'));
 106          $this->useridfield = 'userid';
 107          $this->init($group);
 108      }
 109  
 110      /**
 111       * Initialises table
 112       * @param int $group retrieve only users from this group (optional)
 113       */
 114      protected function init($group = 0) {
 115  
 116          $tablecolumns = array('userpic', 'fullname', 'groups');
 117          $tableheaders = array(
 118              get_string('userpic'),
 119              get_string('fullnameuser'),
 120              get_string('groups')
 121          );
 122  
 123          // TODO Does not support custom user profile fields (MDL-70456).
 124          $userfieldsapi = \core_user\fields::for_identity($this->get_context(), false)->with_userpic();
 125          $ufields = $userfieldsapi->get_sql('u', false, '', $this->useridfield, false)->selects;
 126          $extrafields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);
 127          $fields = 'c.id, c.timemodified as completed_timemodified, c.courseid, '.$ufields;
 128          $from = '{feedback_completed} c '
 129                  . 'JOIN {user} u ON u.id = c.userid AND u.deleted = :notdeleted';
 130          $where = 'c.anonymous_response = :anon
 131                  AND c.feedback = :instance';
 132          if ($this->feedbackstructure->get_courseid()) {
 133              $where .= ' AND c.courseid = :courseid';
 134          }
 135  
 136          if ($this->is_downloading()) {
 137              // When downloading data:
 138              // Remove 'userpic' from downloaded data.
 139              array_shift($tablecolumns);
 140              array_shift($tableheaders);
 141  
 142              // Add all identity fields as separate columns.
 143              foreach ($extrafields as $field) {
 144                  $fields .= ", u.{$field}";
 145                  $tablecolumns[] = $field;
 146                  $tableheaders[] = \core_user\fields::get_display_name($field);
 147              }
 148          }
 149  
 150          if ($this->feedbackstructure->get_feedback()->course == SITEID && !$this->feedbackstructure->get_courseid()) {
 151              $tablecolumns[] = 'courseid';
 152              $tableheaders[] = get_string('course');
 153          }
 154  
 155          $tablecolumns[] = 'completed_timemodified';
 156          $tableheaders[] = get_string('date');
 157  
 158          $this->define_columns($tablecolumns);
 159          $this->define_headers($tableheaders);
 160  
 161          $this->sortable(true, 'lastname', SORT_ASC);
 162          $this->no_sorting('groups');
 163          $this->collapsible(true);
 164          $this->set_attribute('id', 'showentrytable');
 165  
 166          $params = array();
 167          $params['anon'] = FEEDBACK_ANONYMOUS_NO;
 168          $params['instance'] = $this->feedbackstructure->get_feedback()->id;
 169          $params['notdeleted'] = 0;
 170          $params['courseid'] = $this->feedbackstructure->get_courseid();
 171  
 172          $group = (empty($group)) ? groups_get_activity_group($this->feedbackstructure->get_cm(), true) : $group;
 173          if ($group) {
 174              $where .= ' AND c.userid IN (SELECT g.userid FROM {groups_members} g WHERE g.groupid = :group)';
 175              $params['group'] = $group;
 176          }
 177  
 178          $this->set_sql($fields, $from, $where, $params);
 179          $this->set_count_sql("SELECT COUNT(c.id) FROM $from WHERE $where", $params);
 180      }
 181  
 182      /**
 183       * Current context
 184       * @return context_module
 185       */
 186      public function get_context(): context {
 187          return context_module::instance($this->feedbackstructure->get_cm()->id);
 188      }
 189  
 190      /**
 191       * Allows to set the display column value for all columns without "col_xxxxx" method.
 192       * @param string $column column name
 193       * @param stdClass $row current record result of SQL query
 194       */
 195      public function other_cols($column, $row) {
 196          if (preg_match('/^val(\d+)$/', $column, $matches)) {
 197              $items = $this->feedbackstructure->get_items();
 198              $itemobj = feedback_get_item_class($items[$matches[1]]->typ);
 199              $printval = $itemobj->get_printval($items[$matches[1]], (object) ['value' => $row->$column]);
 200              if ($this->is_downloading()) {
 201                  $printval = s($printval);
 202              }
 203              return trim($printval);
 204          }
 205          return parent::other_cols($column, $row);
 206      }
 207  
 208      /**
 209       * Prepares column userpic for display
 210       * @param stdClass $row
 211       * @return string
 212       */
 213      public function col_userpic($row) {
 214          global $OUTPUT;
 215          $user = user_picture::unalias($row, [], $this->useridfield);
 216          return $OUTPUT->user_picture($user, array('courseid' => $this->feedbackstructure->get_cm()->course));
 217      }
 218  
 219      /**
 220       * Prepares column deleteentry for display
 221       * @param stdClass $row
 222       * @return string
 223       */
 224      public function col_deleteentry($row) {
 225          global $OUTPUT;
 226          $deleteentryurl = new moodle_url($this->baseurl, ['delete' => $row->id, 'sesskey' => sesskey()]);
 227          $deleteaction = new confirm_action(get_string('confirmdeleteentry', 'feedback'));
 228          return $OUTPUT->action_icon($deleteentryurl,
 229              new pix_icon('t/delete', get_string('delete_entry', 'feedback')), $deleteaction);
 230      }
 231  
 232      /**
 233       * Returns a link for viewing a single response
 234       * @param stdClass $row
 235       * @return \moodle_url
 236       */
 237      protected function get_link_single_entry($row) {
 238          return new moodle_url($this->baseurl, ['userid' => $row->{$this->useridfield}, 'showcompleted' => $row->id]);
 239      }
 240  
 241      /**
 242       * Prepares column completed_timemodified for display
 243       * @param stdClass $student
 244       * @return string
 245       */
 246      public function col_completed_timemodified($student) {
 247          if ($this->is_downloading()) {
 248              return userdate($student->completed_timemodified);
 249          } else {
 250              return html_writer::link($this->get_link_single_entry($student),
 251                      userdate($student->completed_timemodified));
 252          }
 253      }
 254  
 255      /**
 256       * Prepares column courseid for display
 257       * @param array $row
 258       * @return string
 259       */
 260      public function col_courseid($row) {
 261          $courses = $this->feedbackstructure->get_completed_courses();
 262          $name = '';
 263          if (isset($courses[$row->courseid])) {
 264              $name = $courses[$row->courseid];
 265              if (!$this->is_downloading()) {
 266                  $name = html_writer::link(course_get_url($row->courseid), $name);
 267              }
 268          }
 269          return $name;
 270      }
 271  
 272      /**
 273       * Prepares column groups for display
 274       * @param array $row
 275       * @return string
 276       */
 277      public function col_groups($row) {
 278          $groups = '';
 279          if ($usergrps = groups_get_all_groups($this->feedbackstructure->get_cm()->course, $row->userid, 0, 'name')) {
 280              foreach ($usergrps as $group) {
 281                  $groups .= format_string($group->name). ' ';
 282              }
 283          }
 284          return trim($groups);
 285      }
 286  
 287      /**
 288       * Adds common values to the table that do not change the number or order of entries and
 289       * are only needed when outputting or downloading data.
 290       */
 291      protected function add_all_values_to_output() {
 292          global $DB;
 293  
 294          $tablecolumns = array_keys($this->columns);
 295          $tableheaders = $this->headers;
 296  
 297          $items = $this->feedbackstructure->get_items(true);
 298          if (!$this->is_downloading() && !$this->buildforexternal) {
 299              // In preview mode do not show all columns or the page becomes unreadable.
 300              // The information message will be displayed to the teacher that the rest of the data can be viewed when downloading.
 301              $items = array_slice($items, 0, self::PREVIEWCOLUMNSLIMIT, true);
 302          }
 303  
 304          $columnscount = 0;
 305          $this->hasmorecolumns = max(0, count($items) - self::TABLEJOINLIMIT);
 306  
 307          $headernamepostfix = !$this->is_downloading();
 308          // Add feedback response values.
 309          foreach ($items as $nr => $item) {
 310              if ($columnscount++ < self::TABLEJOINLIMIT) {
 311                  // Mysql has a limit on the number of tables in the join, so we only add limited number of columns here,
 312                  // the rest will be added in {@link self::build_table()} and {@link self::build_table_chunk()} functions.
 313                  $this->sql->fields .= ", " . $DB->sql_cast_to_char("v{$nr}.value") . " AS val{$nr}";
 314                  $this->sql->from .= " LEFT OUTER JOIN {feedback_value} v{$nr} " .
 315                      "ON v{$nr}.completed = c.id AND v{$nr}.item = :itemid{$nr}";
 316                  $this->sql->params["itemid{$nr}"] = $item->id;
 317              }
 318  
 319              $tablecolumns[] = "val{$nr}";
 320              $itemobj = feedback_get_item_class($item->typ);
 321              $columnheader = $itemobj->get_display_name($item, $headernamepostfix);
 322              if (!$this->is_downloading()) {
 323                  $columnheader = shorten_text($columnheader);
 324              }
 325              if (strval($item->label) !== '') {
 326                  $columnheader = get_string('nameandlabelformat', 'mod_feedback',
 327                      (object)['label' => format_string($item->label), 'name' => $columnheader]);
 328              }
 329              $tableheaders[] = $columnheader;
 330          }
 331  
 332          // Add 'Delete entry' column.
 333          if (!$this->is_downloading() && has_capability('mod/feedback:deletesubmissions', $this->get_context())) {
 334              $tablecolumns[] = 'deleteentry';
 335              $tableheaders[] = '';
 336          }
 337  
 338          $this->define_columns($tablecolumns);
 339          $this->define_headers($tableheaders);
 340      }
 341  
 342      /**
 343       * Query the db. Store results in the table object for use by build_table.
 344       *
 345       * @param int $pagesize size of page for paginated displayed table.
 346       * @param bool $useinitialsbar do you want to use the initials bar. Bar
 347       * will only be used if there is a fullname column defined for the table.
 348       */
 349      public function query_db($pagesize, $useinitialsbar=true) {
 350          global $DB;
 351          $this->totalrows = $grandtotal = $this->get_total_responses_count();
 352          if (!$this->is_downloading()) {
 353              $this->initialbars($useinitialsbar);
 354  
 355              list($wsql, $wparams) = $this->get_sql_where();
 356              if ($wsql) {
 357                  $this->countsql .= ' AND '.$wsql;
 358                  $this->countparams = array_merge($this->countparams, $wparams);
 359  
 360                  $this->sql->where .= ' AND '.$wsql;
 361                  $this->sql->params = array_merge($this->sql->params, $wparams);
 362  
 363                  $this->totalrows  = $DB->count_records_sql($this->countsql, $this->countparams);
 364              }
 365  
 366              if ($this->totalrows > $pagesize) {
 367                  $this->pagesize($pagesize, $this->totalrows);
 368              }
 369          }
 370  
 371          if ($sort = $this->get_sql_sort()) {
 372              $sort = "ORDER BY $sort";
 373          }
 374          $sql = "SELECT
 375                  {$this->sql->fields}
 376                  FROM {$this->sql->from}
 377                  WHERE {$this->sql->where}
 378                  {$sort}";
 379  
 380          if (!$this->is_downloading()) {
 381              $this->rawdata = $DB->get_recordset_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
 382          } else {
 383              $this->rawdata = $DB->get_recordset_sql($sql, $this->sql->params);
 384          }
 385      }
 386  
 387      /**
 388       * Returns total number of reponses (without any filters applied)
 389       * @return int
 390       */
 391      public function get_total_responses_count() {
 392          global $DB;
 393          if ($this->grandtotal === null) {
 394              $this->grandtotal = $DB->count_records_sql($this->countsql, $this->countparams);
 395          }
 396          return $this->grandtotal;
 397      }
 398  
 399      /**
 400       * Defines columns
 401       * @param array $columns an array of identifying names for columns. If
 402       * columns are sorted then column names must correspond to a field in sql.
 403       */
 404      public function define_columns($columns) {
 405          parent::define_columns($columns);
 406          foreach ($this->columns as $column => $column) {
 407              // Automatically assign classes to columns.
 408              $this->column_class[$column] = ' ' . $column;
 409          }
 410      }
 411  
 412      /**
 413       * Convenience method to call a number of methods for you to display the
 414       * table.
 415       * @param int $pagesize
 416       * @param bool $useinitialsbar
 417       * @param string $downloadhelpbutton
 418       */
 419      public function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
 420          $this->add_all_values_to_output();
 421          parent::out($pagesize, $useinitialsbar, $downloadhelpbutton);
 422      }
 423  
 424      /**
 425       * Displays the table
 426       */
 427      public function display() {
 428          global $OUTPUT;
 429          groups_print_activity_menu($this->feedbackstructure->get_cm(), $this->baseurl->out());
 430          $grandtotal = $this->get_total_responses_count();
 431          if (!$grandtotal) {
 432              echo $OUTPUT->box(get_string('nothingtodisplay'), 'generalbox nothingtodisplay');
 433              return;
 434          }
 435  
 436          if (count($this->feedbackstructure->get_items(true)) > self::PREVIEWCOLUMNSLIMIT) {
 437              echo $OUTPUT->notification(get_string('questionslimited', 'feedback', self::PREVIEWCOLUMNSLIMIT), 'info');
 438          }
 439  
 440          $this->out($this->showall ? $grandtotal : FEEDBACK_DEFAULT_PAGE_COUNT,
 441                  $grandtotal > FEEDBACK_DEFAULT_PAGE_COUNT);
 442  
 443          // Toggle 'Show all' link.
 444          if ($this->totalrows > FEEDBACK_DEFAULT_PAGE_COUNT) {
 445              if (!$this->use_pages) {
 446                  echo html_writer::div(html_writer::link(new moodle_url($this->baseurl, [$this->showallparamname => 0]),
 447                          get_string('showperpage', '', FEEDBACK_DEFAULT_PAGE_COUNT)), 'showall');
 448              } else {
 449                  echo html_writer::div(html_writer::link(new moodle_url($this->baseurl, [$this->showallparamname => 1]),
 450                          get_string('showall', '', $this->totalrows)), 'showall');
 451              }
 452          }
 453      }
 454  
 455      /**
 456       * Returns links to previous/next responses in the list
 457       * @param stdClass $record
 458       * @return array array of three elements [$prevresponseurl, $returnurl, $nextresponseurl]
 459       */
 460      public function get_reponse_navigation_links($record) {
 461          $this->setup();
 462          $grandtotal = $this->get_total_responses_count();
 463          $this->query_db($grandtotal);
 464          $lastrow = $thisrow = $nextrow = null;
 465          $counter = 0;
 466          $page = 0;
 467          while ($this->rawdata->valid()) {
 468              $row = $this->rawdata->current();
 469              if ($row->id == $record->id) {
 470                  $page = $this->showall ? 0 : floor($counter / FEEDBACK_DEFAULT_PAGE_COUNT);
 471                  $thisrow = $row;
 472                  $this->rawdata->next();
 473                  $nextrow = $this->rawdata->valid() ? $this->rawdata->current() : null;
 474                  break;
 475              }
 476              $lastrow = $row;
 477              $this->rawdata->next();
 478              $counter++;
 479          }
 480          $this->rawdata->close();
 481          if (!$thisrow) {
 482              $lastrow = null;
 483          }
 484          return [
 485              $lastrow ? $this->get_link_single_entry($lastrow) : null,
 486              new moodle_url($this->baseurl, [$this->request[TABLE_VAR_PAGE] => $page]),
 487              $nextrow ? $this->get_link_single_entry($nextrow) : null,
 488          ];
 489      }
 490  
 491      /**
 492       * Download the data.
 493       */
 494      public function download() {
 495          \core\session\manager::write_close();
 496          $this->out($this->get_total_responses_count(), false);
 497          exit;
 498      }
 499  
 500      /**
 501       * Take the data returned from the db_query and go through all the rows
 502       * processing each col using either col_{columnname} method or other_cols
 503       * method or if other_cols returns NULL then put the data straight into the
 504       * table.
 505       *
 506       * This overwrites the parent method because full SQL query may fail on Mysql
 507       * because of the limit in the number of tables in the join. Therefore we only
 508       * join 59 tables in the main query and add the rest here.
 509       *
 510       * @return void
 511       */
 512      public function build_table() {
 513          if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) {
 514              return;
 515          }
 516          if (!$this->rawdata) {
 517              return;
 518          }
 519  
 520          $columnsgroups = [];
 521          if ($this->hasmorecolumns) {
 522              $items = $this->feedbackstructure->get_items(true);
 523              $notretrieveditems = array_slice($items, self::TABLEJOINLIMIT, $this->hasmorecolumns, true);
 524              $columnsgroups = array_chunk($notretrieveditems, self::TABLEJOINLIMIT, true);
 525          }
 526  
 527          $chunk = [];
 528          foreach ($this->rawdata as $row) {
 529              if ($this->hasmorecolumns) {
 530                  $chunk[$row->id] = $row;
 531                  if (count($chunk) >= self::ROWCHUNKSIZE) {
 532                      $this->build_table_chunk($chunk, $columnsgroups);
 533                      $chunk = [];
 534                  }
 535              } else {
 536                  if ($this->buildforexternal) {
 537                      $this->add_data_for_external($row);
 538                  } else {
 539                      $this->add_data_keyed($this->format_row($row), $this->get_row_class($row));
 540                  }
 541              }
 542          }
 543          $this->build_table_chunk($chunk, $columnsgroups);
 544      }
 545  
 546      /**
 547       * Retrieve additional columns. Database engine may have a limit on number of joins.
 548       *
 549       * @param array $rows Array of rows with already retrieved data, new values will be added to this array
 550       * @param array $columnsgroups array of arrays of columns. Each element has up to self::TABLEJOINLIMIT items. This
 551       *     is easy to calculate but because we can call this method many times we calculate it once and pass by
 552       *     reference for performance reasons
 553       */
 554      protected function build_table_chunk(&$rows, &$columnsgroups) {
 555          global $DB;
 556          if (!$rows) {
 557              return;
 558          }
 559  
 560          foreach ($columnsgroups as $columnsgroup) {
 561              $fields = 'c.id';
 562              $from = '{feedback_completed} c';
 563              $params = [];
 564              foreach ($columnsgroup as $nr => $item) {
 565                  $fields .= ", " . $DB->sql_cast_to_char("v{$nr}.value") . " AS val{$nr}";
 566                  $from .= " LEFT OUTER JOIN {feedback_value} v{$nr} " .
 567                      "ON v{$nr}.completed = c.id AND v{$nr}.item = :itemid{$nr}";
 568                  $params["itemid{$nr}"] = $item->id;
 569              }
 570              list($idsql, $idparams) = $DB->get_in_or_equal(array_keys($rows), SQL_PARAMS_NAMED);
 571              $sql = "SELECT $fields FROM $from WHERE c.id ".$idsql;
 572              $results = $DB->get_records_sql($sql, $params + $idparams);
 573              foreach ($results as $result) {
 574                  foreach ($result as $key => $value) {
 575                      $rows[$result->id]->{$key} = $value;
 576                  }
 577              }
 578          }
 579  
 580          foreach ($rows as $row) {
 581              if ($this->buildforexternal) {
 582                  $this->add_data_for_external($row);
 583              } else {
 584                  $this->add_data_keyed($this->format_row($row), $this->get_row_class($row));
 585              }
 586          }
 587      }
 588  
 589      /**
 590       * Returns html code for displaying "Download" button if applicable.
 591       */
 592      public function download_buttons() {
 593          global $OUTPUT;
 594  
 595          if ($this->is_downloadable() && !$this->is_downloading()) {
 596              return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'),
 597                      $this->baseurl->out_omit_querystring(), $this->downloadparamname, $this->baseurl->params());
 598          } else {
 599              return '';
 600          }
 601      }
 602  
 603      /**
 604       * Return user responses data ready for the external function.
 605       *
 606       * @param stdClass $row the table row containing the responses
 607       * @return array returns the responses ready to be used by an external function
 608       * @since Moodle 3.3
 609       */
 610      protected function get_responses_for_external($row) {
 611          $responses = [];
 612          foreach ($row as $el => $val) {
 613              // Get id from column name.
 614              if (preg_match('/^val(\d+)$/', $el, $matches)) {
 615                  $id = $matches[1];
 616  
 617                  $responses[] = [
 618                      'id' => $id,
 619                      'name' => $this->headers[$this->columns[$el]],
 620                      'printval' => $this->other_cols($el, $row),
 621                      'rawval' => $val,
 622                  ];
 623              }
 624          }
 625          return $responses;
 626      }
 627  
 628      /**
 629       * Add data for the external structure that will be returned.
 630       *
 631       * @param stdClass $row a database query record row
 632       * @since Moodle 3.3
 633       */
 634      protected function add_data_for_external($row) {
 635          $this->dataforexternal[] = [
 636              'id' => $row->id,
 637              'courseid' => $row->courseid,
 638              'userid' => $row->userid,
 639              'fullname' => fullname($row),
 640              'timemodified' => $row->completed_timemodified,
 641              'responses' => $this->get_responses_for_external($row),
 642          ];
 643      }
 644  
 645      /**
 646       * Exports the table as an external structure handling pagination.
 647       *
 648       * @param int $page page number (for pagination)
 649       * @param int $perpage elements per page
 650       * @since Moodle 3.3
 651       * @return array returns the table ready to be used by an external function
 652       */
 653      public function export_external_structure($page = 0, $perpage = 0) {
 654  
 655          $this->buildforexternal = true;
 656          $this->add_all_values_to_output();
 657          // Set-up.
 658          $this->setup();
 659          // Override values, if needed.
 660          if ($perpage > 0) {
 661              $this->pageable = true;
 662              $this->currpage = $page;
 663              $this->pagesize = $perpage;
 664          } else {
 665              $this->pagesize = $this->get_total_responses_count();
 666          }
 667          $this->query_db($this->pagesize, false);
 668          $this->build_table();
 669          $this->close_recordset();
 670          return $this->dataforexternal;
 671      }
 672  }