[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/mod/quiz/report/ -> attemptsreport_table.php (source)

   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   * Base class for the table used by a {@link quiz_attempts_report}.
  19   *
  20   * @package   mod_quiz
  21   * @copyright 2010 The Open University
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  require_once($CFG->libdir.'/tablelib.php');
  29  
  30  
  31  /**
  32   * Base class for the table used by a {@link quiz_attempts_report}.
  33   *
  34   * @copyright 2010 The Open University
  35   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  abstract class quiz_attempts_report_table extends table_sql {
  38      public $useridfield = 'userid';
  39  
  40      /** @var moodle_url the URL of this report. */
  41      protected $reporturl;
  42  
  43      /** @var array the display options. */
  44      protected $displayoptions;
  45  
  46      /**
  47       * @var array information about the latest step of each question.
  48       * Loaded by {@link load_question_latest_steps()}, if applicable.
  49       */
  50      protected $lateststeps = null;
  51  
  52      /** @var object the quiz settings for the quiz we are reporting on. */
  53      protected $quiz;
  54  
  55      /** @var context the quiz context. */
  56      protected $context;
  57  
  58      /** @var string HTML fragment to select the first/best/last attempt, if appropriate. */
  59      protected $qmsubselect;
  60  
  61      /** @var object mod_quiz_attempts_report_options the options affecting this report. */
  62      protected $options;
  63  
  64      /** @var object the ids of the students in the currently selected group, if applicable. */
  65      protected $groupstudents;
  66  
  67      /** @var object the ids of the students in the course. */
  68      protected $students;
  69  
  70      /** @var object the questions that comprise this quiz.. */
  71      protected $questions;
  72  
  73      /** @var bool whether to include the column with checkboxes to select each attempt. */
  74      protected $includecheckboxes;
  75  
  76      /**
  77       * Constructor
  78       * @param string $uniqueid
  79       * @param object $quiz
  80       * @param context $context
  81       * @param string $qmsubselect
  82       * @param mod_quiz_attempts_report_options $options
  83       * @param array $groupstudents
  84       * @param array $students
  85       * @param array $questions
  86       * @param moodle_url $reporturl
  87       */
  88      public function __construct($uniqueid, $quiz, $context, $qmsubselect,
  89              mod_quiz_attempts_report_options $options, $groupstudents, $students,
  90              $questions, $reporturl) {
  91          parent::__construct($uniqueid);
  92          $this->quiz = $quiz;
  93          $this->context = $context;
  94          $this->qmsubselect = $qmsubselect;
  95          $this->groupstudents = $groupstudents;
  96          $this->students = $students;
  97          $this->questions = $questions;
  98          $this->includecheckboxes = $options->checkboxcolumn;
  99          $this->reporturl = $reporturl;
 100          $this->options = $options;
 101      }
 102  
 103      /**
 104       * Generate the display of the checkbox column.
 105       * @param object $attempt the table row being output.
 106       * @return string HTML content to go inside the td.
 107       */
 108      public function col_checkbox($attempt) {
 109          if ($attempt->attempt) {
 110              return '<input type="checkbox" name="attemptid[]" value="'.$attempt->attempt.'" />';
 111          } else {
 112              return '';
 113          }
 114      }
 115  
 116      /**
 117       * Generate the display of the user's picture column.
 118       * @param object $attempt the table row being output.
 119       * @return string HTML content to go inside the td.
 120       */
 121      public function col_picture($attempt) {
 122          global $OUTPUT;
 123          $user = new stdClass();
 124          $additionalfields = explode(',', user_picture::fields());
 125          $user = username_load_fields_from_object($user, $attempt, null, $additionalfields);
 126          $user->id = $attempt->userid;
 127          return $OUTPUT->user_picture($user);
 128      }
 129  
 130      /**
 131       * Generate the display of the user's full name column.
 132       * @param object $attempt the table row being output.
 133       * @return string HTML content to go inside the td.
 134       */
 135      public function col_fullname($attempt) {
 136          $html = parent::col_fullname($attempt);
 137          if ($this->is_downloading() || empty($attempt->attempt)) {
 138              return $html;
 139          }
 140  
 141          return $html . html_writer::empty_tag('br') . html_writer::link(
 142                  new moodle_url('/mod/quiz/review.php', array('attempt' => $attempt->attempt)),
 143                  get_string('reviewattempt', 'quiz'), array('class' => 'reviewlink'));
 144      }
 145  
 146      /**
 147       * Generate the display of the attempt state column.
 148       * @param object $attempt the table row being output.
 149       * @return string HTML content to go inside the td.
 150       */
 151      public function col_state($attempt) {
 152          if (!is_null($attempt->attempt)) {
 153              return quiz_attempt::state_name($attempt->state);
 154          } else {
 155              return  '-';
 156          }
 157      }
 158  
 159      /**
 160       * Generate the display of the start time column.
 161       * @param object $attempt the table row being output.
 162       * @return string HTML content to go inside the td.
 163       */
 164      public function col_timestart($attempt) {
 165          if ($attempt->attempt) {
 166              return userdate($attempt->timestart, $this->strtimeformat);
 167          } else {
 168              return  '-';
 169          }
 170      }
 171  
 172      /**
 173       * Generate the display of the finish time column.
 174       * @param object $attempt the table row being output.
 175       * @return string HTML content to go inside the td.
 176       */
 177      public function col_timefinish($attempt) {
 178          if ($attempt->attempt && $attempt->timefinish) {
 179              return userdate($attempt->timefinish, $this->strtimeformat);
 180          } else {
 181              return  '-';
 182          }
 183      }
 184  
 185      /**
 186       * Generate the display of the time taken column.
 187       * @param object $attempt the table row being output.
 188       * @return string HTML content to go inside the td.
 189       */
 190      public function col_duration($attempt) {
 191          if ($attempt->timefinish) {
 192              return format_time($attempt->timefinish - $attempt->timestart);
 193          } else {
 194              return '-';
 195          }
 196      }
 197  
 198      /**
 199       * Generate the display of the feedback column.
 200       * @param object $attempt the table row being output.
 201       * @return string HTML content to go inside the td.
 202       */
 203      public function col_feedbacktext($attempt) {
 204          if ($attempt->state != quiz_attempt::FINISHED) {
 205              return '-';
 206          }
 207  
 208          $feedback = quiz_report_feedback_for_grade(
 209                  quiz_rescale_grade($attempt->sumgrades, $this->quiz, false),
 210                  $this->quiz->id, $this->context);
 211  
 212          if ($this->is_downloading()) {
 213              $feedback = strip_tags($feedback);
 214          }
 215  
 216          return $feedback;
 217      }
 218  
 219      public function get_row_class($attempt) {
 220          if ($this->qmsubselect && $attempt->gradedattempt) {
 221              return 'gradedattempt';
 222          } else {
 223              return '';
 224          }
 225      }
 226  
 227      /**
 228       * Make a link to review an individual question in a popup window.
 229       *
 230       * @param string $data HTML fragment. The text to make into the link.
 231       * @param object $attempt data for the row of the table being output.
 232       * @param int $slot the number used to identify this question within this usage.
 233       */
 234      public function make_review_link($data, $attempt, $slot) {
 235          global $OUTPUT;
 236  
 237          $flag = '';
 238          if ($this->is_flagged($attempt->usageid, $slot)) {
 239              $flag = $OUTPUT->pix_icon('i/flagged', get_string('flagged', 'question'),
 240                      'moodle', array('class' => 'questionflag'));
 241          }
 242  
 243          $feedbackimg = '';
 244          $state = $this->slot_state($attempt, $slot);
 245          if ($state->is_finished() && $state != question_state::$needsgrading) {
 246              $feedbackimg = $this->icon_for_fraction($this->slot_fraction($attempt, $slot));
 247          }
 248  
 249          $output = html_writer::tag('span', $feedbackimg . html_writer::tag('span',
 250                  $data, array('class' => $state->get_state_class(true))) . $flag, array('class' => 'que'));
 251  
 252          $reviewparams = array('attempt' => $attempt->attempt, 'slot' => $slot);
 253          if (isset($attempt->try)) {
 254              $reviewparams['step'] = $this->step_no_for_try($attempt->usageid, $slot, $attempt->try);
 255          }
 256          $url = new moodle_url('/mod/quiz/reviewquestion.php', $reviewparams);
 257          $output = $OUTPUT->action_link($url, $output,
 258                  new popup_action('click', $url, 'reviewquestion',
 259                          array('height' => 450, 'width' => 650)),
 260                  array('title' => get_string('reviewresponse', 'quiz')));
 261  
 262          return $output;
 263      }
 264  
 265      /**
 266       * @param object $attempt the row data
 267       * @param int $slot
 268       * @return question_state
 269       */
 270      protected function slot_state($attempt, $slot) {
 271          $stepdata = $this->lateststeps[$attempt->usageid][$slot];
 272          return question_state::get($stepdata->state);
 273      }
 274  
 275      /**
 276       * @param int $questionusageid
 277       * @param int $slot
 278       * @return bool
 279       */
 280      protected function is_flagged($questionusageid, $slot) {
 281          $stepdata = $this->lateststeps[$questionusageid][$slot];
 282          return $stepdata->flagged;
 283      }
 284  
 285  
 286      /**
 287       * @param object $attempt the row data
 288       * @param int $slot
 289       * @return float
 290       */
 291      protected function slot_fraction($attempt, $slot) {
 292          $stepdata = $this->lateststeps[$attempt->usageid][$slot];
 293          return $stepdata->fraction;
 294      }
 295  
 296      /**
 297       * Return an appropriate icon (green tick, red cross, etc.) for a grade.
 298       * @param float $fraction grade on a scale 0..1.
 299       * @return string html fragment.
 300       */
 301      protected function icon_for_fraction($fraction) {
 302          global $OUTPUT;
 303  
 304          $feedbackclass = question_state::graded_state_for_fraction($fraction)->get_feedback_class();
 305          return $OUTPUT->pix_icon('i/grade_' . $feedbackclass, get_string($feedbackclass, 'question'),
 306                  'moodle', array('class' => 'icon'));
 307      }
 308  
 309      /**
 310       * Load any extra data after main query. At this point you can call {@link get_qubaids_condition} to get the condition that
 311       * limits the query to just the question usages shown in this report page or alternatively for all attempts if downloading a
 312       * full report.
 313       */
 314      protected function load_extra_data() {
 315          $this->lateststeps = $this->load_question_latest_steps();
 316      }
 317  
 318      /**
 319       * Load information about the latest state of selected questions in selected attempts.
 320       *
 321       * The results are returned as an two dimensional array $qubaid => $slot => $dataobject
 322       *
 323       * @param qubaid_condition|null $qubaids used to restrict which usages are included
 324       * in the query. See {@link qubaid_condition}.
 325       * @return array of records. See the SQL in this function to see the fields available.
 326       */
 327      protected function load_question_latest_steps(qubaid_condition $qubaids = null) {
 328          if ($qubaids === null) {
 329              $qubaids = $this->get_qubaids_condition();
 330          }
 331          $dm = new question_engine_data_mapper();
 332          $latesstepdata = $dm->load_questions_usages_latest_steps(
 333                  $qubaids, array_keys($this->questions));
 334  
 335          $lateststeps = array();
 336          foreach ($latesstepdata as $step) {
 337              $lateststeps[$step->questionusageid][$step->slot] = $step;
 338          }
 339  
 340          return $lateststeps;
 341      }
 342  
 343      /**
 344       * Does this report require loading any more data after the main query. After the main query then
 345       * you can use $this->get
 346       *
 347       * @return bool should {@link query_db()} call {@link load_extra_data}?
 348       */
 349      protected function requires_extra_data() {
 350          return $this->requires_latest_steps_loaded();
 351      }
 352  
 353      /**
 354       * Does this report require the detailed information for each question from the
 355       * question_attempts_steps table?
 356       * @return bool should {@link load_extra_data} call {@link load_question_latest_steps}?
 357       */
 358      protected function requires_latest_steps_loaded() {
 359          return false;
 360      }
 361  
 362      /**
 363       * Is this a column that depends on joining to the latest state information?
 364       * If so, return the corresponding slot. If not, return false.
 365       * @param string $column a column name
 366       * @return int false if no, else a slot.
 367       */
 368      protected function is_latest_step_column($column) {
 369          return false;
 370      }
 371  
 372      /**
 373       * Get any fields that might be needed when sorting on date for a particular slot.
 374       * @param int $slot the slot for the column we want.
 375       * @param string $alias the table alias for latest state information relating to that slot.
 376       */
 377      protected function get_required_latest_state_fields($slot, $alias) {
 378          return '';
 379      }
 380  
 381      /**
 382       * Contruct all the parts of the main database query.
 383       * @param array $reportstudents list if userids of users to include in the report.
 384       * @return array with 4 elements ($fields, $from, $where, $params) that can be used to
 385       *      build the actual database query.
 386       */
 387      public function base_sql($reportstudents) {
 388          global $DB;
 389  
 390          $fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') . ' AS uniqueid,';
 391  
 392          if ($this->qmsubselect) {
 393              $fields .= "\n(CASE WHEN $this->qmsubselect THEN 1 ELSE 0 END) AS gradedattempt,";
 394          }
 395  
 396          $extrafields = get_extra_user_fields_sql($this->context, 'u', '',
 397                  array('id', 'idnumber', 'firstname', 'lastname', 'picture',
 398                  'imagealt', 'institution', 'department', 'email'));
 399          $allnames = get_all_user_name_fields(true, 'u');
 400          $fields .= '
 401                  quiza.uniqueid AS usageid,
 402                  quiza.id AS attempt,
 403                  u.id AS userid,
 404                  u.idnumber, ' . $allnames . ',
 405                  u.picture,
 406                  u.imagealt,
 407                  u.institution,
 408                  u.department,
 409                  u.email' . $extrafields . ',
 410                  quiza.state,
 411                  quiza.sumgrades,
 412                  quiza.timefinish,
 413                  quiza.timestart,
 414                  CASE WHEN quiza.timefinish = 0 THEN null
 415                       WHEN quiza.timefinish > quiza.timestart THEN quiza.timefinish - quiza.timestart
 416                       ELSE 0 END AS duration';
 417              // To explain that last bit, timefinish can be non-zero and less
 418              // than timestart when you have two load-balanced servers with very
 419              // badly synchronised clocks, and a student does a really quick attempt.
 420  
 421          // This part is the same for all cases. Join the users and quiz_attempts tables.
 422          $from = "\n{user} u";
 423          $from .= "\nLEFT JOIN {quiz_attempts} quiza ON
 424                                      quiza.userid = u.id AND quiza.quiz = :quizid";
 425          $params = array('quizid' => $this->quiz->id);
 426  
 427          if ($this->qmsubselect && $this->options->onlygraded) {
 428              $from .= " AND (quiza.state <> :finishedstate OR $this->qmsubselect)";
 429              $params['finishedstate'] = quiz_attempt::FINISHED;
 430          }
 431  
 432          switch ($this->options->attempts) {
 433              case quiz_attempts_report::ALL_WITH:
 434                  // Show all attempts, including students who are no longer in the course.
 435                  $where = 'quiza.id IS NOT NULL AND quiza.preview = 0';
 436                  break;
 437              case quiz_attempts_report::ENROLLED_WITH:
 438                  // Show only students with attempts.
 439                  list($usql, $uparams) = $DB->get_in_or_equal(
 440                          $reportstudents, SQL_PARAMS_NAMED, 'u');
 441                  $params += $uparams;
 442                  $where = "u.id $usql AND quiza.preview = 0 AND quiza.id IS NOT NULL";
 443                  break;
 444              case quiz_attempts_report::ENROLLED_WITHOUT:
 445                  // Show only students without attempts.
 446                  list($usql, $uparams) = $DB->get_in_or_equal(
 447                          $reportstudents, SQL_PARAMS_NAMED, 'u');
 448                  $params += $uparams;
 449                  $where = "u.id $usql AND quiza.id IS NULL";
 450                  break;
 451              case quiz_attempts_report::ENROLLED_ALL:
 452                  // Show all students with or without attempts.
 453                  list($usql, $uparams) = $DB->get_in_or_equal(
 454                          $reportstudents, SQL_PARAMS_NAMED, 'u');
 455                  $params += $uparams;
 456                  $where = "u.id $usql AND (quiza.preview = 0 OR quiza.preview IS NULL)";
 457                  break;
 458          }
 459  
 460          if ($this->options->states) {
 461              list($statesql, $stateparams) = $DB->get_in_or_equal($this->options->states,
 462                      SQL_PARAMS_NAMED, 'state');
 463              $params += $stateparams;
 464              $where .= " AND (quiza.state $statesql OR quiza.state IS NULL)";
 465          }
 466  
 467          return array($fields, $from, $where, $params);
 468      }
 469  
 470      /**
 471       * Add the information about the latest state of the question with slot
 472       * $slot to the query.
 473       *
 474       * The extra information is added as a join to a
 475       * 'table' with alias qa$slot, with columns that are a union of
 476       * the columns of the question_attempts and question_attempts_states tables.
 477       *
 478       * @param int $slot the question to add information for.
 479       */
 480      protected function add_latest_state_join($slot) {
 481          $alias = 'qa' . $slot;
 482  
 483          $fields = $this->get_required_latest_state_fields($slot, $alias);
 484          if (!$fields) {
 485              return;
 486          }
 487  
 488          // This condition roughly filters the list of attempts to be considered.
 489          // It is only used in a subselect to help crappy databases (see MDL-30122)
 490          // therefore, it is better to use a very simple join, which may include
 491          // too many records, than to do a super-accurate join.
 492          $qubaids = new qubaid_join("{quiz_attempts} {$alias}quiza", "{$alias}quiza.uniqueid",
 493                  "{$alias}quiza.quiz = :{$alias}quizid", array("{$alias}quizid" => $this->sql->params['quizid']));
 494  
 495          $dm = new question_engine_data_mapper();
 496          list($inlineview, $viewparams) = $dm->question_attempt_latest_state_view($alias, $qubaids);
 497  
 498          $this->sql->fields .= ",\n$fields";
 499          $this->sql->from .= "\nLEFT JOIN $inlineview ON " .
 500                  "$alias.questionusageid = quiza.uniqueid AND $alias.slot = :{$alias}slot";
 501          $this->sql->params[$alias . 'slot'] = $slot;
 502          $this->sql->params = array_merge($this->sql->params, $viewparams);
 503      }
 504  
 505      /**
 506       * Get an appropriate qubaid_condition for loading more data about the
 507       * attempts we are displaying.
 508       * @return qubaid_condition
 509       */
 510      protected function get_qubaids_condition() {
 511          if (is_null($this->rawdata)) {
 512              throw new coding_exception(
 513                      'Cannot call get_qubaids_condition until the main data has been loaded.');
 514          }
 515  
 516          if ($this->is_downloading()) {
 517              // We want usages for all attempts.
 518              return new qubaid_join($this->sql->from, 'quiza.uniqueid',
 519                      $this->sql->where, $this->sql->params);
 520          }
 521  
 522          $qubaids = array();
 523          foreach ($this->rawdata as $attempt) {
 524              if ($attempt->usageid > 0) {
 525                  $qubaids[] = $attempt->usageid;
 526              }
 527          }
 528  
 529          return new qubaid_list($qubaids);
 530      }
 531  
 532      public function query_db($pagesize, $useinitialsbar = true) {
 533          $doneslots = array();
 534          foreach ($this->get_sort_columns() as $column => $notused) {
 535              $slot = $this->is_latest_step_column($column);
 536              if ($slot && !in_array($slot, $doneslots)) {
 537                  $this->add_latest_state_join($slot);
 538                  $doneslots[] = $slot;
 539              }
 540          }
 541  
 542          parent::query_db($pagesize, $useinitialsbar);
 543  
 544          if ($this->requires_extra_data()) {
 545              $this->load_extra_data();
 546          }
 547      }
 548  
 549      public function get_sort_columns() {
 550          // Add attemptid as a final tie-break to the sort. This ensures that
 551          // Attempts by the same student appear in order when just sorting by name.
 552          $sortcolumns = parent::get_sort_columns();
 553          $sortcolumns['quiza.id'] = SORT_ASC;
 554          return $sortcolumns;
 555      }
 556  
 557      public function wrap_html_start() {
 558          if ($this->is_downloading() || !$this->includecheckboxes) {
 559              return;
 560          }
 561  
 562          $url = $this->options->get_url();
 563          $url->param('sesskey', sesskey());
 564  
 565          echo '<div id="tablecontainer">';
 566          echo '<form id="attemptsform" method="post" action="' . $url->out_omit_querystring() . '">';
 567  
 568          echo html_writer::input_hidden_params($url);
 569          echo '<div>';
 570      }
 571  
 572      public function wrap_html_finish() {
 573          if ($this->is_downloading() || !$this->includecheckboxes) {
 574              return;
 575          }
 576  
 577          echo '<div id="commands">';
 578          echo '<a href="javascript:select_all_in(\'DIV\', null, \'tablecontainer\');">' .
 579                  get_string('selectall', 'quiz') . '</a> / ';
 580          echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'tablecontainer\');">' .
 581                  get_string('selectnone', 'quiz') . '</a> ';
 582          echo '&nbsp;&nbsp;';
 583          $this->submit_buttons();
 584          echo '</div>';
 585  
 586          // Close the form.
 587          echo '</div>';
 588          echo '</form></div>';
 589      }
 590  
 591      /**
 592       * Output any submit buttons required by the $this->includecheckboxes form.
 593       */
 594      protected function submit_buttons() {
 595          global $PAGE;
 596          if (has_capability('mod/quiz:deleteattempts', $this->context)) {
 597              echo '<input type="submit" id="deleteattemptsbutton" name="delete" value="' .
 598                      get_string('deleteselected', 'quiz_overview') . '"/>';
 599              $PAGE->requires->event_handler('#deleteattemptsbutton', 'click', 'M.util.show_confirm_dialog',
 600                      array('message' => get_string('deleteattemptcheck', 'quiz')));
 601          }
 602      }
 603  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1