Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]
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 $tablecolumns = array_keys($this->columns); 293 $tableheaders = $this->headers; 294 295 $items = $this->feedbackstructure->get_items(true); 296 if (!$this->is_downloading() && !$this->buildforexternal) { 297 // In preview mode do not show all columns or the page becomes unreadable. 298 // The information message will be displayed to the teacher that the rest of the data can be viewed when downloading. 299 $items = array_slice($items, 0, self::PREVIEWCOLUMNSLIMIT, true); 300 } 301 302 $columnscount = 0; 303 $this->hasmorecolumns = max(0, count($items) - self::TABLEJOINLIMIT); 304 305 $headernamepostfix = !$this->is_downloading(); 306 // Add feedback response values. 307 foreach ($items as $nr => $item) { 308 if ($columnscount++ < self::TABLEJOINLIMIT) { 309 // Mysql has a limit on the number of tables in the join, so we only add limited number of columns here, 310 // the rest will be added in {@link self::build_table()} and {@link self::build_table_chunk()} functions. 311 $this->sql->fields .= ", v{$nr}.value AS val{$nr}"; 312 $this->sql->from .= " LEFT OUTER JOIN {feedback_value} v{$nr} " . 313 "ON v{$nr}.completed = c.id AND v{$nr}.item = :itemid{$nr}"; 314 $this->sql->params["itemid{$nr}"] = $item->id; 315 } 316 317 $tablecolumns[] = "val{$nr}"; 318 $itemobj = feedback_get_item_class($item->typ); 319 $columnheader = $itemobj->get_display_name($item, $headernamepostfix); 320 if (!$this->is_downloading()) { 321 $columnheader = shorten_text($columnheader); 322 } 323 if (strval($item->label) !== '') { 324 $columnheader = get_string('nameandlabelformat', 'mod_feedback', 325 (object)['label' => format_string($item->label), 'name' => $columnheader]); 326 } 327 $tableheaders[] = $columnheader; 328 } 329 330 // Add 'Delete entry' column. 331 if (!$this->is_downloading() && has_capability('mod/feedback:deletesubmissions', $this->get_context())) { 332 $tablecolumns[] = 'deleteentry'; 333 $tableheaders[] = ''; 334 } 335 336 $this->define_columns($tablecolumns); 337 $this->define_headers($tableheaders); 338 } 339 340 /** 341 * Query the db. Store results in the table object for use by build_table. 342 * 343 * @param int $pagesize size of page for paginated displayed table. 344 * @param bool $useinitialsbar do you want to use the initials bar. Bar 345 * will only be used if there is a fullname column defined for the table. 346 */ 347 public function query_db($pagesize, $useinitialsbar=true) { 348 global $DB; 349 $this->totalrows = $grandtotal = $this->get_total_responses_count(); 350 if (!$this->is_downloading()) { 351 $this->initialbars($useinitialsbar); 352 353 list($wsql, $wparams) = $this->get_sql_where(); 354 if ($wsql) { 355 $this->countsql .= ' AND '.$wsql; 356 $this->countparams = array_merge($this->countparams, $wparams); 357 358 $this->sql->where .= ' AND '.$wsql; 359 $this->sql->params = array_merge($this->sql->params, $wparams); 360 361 $this->totalrows = $DB->count_records_sql($this->countsql, $this->countparams); 362 } 363 364 if ($this->totalrows > $pagesize) { 365 $this->pagesize($pagesize, $this->totalrows); 366 } 367 } 368 369 if ($sort = $this->get_sql_sort()) { 370 $sort = "ORDER BY $sort"; 371 } 372 $sql = "SELECT 373 {$this->sql->fields} 374 FROM {$this->sql->from} 375 WHERE {$this->sql->where} 376 {$sort}"; 377 378 if (!$this->is_downloading()) { 379 $this->rawdata = $DB->get_recordset_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size()); 380 } else { 381 $this->rawdata = $DB->get_recordset_sql($sql, $this->sql->params); 382 } 383 } 384 385 /** 386 * Returns total number of reponses (without any filters applied) 387 * @return int 388 */ 389 public function get_total_responses_count() { 390 global $DB; 391 if ($this->grandtotal === null) { 392 $this->grandtotal = $DB->count_records_sql($this->countsql, $this->countparams); 393 } 394 return $this->grandtotal; 395 } 396 397 /** 398 * Defines columns 399 * @param array $columns an array of identifying names for columns. If 400 * columns are sorted then column names must correspond to a field in sql. 401 */ 402 public function define_columns($columns) { 403 parent::define_columns($columns); 404 foreach ($this->columns as $column => $column) { 405 // Automatically assign classes to columns. 406 $this->column_class[$column] = ' ' . $column; 407 } 408 } 409 410 /** 411 * Convenience method to call a number of methods for you to display the 412 * table. 413 * @param int $pagesize 414 * @param bool $useinitialsbar 415 * @param string $downloadhelpbutton 416 */ 417 public function out($pagesize, $useinitialsbar, $downloadhelpbutton='') { 418 $this->add_all_values_to_output(); 419 parent::out($pagesize, $useinitialsbar, $downloadhelpbutton); 420 } 421 422 /** 423 * Displays the table 424 */ 425 public function display() { 426 global $OUTPUT; 427 groups_print_activity_menu($this->feedbackstructure->get_cm(), $this->baseurl->out()); 428 $grandtotal = $this->get_total_responses_count(); 429 if (!$grandtotal) { 430 echo $OUTPUT->box(get_string('nothingtodisplay'), 'generalbox nothingtodisplay'); 431 return; 432 } 433 434 if (count($this->feedbackstructure->get_items(true)) > self::PREVIEWCOLUMNSLIMIT) { 435 echo $OUTPUT->notification(get_string('questionslimited', 'feedback', self::PREVIEWCOLUMNSLIMIT), 'info'); 436 } 437 438 $this->out($this->showall ? $grandtotal : FEEDBACK_DEFAULT_PAGE_COUNT, 439 $grandtotal > FEEDBACK_DEFAULT_PAGE_COUNT); 440 441 // Toggle 'Show all' link. 442 if ($this->totalrows > FEEDBACK_DEFAULT_PAGE_COUNT) { 443 if (!$this->use_pages) { 444 echo html_writer::div(html_writer::link(new moodle_url($this->baseurl, [$this->showallparamname => 0]), 445 get_string('showperpage', '', FEEDBACK_DEFAULT_PAGE_COUNT)), 'showall'); 446 } else { 447 echo html_writer::div(html_writer::link(new moodle_url($this->baseurl, [$this->showallparamname => 1]), 448 get_string('showall', '', $this->totalrows)), 'showall'); 449 } 450 } 451 } 452 453 /** 454 * Returns links to previous/next responses in the list 455 * @param stdClass $record 456 * @return array array of three elements [$prevresponseurl, $returnurl, $nextresponseurl] 457 */ 458 public function get_reponse_navigation_links($record) { 459 $this->setup(); 460 $grandtotal = $this->get_total_responses_count(); 461 $this->query_db($grandtotal); 462 $lastrow = $thisrow = $nextrow = null; 463 $counter = 0; 464 $page = 0; 465 while ($this->rawdata->valid()) { 466 $row = $this->rawdata->current(); 467 if ($row->id == $record->id) { 468 $page = $this->showall ? 0 : floor($counter / FEEDBACK_DEFAULT_PAGE_COUNT); 469 $thisrow = $row; 470 $this->rawdata->next(); 471 $nextrow = $this->rawdata->valid() ? $this->rawdata->current() : null; 472 break; 473 } 474 $lastrow = $row; 475 $this->rawdata->next(); 476 $counter++; 477 } 478 $this->rawdata->close(); 479 if (!$thisrow) { 480 $lastrow = null; 481 } 482 return [ 483 $lastrow ? $this->get_link_single_entry($lastrow) : null, 484 new moodle_url($this->baseurl, [$this->request[TABLE_VAR_PAGE] => $page]), 485 $nextrow ? $this->get_link_single_entry($nextrow) : null, 486 ]; 487 } 488 489 /** 490 * Download the data. 491 */ 492 public function download() { 493 \core\session\manager::write_close(); 494 $this->out($this->get_total_responses_count(), false); 495 exit; 496 } 497 498 /** 499 * Take the data returned from the db_query and go through all the rows 500 * processing each col using either col_{columnname} method or other_cols 501 * method or if other_cols returns NULL then put the data straight into the 502 * table. 503 * 504 * This overwrites the parent method because full SQL query may fail on Mysql 505 * because of the limit in the number of tables in the join. Therefore we only 506 * join 59 tables in the main query and add the rest here. 507 * 508 * @return void 509 */ 510 public function build_table() { 511 if ($this->rawdata instanceof \Traversable && !$this->rawdata->valid()) { 512 return; 513 } 514 if (!$this->rawdata) { 515 return; 516 } 517 518 $columnsgroups = []; 519 if ($this->hasmorecolumns) { 520 $items = $this->feedbackstructure->get_items(true); 521 $notretrieveditems = array_slice($items, self::TABLEJOINLIMIT, $this->hasmorecolumns, true); 522 $columnsgroups = array_chunk($notretrieveditems, self::TABLEJOINLIMIT, true); 523 } 524 525 $chunk = []; 526 foreach ($this->rawdata as $row) { 527 if ($this->hasmorecolumns) { 528 $chunk[$row->id] = $row; 529 if (count($chunk) >= self::ROWCHUNKSIZE) { 530 $this->build_table_chunk($chunk, $columnsgroups); 531 $chunk = []; 532 } 533 } else { 534 if ($this->buildforexternal) { 535 $this->add_data_for_external($row); 536 } else { 537 $this->add_data_keyed($this->format_row($row), $this->get_row_class($row)); 538 } 539 } 540 } 541 $this->build_table_chunk($chunk, $columnsgroups); 542 } 543 544 /** 545 * Retrieve additional columns. Database engine may have a limit on number of joins. 546 * 547 * @param array $rows Array of rows with already retrieved data, new values will be added to this array 548 * @param array $columnsgroups array of arrays of columns. Each element has up to self::TABLEJOINLIMIT items. This 549 * is easy to calculate but because we can call this method many times we calculate it once and pass by 550 * reference for performance reasons 551 */ 552 protected function build_table_chunk(&$rows, &$columnsgroups) { 553 global $DB; 554 if (!$rows) { 555 return; 556 } 557 558 foreach ($columnsgroups as $columnsgroup) { 559 $fields = 'c.id'; 560 $from = '{feedback_completed} c'; 561 $params = []; 562 foreach ($columnsgroup as $nr => $item) { 563 $fields .= ", v{$nr}.value AS val{$nr}"; 564 $from .= " LEFT OUTER JOIN {feedback_value} v{$nr} " . 565 "ON v{$nr}.completed = c.id AND v{$nr}.item = :itemid{$nr}"; 566 $params["itemid{$nr}"] = $item->id; 567 } 568 list($idsql, $idparams) = $DB->get_in_or_equal(array_keys($rows), SQL_PARAMS_NAMED); 569 $sql = "SELECT $fields FROM $from WHERE c.id ".$idsql; 570 $results = $DB->get_records_sql($sql, $params + $idparams); 571 foreach ($results as $result) { 572 foreach ($result as $key => $value) { 573 $rows[$result->id]->{$key} = $value; 574 } 575 } 576 } 577 578 foreach ($rows as $row) { 579 if ($this->buildforexternal) { 580 $this->add_data_for_external($row); 581 } else { 582 $this->add_data_keyed($this->format_row($row), $this->get_row_class($row)); 583 } 584 } 585 } 586 587 /** 588 * Returns html code for displaying "Download" button if applicable. 589 */ 590 public function download_buttons() { 591 global $OUTPUT; 592 593 if ($this->is_downloadable() && !$this->is_downloading()) { 594 return $OUTPUT->download_dataformat_selector(get_string('downloadas', 'table'), 595 $this->baseurl->out_omit_querystring(), $this->downloadparamname, $this->baseurl->params()); 596 } else { 597 return ''; 598 } 599 } 600 601 /** 602 * Return user responses data ready for the external function. 603 * 604 * @param stdClass $row the table row containing the responses 605 * @return array returns the responses ready to be used by an external function 606 * @since Moodle 3.3 607 */ 608 protected function get_responses_for_external($row) { 609 $responses = []; 610 foreach ($row as $el => $val) { 611 // Get id from column name. 612 if (preg_match('/^val(\d+)$/', $el, $matches)) { 613 $id = $matches[1]; 614 615 $responses[] = [ 616 'id' => $id, 617 'name' => $this->headers[$this->columns[$el]], 618 'printval' => $this->other_cols($el, $row), 619 'rawval' => $val, 620 ]; 621 } 622 } 623 return $responses; 624 } 625 626 /** 627 * Add data for the external structure that will be returned. 628 * 629 * @param stdClass $row a database query record row 630 * @since Moodle 3.3 631 */ 632 protected function add_data_for_external($row) { 633 $this->dataforexternal[] = [ 634 'id' => $row->id, 635 'courseid' => $row->courseid, 636 'userid' => $row->userid, 637 'fullname' => fullname($row), 638 'timemodified' => $row->completed_timemodified, 639 'responses' => $this->get_responses_for_external($row), 640 ]; 641 } 642 643 /** 644 * Exports the table as an external structure handling pagination. 645 * 646 * @param int $page page number (for pagination) 647 * @param int $perpage elements per page 648 * @since Moodle 3.3 649 * @return array returns the table ready to be used by an external function 650 */ 651 public function export_external_structure($page = 0, $perpage = 0) { 652 653 $this->buildforexternal = true; 654 $this->add_all_values_to_output(); 655 // Set-up. 656 $this->setup(); 657 // Override values, if needed. 658 if ($perpage > 0) { 659 $this->pageable = true; 660 $this->currpage = $page; 661 $this->pagesize = $perpage; 662 } else { 663 $this->pagesize = $this->get_total_responses_count(); 664 } 665 $this->query_db($this->pagesize, false); 666 $this->build_table(); 667 $this->close_recordset(); 668 return $this->dataforexternal; 669 } 670 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body