Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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   * Renderable class for gradehistory report.
  19   *
  20   * @package    gradereport_history
  21   * @copyright  2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  namespace gradereport_history\output;
  26  
  27  defined('MOODLE_INTERNAL') || die;
  28  
  29  require_once($CFG->libdir . '/tablelib.php');
  30  require_once($CFG->dirroot . '/user/lib.php');
  31  
  32  /**
  33   * Renderable class for gradehistory report.
  34   *
  35   * @since      Moodle 2.8
  36   * @package    gradereport_history
  37   * @copyright  2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
  38   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39   */
  40  class tablelog extends \table_sql implements \renderable {
  41  
  42      /**
  43       * @var int course id.
  44       */
  45      protected $courseid;
  46  
  47      /**
  48       * @var \context context of the page to be rendered.
  49       */
  50      protected $context;
  51  
  52      /**
  53       * @var \stdClass A list of filters to be applied to the sql query.
  54       */
  55      protected $filters;
  56  
  57      /**
  58       * @var \stdClass[] List of users included in the report (if userids are specified as filters)
  59       */
  60      protected $users = [];
  61  
  62      /**
  63       * @var array A list of grade items present in the course.
  64       */
  65      protected $gradeitems = array();
  66  
  67      /**
  68       * @var \course_modinfo|null A list of cm instances in course.
  69       */
  70      protected $cms;
  71  
  72      /**
  73       * @var int The default number of decimal points to use in this course
  74       * when a grade item does not itself define the number of decimal points.
  75       */
  76      protected $defaultdecimalpoints;
  77  
  78      /**
  79       * Sets up the table_log parameters.
  80       *
  81       * @param string $uniqueid unique id of table.
  82       * @param \context_course $context Context of the report.
  83       * @param \moodle_url $url url of the page where this table would be displayed.
  84       * @param array $filters options are:
  85       *                          userids : limit to specific users (default: none)
  86       *                          itemid : limit to specific grade item (default: all)
  87       *                          grader : limit to specific graders (default: all)
  88       *                          datefrom : start of date range
  89       *                          datetill : end of date range
  90       *                          revisedonly : only show revised grades (default: false)
  91       *                          format : page | csv | excel (default: page)
  92       * @param string $download Represents download format, pass '' no download at this time.
  93       * @param int $page The current page being displayed.
  94       * @param int $perpage Number of rules to display per page.
  95       */
  96      public function __construct($uniqueid, \context_course $context, $url, $filters = array(), $download = '', $page = 0,
  97                                  $perpage = 100) {
  98          global $CFG;
  99          parent::__construct($uniqueid);
 100  
 101          $this->set_attribute('class', 'gradereport_history generaltable generalbox');
 102  
 103          // Set protected properties.
 104          $this->context = $context;
 105          $this->courseid = $this->context->instanceid;
 106          $this->pagesize = $perpage;
 107          $this->page = $page;
 108          $this->gradeitems = \grade_item::fetch_all(array('courseid' => $this->courseid));
 109          $this->cms = get_fast_modinfo($this->courseid);
 110          $this->useridfield = 'userid';
 111          $this->defaultdecimalpoints = grade_get_setting($this->courseid, 'decimalpoints', $CFG->grade_decimalpoints);
 112  
 113          // Define columns in the table.
 114          $this->define_table_columns();
 115  
 116          // Define filters.
 117          $this->define_table_filters((object) $filters);
 118  
 119          // Define configs.
 120          $this->define_table_configs($url);
 121  
 122          // Set download status.
 123          $this->is_downloading($download, get_string('exportfilename', 'gradereport_history'));
 124      }
 125  
 126      /**
 127       * Define table configs.
 128       *
 129       * @param \moodle_url $url url of the page where this table would be displayed.
 130       */
 131      protected function define_table_configs(\moodle_url $url) {
 132  
 133          // Set table url.
 134          $urlparams = (array)$this->filters;
 135          unset($urlparams['submitbutton']);
 136          unset($urlparams['userfullnames']);
 137          $url->params($urlparams);
 138          $this->define_baseurl($url);
 139  
 140          // Set table configs.
 141          $this->collapsible(true);
 142          $this->sortable(true, 'timemodified', SORT_DESC);
 143          $this->pageable(true);
 144          $this->no_sorting('grader');
 145      }
 146  
 147      /**
 148       * Define table filters
 149       *
 150       * @param \stdClass $filters
 151       */
 152      protected function define_table_filters(\stdClass $filters): void {
 153          global $DB;
 154  
 155          $this->filters = $filters;
 156  
 157          if (!empty($this->filters->userids)) {
 158  
 159              $course = get_course($this->courseid);
 160  
 161              // Retrieve userids that are part of the filters object, and ensure user can access each of them.
 162              [$userselect, $userparams] = $DB->get_in_or_equal(explode(',', $this->filters->userids), SQL_PARAMS_NAMED);
 163              [$usersort] = users_order_by_sql();
 164  
 165              $this->users = array_filter(
 166                  $DB->get_records_select('user', "id {$userselect}", $userparams, $usersort),
 167                  static function(\stdClass $user) use ($course): bool {
 168                      return user_can_view_profile($user, $course);
 169                  }
 170              );
 171  
 172              // Reset userids to the filtered array of users.
 173              $this->filters->userids = implode(',', array_keys($this->users));
 174          }
 175      }
 176  
 177      /**
 178       * Setup the headers for the html table.
 179       */
 180      protected function define_table_columns() {
 181          // TODO Does not support custom user profile fields (MDL-70456).
 182          $extrafields = \core_user\fields::get_identity_fields($this->context, false);
 183  
 184          // Define headers and columns.
 185          $cols = array(
 186              'timemodified' => get_string('datetime', 'gradereport_history'),
 187              'fullname' => get_string('name')
 188          );
 189  
 190          // Add headers for extra user fields.
 191          foreach ($extrafields as $field) {
 192              if (get_string_manager()->string_exists($field, 'moodle')) {
 193                  $cols[$field] = get_string($field);
 194              } else {
 195                  $cols[$field] = $field;
 196              }
 197          }
 198  
 199          // Add remaining headers.
 200          $cols = array_merge($cols, array(
 201              'itemname' => get_string('gradeitem', 'grades'),
 202              'prevgrade' => get_string('gradeold', 'gradereport_history'),
 203              'finalgrade' => get_string('gradenew', 'gradereport_history'),
 204              'grader' => get_string('grader', 'gradereport_history'),
 205              'source' => get_string('source', 'gradereport_history'),
 206              'overridden' => get_string('overridden', 'grades'),
 207              'locked' => get_string('locked', 'grades'),
 208              'excluded' => get_string('excluded', 'gradereport_history'),
 209              'feedback' => get_string('feedbacktext', 'gradereport_history')
 210              )
 211          );
 212  
 213          $this->define_columns(array_keys($cols));
 214          $this->define_headers(array_values($cols));
 215      }
 216  
 217      /**
 218       * Method to display the final grade.
 219       *
 220       * @param \stdClass $history an entry of history record.
 221       *
 222       * @return string HTML to display
 223       */
 224      public function col_finalgrade(\stdClass $history) {
 225          if (!empty($this->gradeitems[$history->itemid])) {
 226              $decimalpoints = $this->gradeitems[$history->itemid]->get_decimals();
 227          } else {
 228              $decimalpoints = $this->defaultdecimalpoints;
 229          }
 230  
 231          return format_float($history->finalgrade, $decimalpoints);
 232      }
 233  
 234      /**
 235       * Method to display the previous grade.
 236       *
 237       * @param \stdClass $history an entry of history record.
 238       *
 239       * @return string HTML to display
 240       */
 241      public function col_prevgrade(\stdClass $history) {
 242          if (!empty($this->gradeitems[$history->itemid])) {
 243              $decimalpoints = $this->gradeitems[$history->itemid]->get_decimals();
 244          } else {
 245              $decimalpoints = $this->defaultdecimalpoints;
 246          }
 247  
 248          return format_float($history->prevgrade, $decimalpoints);
 249      }
 250  
 251      /**
 252       * Method to display column timemodifed.
 253       *
 254       * @param \stdClass $history an entry of history record.
 255       *
 256       * @return string HTML to display
 257       */
 258      public function col_timemodified(\stdClass $history) {
 259          return userdate($history->timemodified);
 260      }
 261  
 262      /**
 263       * Method to display column itemname.
 264       *
 265       * @param \stdClass $history an entry of history record.
 266       *
 267       * @return string HTML to display
 268       */
 269      public function col_itemname(\stdClass $history) {
 270          // Make sure grade item is still present and link it to the module if possible.
 271          $itemid = $history->itemid;
 272          if (!empty($this->gradeitems[$itemid])) {
 273              if ($history->itemtype === 'mod' && !$this->is_downloading()) {
 274                  if (!empty($this->cms->instances[$history->itemmodule][$history->iteminstance])) {
 275                      $cm = $this->cms->instances[$history->itemmodule][$history->iteminstance];
 276                      $url = new \moodle_url('/mod/' . $history->itemmodule . '/view.php', array('id' => $cm->id));
 277                      return \html_writer::link($url, $this->gradeitems[$itemid]->get_name());
 278                  }
 279              }
 280              return $this->gradeitems[$itemid]->get_name();
 281          }
 282          return get_string('deleteditemid', 'gradereport_history', $history->itemid);
 283      }
 284  
 285      /**
 286       * Method to display column grader.
 287       *
 288       * @param \stdClass $history an entry of history record.
 289       *
 290       * @return string HTML to display
 291       */
 292      public function col_grader(\stdClass $history) {
 293          if (empty($history->usermodified)) {
 294              // Not every row has a valid usermodified.
 295              return '';
 296          }
 297  
 298          $grader = new \stdClass();
 299          $grader = username_load_fields_from_object($grader, $history, 'grader');
 300          $name = fullname($grader);
 301  
 302          if ($this->download) {
 303              return $name;
 304          }
 305  
 306          $userid = $history->usermodified;
 307          $profileurl = new \moodle_url('/user/view.php', array('id' => $userid, 'course' => $this->courseid));
 308  
 309          return \html_writer::link($profileurl, $name);
 310      }
 311  
 312      /**
 313       * Method to display column overridden.
 314       *
 315       * @param \stdClass $history an entry of history record.
 316       *
 317       * @return string HTML to display
 318       */
 319      public function col_overridden(\stdClass $history) {
 320          return $history->overridden ? get_string('yes') : get_string('no');
 321      }
 322  
 323      /**
 324       * Method to display column locked.
 325       *
 326       * @param \stdClass $history an entry of history record.
 327       *
 328       * @return string HTML to display
 329       */
 330      public function col_locked(\stdClass $history) {
 331          return $history->locked ? get_string('yes') : get_string('no');
 332      }
 333  
 334      /**
 335       * Method to display column excluded.
 336       *
 337       * @param \stdClass $history an entry of history record.
 338       *
 339       * @return string HTML to display
 340       */
 341      public function col_excluded(\stdClass $history) {
 342          return $history->excluded ? get_string('yes') : get_string('no');
 343      }
 344  
 345      /**
 346       * Method to display column feedback.
 347       *
 348       * @param \stdClass $history an entry of history record.
 349       *
 350       * @return string HTML to display
 351       */
 352      public function col_feedback(\stdClass $history) {
 353          if ($this->is_downloading()) {
 354              return $history->feedback;
 355          } else {
 356              // We need the activity context, not the course context.
 357              $gradeitem = $this->gradeitems[$history->itemid];
 358              $context = $gradeitem->get_context();
 359  
 360              $feedback = file_rewrite_pluginfile_urls(
 361                  $history->feedback,
 362                  'pluginfile.php',
 363                  $context->id,
 364                  GRADE_FILE_COMPONENT,
 365                  GRADE_HISTORY_FEEDBACK_FILEAREA,
 366                  $history->id
 367              );
 368  
 369              return format_text($feedback, $history->feedbackformat, array('context' => $context));
 370          }
 371      }
 372  
 373      /**
 374       * Builds the sql and param list needed, based on the user selected filters.
 375       *
 376       * @return array containing sql to use and an array of params.
 377       */
 378      protected function get_filters_sql_and_params() {
 379          global $DB, $USER;
 380  
 381          $coursecontext = $this->context;
 382          $filter = 'gi.courseid = :courseid';
 383          $params = array(
 384              'courseid' => $coursecontext->instanceid,
 385          );
 386  
 387          if (!empty($this->filters->itemid)) {
 388              $filter .= ' AND ggh.itemid = :itemid';
 389              $params['itemid'] = $this->filters->itemid;
 390          }
 391          if (!empty($this->filters->userids)) {
 392              $list = explode(',', $this->filters->userids);
 393              list($insql, $plist) = $DB->get_in_or_equal($list, SQL_PARAMS_NAMED);
 394              $filter .= " AND ggh.userid $insql";
 395              $params += $plist;
 396          }
 397          if (!empty($this->filters->datefrom)) {
 398              $filter .= " AND ggh.timemodified >= :datefrom";
 399              $params += array('datefrom' => $this->filters->datefrom);
 400          }
 401          if (!empty($this->filters->datetill)) {
 402              $filter .= " AND ggh.timemodified <= :datetill";
 403              $params += array('datetill' => $this->filters->datetill);
 404          }
 405          if (!empty($this->filters->grader)) {
 406              $filter .= " AND ggh.usermodified = :grader";
 407              $params += array('grader' => $this->filters->grader);
 408          }
 409  
 410          // If the course is separate group mode and the current user is not allowed to see all groups make sure
 411          // that we display only users from the same groups as current user.
 412          $groupmode = get_course($coursecontext->instanceid)->groupmode;
 413          if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $coursecontext)) {
 414              $groupids = array_column(groups_get_all_groups($coursecontext->instanceid, $USER->id, 0, 'g.id'), 'id');
 415              list($gsql, $gparams) = $DB->get_in_or_equal($groupids, SQL_PARAMS_NAMED, 'gmuparam', true, 0);
 416              $filter .= " AND EXISTS (SELECT 1 FROM {groups_members} gmu WHERE gmu.userid=ggh.userid AND gmu.groupid $gsql)";
 417              $params += $gparams;
 418          }
 419  
 420          return array($filter, $params);
 421      }
 422  
 423      /**
 424       * Builds the complete sql with all the joins to get the grade history data.
 425       *
 426       * @param bool $count setting this to true, returns an sql to get count only instead of the complete data records.
 427       *
 428       * @return array containing sql to use and an array of params.
 429       */
 430      protected function get_sql_and_params($count = false) {
 431          $fields = 'ggh.id, ggh.timemodified, ggh.itemid, ggh.userid, ggh.finalgrade, ggh.usermodified,
 432                     ggh.source, ggh.overridden, ggh.locked, ggh.excluded, ggh.feedback, ggh.feedbackformat,
 433                     gi.itemtype, gi.itemmodule, gi.iteminstance, gi.itemnumber, ';
 434  
 435          // Add extra user fields that we need for the graded user.
 436          // TODO Does not support custom user profile fields (MDL-70456).
 437          $extrafields = \core_user\fields::get_identity_fields($this->context, false);
 438          foreach ($extrafields as $field) {
 439              $fields .= 'u.' . $field . ', ';
 440          }
 441          $userfieldsapi = \core_user\fields::for_name();
 442          $gradeduserfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 443          $fields .= $gradeduserfields . ', ';
 444          $groupby = $fields;
 445  
 446          // Add extra user fields that we need for the grader user.
 447          $fields .= $userfieldsapi->get_sql('ug', false, 'grader', '', false)->selects;
 448          $groupby .= $userfieldsapi->get_sql('ug', false, '', '', false)->selects;
 449  
 450          // Filtering on revised grades only.
 451          $revisedonly = !empty($this->filters->revisedonly);
 452  
 453          if ($count && !$revisedonly) {
 454              // We can only directly use count when not using the filter revised only.
 455              $select = "COUNT(1)";
 456          } else {
 457              // Fetching the previous grade. We use MAX() to ensure that we only get one result if
 458              // more than one histories happened at the same second.
 459              $prevgrade = "SELECT MAX(finalgrade)
 460                              FROM {grade_grades_history} h
 461                             WHERE h.itemid = ggh.itemid
 462                               AND h.userid = ggh.userid
 463                               AND h.timemodified < ggh.timemodified
 464                               AND NOT EXISTS (
 465                                SELECT 1
 466                                  FROM {grade_grades_history} h2
 467                                 WHERE h2.itemid = ggh.itemid
 468                                   AND h2.userid = ggh.userid
 469                                   AND h2.timemodified < ggh.timemodified
 470                                   AND h.timemodified < h2.timemodified)";
 471  
 472              $select = "$fields, ($prevgrade) AS prevgrade,
 473                        CASE WHEN gi.itemname IS NULL THEN gi.itemtype ELSE gi.itemname END AS itemname";
 474          }
 475  
 476          list($where, $params) = $this->get_filters_sql_and_params();
 477  
 478          $sql =  "SELECT $select
 479                     FROM {grade_grades_history} ggh
 480                     JOIN {grade_items} gi ON gi.id = ggh.itemid
 481                     JOIN {user} u ON u.id = ggh.userid
 482                LEFT JOIN {user} ug ON ug.id = ggh.usermodified
 483                    WHERE $where";
 484  
 485          // As prevgrade is a dynamic field, we need to wrap the query. This is the only filtering
 486          // that should be defined outside the method self::get_filters_sql_and_params().
 487          if ($revisedonly) {
 488              $allorcount = $count ? 'COUNT(1)' : '*';
 489              $sql = "SELECT $allorcount FROM ($sql) pg
 490                       WHERE pg.finalgrade != pg.prevgrade
 491                          OR (pg.prevgrade IS NULL AND pg.finalgrade IS NOT NULL)
 492                          OR (pg.prevgrade IS NOT NULL AND pg.finalgrade IS NULL)";
 493          }
 494  
 495          // Add order by if needed.
 496          if (!$count && $sqlsort = $this->get_sql_sort()) {
 497              $sql .= " ORDER BY " . $sqlsort;
 498          }
 499  
 500          return array($sql, $params);
 501      }
 502  
 503      /**
 504       * Get the SQL fragment to sort by.
 505       *
 506       * This is overridden to sort by timemodified and ID by default. Many items happen at the same time
 507       * and a second sorting by ID is valuable to distinguish the order in which the history happened.
 508       *
 509       * @return string SQL fragment.
 510       */
 511      public function get_sql_sort() {
 512          $columns = $this->get_sort_columns();
 513          if (count($columns) == 1 && isset($columns['timemodified']) && $columns['timemodified'] == SORT_DESC) {
 514              // Add the 'id' column when we are using the default sorting.
 515              $columns['id'] = SORT_DESC;
 516              return self::construct_order_by($columns);
 517          }
 518          return parent::get_sql_sort();
 519      }
 520  
 521      /**
 522       * Query the reader. Store results in the object for use by build_table.
 523       *
 524       * @param int $pagesize size of page for paginated displayed table.
 525       * @param bool $useinitialsbar do you want to use the initials bar.
 526       */
 527      public function query_db($pagesize, $useinitialsbar = true) {
 528          global $DB;
 529  
 530          list($countsql, $countparams) = $this->get_sql_and_params(true);
 531          list($sql, $params) = $this->get_sql_and_params();
 532          $total = $DB->count_records_sql($countsql, $countparams);
 533          $this->pagesize($pagesize, $total);
 534          if ($this->is_downloading()) {
 535              $histories = $DB->get_records_sql($sql, $params);
 536          } else {
 537              $histories = $DB->get_records_sql($sql, $params, $this->pagesize * $this->page, $this->pagesize);
 538          }
 539          foreach ($histories as $history) {
 540              $this->rawdata[] = $history;
 541          }
 542          // Set initial bars.
 543          if ($useinitialsbar) {
 544              $this->initialbars($total > $pagesize);
 545          }
 546      }
 547  
 548      /**
 549       * Returns a list of selected users.
 550       *
 551       * @return \stdClass[] List of user objects
 552       */
 553      public function get_selected_users(): array {
 554          return $this->users;
 555      }
 556  }