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 38 and 311] [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   * Definition of the grade_user_report class is defined
  19   *
  20   * @package gradereport_user
  21   * @copyright 2007 Nicolas Connault
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  require_once($CFG->dirroot . '/grade/report/lib.php');
  26  require_once($CFG->libdir.'/tablelib.php');
  27  
  28  //showhiddenitems values
  29  define("GRADE_REPORT_USER_HIDE_HIDDEN", 0);
  30  define("GRADE_REPORT_USER_HIDE_UNTIL", 1);
  31  define("GRADE_REPORT_USER_SHOW_HIDDEN", 2);
  32  
  33  define("GRADE_REPORT_USER_VIEW_SELF", 1);
  34  define("GRADE_REPORT_USER_VIEW_USER", 2);
  35  
  36  /**
  37   * Class providing an API for the user report building and displaying.
  38   * @uses grade_report
  39   * @package gradereport_user
  40   */
  41  class grade_report_user extends grade_report {
  42  
  43      /**
  44       * The user.
  45       * @var object $user
  46       */
  47      public $user;
  48  
  49      /**
  50       * A flexitable to hold the data.
  51       * @var object $table
  52       */
  53      public $table;
  54  
  55      /**
  56       * An array of table headers
  57       * @var array
  58       */
  59      public $tableheaders = array();
  60  
  61      /**
  62       * An array of table columns
  63       * @var array
  64       */
  65      public $tablecolumns = array();
  66  
  67      /**
  68       * An array containing rows of data for the table.
  69       * @var type
  70       */
  71      public $tabledata = array();
  72  
  73      /**
  74       * An array containing the grade items data for external usage (web services, ajax, etc...)
  75       * @var array
  76       */
  77      public $gradeitemsdata = array();
  78  
  79      /**
  80       * The grade tree structure
  81       * @var grade_tree
  82       */
  83      public $gtree;
  84  
  85      /**
  86       * Flat structure similar to grade tree
  87       */
  88      public $gseq;
  89  
  90      /**
  91       * show student ranks
  92       */
  93      public $showrank;
  94  
  95      /**
  96       * show grade percentages
  97       */
  98      public $showpercentage;
  99  
 100      /**
 101       * Show range
 102       */
 103      public $showrange = true;
 104  
 105      /**
 106       * Show grades in the report, default true
 107       * @var bool
 108       */
 109      public $showgrade = true;
 110  
 111      /**
 112       * Decimal points to use for values in the report, default 2
 113       * @var int
 114       */
 115      public $decimals = 2;
 116  
 117      /**
 118       * The number of decimal places to round range to, default 0
 119       * @var int
 120       */
 121      public $rangedecimals = 0;
 122  
 123      /**
 124       * Show grade feedback in the report, default true
 125       * @var bool
 126       */
 127      public $showfeedback = true;
 128  
 129      /**
 130       * Show grade weighting in the report, default true.
 131       * @var bool
 132       */
 133      public $showweight = true;
 134  
 135      /**
 136       * Show letter grades in the report, default false
 137       * @var bool
 138       */
 139      public $showlettergrade = false;
 140  
 141      /**
 142       * Show the calculated contribution to the course total column.
 143       * @var bool
 144       */
 145      public $showcontributiontocoursetotal = true;
 146  
 147      /**
 148       * Show average grades in the report, default false.
 149       * @var false
 150       */
 151      public $showaverage = false;
 152  
 153      public $maxdepth;
 154      public $evenodd;
 155  
 156      public $canviewhidden;
 157  
 158      public $switch;
 159  
 160      /**
 161       * Show hidden items even when user does not have required cap
 162       */
 163      public $showhiddenitems;
 164      public $showtotalsifcontainhidden;
 165  
 166      public $baseurl;
 167      public $pbarurl;
 168  
 169      /**
 170       * The modinfo object to be used.
 171       *
 172       * @var course_modinfo
 173       */
 174      protected $modinfo = null;
 175  
 176      /**
 177       * View as user.
 178       *
 179       * When this is set to true, the visibility checks, and capability checks will be
 180       * applied to the user whose grades are being displayed. This is very useful when
 181       * a mentor/parent is viewing the report of their mentee because they need to have
 182       * access to the same information, but not more, not less.
 183       *
 184       * @var boolean
 185       */
 186      protected $viewasuser = false;
 187  
 188      /**
 189       * An array that collects the aggregationhints for every
 190       * grade_item. The hints contain grade, grademin, grademax
 191       * status, weight and parent.
 192       *
 193       * @var array
 194       */
 195      protected $aggregationhints = array();
 196  
 197      /**
 198       * Constructor. Sets local copies of user preferences and initialises grade_tree.
 199       * @param int $courseid
 200       * @param object $gpr grade plugin return tracking object
 201       * @param string $context
 202       * @param int $userid The id of the user
 203       * @param bool $viewasuser Set this to true when the current user is a mentor/parent of the targetted user.
 204       */
 205      public function __construct($courseid, $gpr, $context, $userid, $viewasuser = null) {
 206          global $DB, $CFG;
 207          parent::__construct($courseid, $gpr, $context);
 208  
 209          $this->showrank        = grade_get_setting($this->courseid, 'report_user_showrank', $CFG->grade_report_user_showrank);
 210          $this->showpercentage  = grade_get_setting($this->courseid, 'report_user_showpercentage', $CFG->grade_report_user_showpercentage);
 211          $this->showhiddenitems = grade_get_setting($this->courseid, 'report_user_showhiddenitems', $CFG->grade_report_user_showhiddenitems);
 212          $this->showtotalsifcontainhidden = array($this->courseid => grade_get_setting($this->courseid, 'report_user_showtotalsifcontainhidden', $CFG->grade_report_user_showtotalsifcontainhidden));
 213  
 214          $this->showgrade       = grade_get_setting($this->courseid, 'report_user_showgrade',       !empty($CFG->grade_report_user_showgrade));
 215          $this->showrange       = grade_get_setting($this->courseid, 'report_user_showrange',       !empty($CFG->grade_report_user_showrange));
 216          $this->showfeedback    = grade_get_setting($this->courseid, 'report_user_showfeedback',    !empty($CFG->grade_report_user_showfeedback));
 217  
 218          $this->showweight = grade_get_setting($this->courseid, 'report_user_showweight',
 219              !empty($CFG->grade_report_user_showweight));
 220  
 221          $this->showcontributiontocoursetotal = grade_get_setting($this->courseid, 'report_user_showcontributiontocoursetotal',
 222              !empty($CFG->grade_report_user_showcontributiontocoursetotal));
 223  
 224          $this->showlettergrade = grade_get_setting($this->courseid, 'report_user_showlettergrade', !empty($CFG->grade_report_user_showlettergrade));
 225          $this->showaverage     = grade_get_setting($this->courseid, 'report_user_showaverage',     !empty($CFG->grade_report_user_showaverage));
 226  
 227          $this->viewasuser = $viewasuser;
 228  
 229          // The default grade decimals is 2
 230          $defaultdecimals = 2;
 231          if (property_exists($CFG, 'grade_decimalpoints')) {
 232              $defaultdecimals = $CFG->grade_decimalpoints;
 233          }
 234          $this->decimals = grade_get_setting($this->courseid, 'decimalpoints', $defaultdecimals);
 235  
 236          // The default range decimals is 0
 237          $defaultrangedecimals = 0;
 238          if (property_exists($CFG, 'grade_report_user_rangedecimals')) {
 239              $defaultrangedecimals = $CFG->grade_report_user_rangedecimals;
 240          }
 241          $this->rangedecimals = grade_get_setting($this->courseid, 'report_user_rangedecimals', $defaultrangedecimals);
 242  
 243          $this->switch = grade_get_setting($this->courseid, 'aggregationposition', $CFG->grade_aggregationposition);
 244  
 245          // Grab the grade_tree for this course
 246          $this->gtree = new grade_tree($this->courseid, false, $this->switch, null, !$CFG->enableoutcomes);
 247  
 248          // Get the user (for full name).
 249          $this->user = $DB->get_record('user', array('id' => $userid));
 250  
 251          // What user are we viewing this as?
 252          $coursecontext = context_course::instance($this->courseid);
 253          if ($viewasuser) {
 254              $this->modinfo = new course_modinfo($this->course, $this->user->id);
 255              $this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext, $this->user->id);
 256          } else {
 257              $this->modinfo = $this->gtree->modinfo;
 258              $this->canviewhidden = has_capability('moodle/grade:viewhidden', $coursecontext);
 259          }
 260  
 261          // Determine the number of rows and indentation.
 262          $this->maxdepth = 1;
 263          $this->inject_rowspans($this->gtree->top_element);
 264          $this->maxdepth++; // Need to account for the lead column that spans all children.
 265          for ($i = 1; $i <= $this->maxdepth; $i++) {
 266              $this->evenodd[$i] = 0;
 267          }
 268  
 269          $this->tabledata = array();
 270  
 271          // base url for sorting by first/last name
 272          $this->baseurl = $CFG->wwwroot.'/grade/report?id='.$courseid.'&amp;userid='.$userid;
 273          $this->pbarurl = $this->baseurl;
 274  
 275          // no groups on this report - rank is from all course users
 276          $this->setup_table();
 277  
 278          //optionally calculate grade item averages
 279          $this->calculate_averages();
 280      }
 281  
 282      /**
 283       * Recurses through a tree of elements setting the rowspan property on each element
 284       *
 285       * @param array $element Either the top element or, during recursion, the current element
 286       * @return int The number of elements processed
 287       */
 288      function inject_rowspans(&$element) {
 289  
 290          if ($element['depth'] > $this->maxdepth) {
 291              $this->maxdepth = $element['depth'];
 292          }
 293          if (empty($element['children'])) {
 294              return 1;
 295          }
 296          $count = 1;
 297  
 298          foreach ($element['children'] as $key=>$child) {
 299              // If category is hidden then do not include it in the rowspan.
 300              if ($child['type'] == 'category' && $child['object']->is_hidden() && !$this->canviewhidden
 301                      && ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN
 302                      || ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$child['object']->is_hiddenuntil()))) {
 303                  // Just calculate the rowspans for children of this category, don't add them to the count.
 304                  $this->inject_rowspans($element['children'][$key]);
 305              } else {
 306                  $count += $this->inject_rowspans($element['children'][$key]);
 307              }
 308          }
 309  
 310          $element['rowspan'] = $count;
 311          return $count;
 312      }
 313  
 314  
 315      /**
 316       * Prepares the headers and attributes of the flexitable.
 317       */
 318      public function setup_table() {
 319          /*
 320           * Table has 1-8 columns
 321           *| All columns except for itemname/description are optional
 322           */
 323  
 324          // setting up table headers
 325  
 326          $this->tablecolumns = array('itemname');
 327          $this->tableheaders = array($this->get_lang_string('gradeitem', 'grades'));
 328  
 329          if ($this->showweight) {
 330              $this->tablecolumns[] = 'weight';
 331              $this->tableheaders[] = $this->get_lang_string('weightuc', 'grades');
 332          }
 333  
 334          if ($this->showgrade) {
 335              $this->tablecolumns[] = 'grade';
 336              $this->tableheaders[] = $this->get_lang_string('grade', 'grades');
 337          }
 338  
 339          if ($this->showrange) {
 340              $this->tablecolumns[] = 'range';
 341              $this->tableheaders[] = $this->get_lang_string('range', 'grades');
 342          }
 343  
 344          if ($this->showpercentage) {
 345              $this->tablecolumns[] = 'percentage';
 346              $this->tableheaders[] = $this->get_lang_string('percentage', 'grades');
 347          }
 348  
 349          if ($this->showlettergrade) {
 350              $this->tablecolumns[] = 'lettergrade';
 351              $this->tableheaders[] = $this->get_lang_string('lettergrade', 'grades');
 352          }
 353  
 354          if ($this->showrank) {
 355              $this->tablecolumns[] = 'rank';
 356              $this->tableheaders[] = $this->get_lang_string('rank', 'grades');
 357          }
 358  
 359          if ($this->showaverage) {
 360              $this->tablecolumns[] = 'average';
 361              $this->tableheaders[] = $this->get_lang_string('average', 'grades');
 362          }
 363  
 364          if ($this->showfeedback) {
 365              $this->tablecolumns[] = 'feedback';
 366              $this->tableheaders[] = $this->get_lang_string('feedback', 'grades');
 367          }
 368  
 369          if ($this->showcontributiontocoursetotal) {
 370              $this->tablecolumns[] = 'contributiontocoursetotal';
 371              $this->tableheaders[] = $this->get_lang_string('contributiontocoursetotal', 'grades');
 372          }
 373      }
 374  
 375      function fill_table() {
 376          //print "<pre>";
 377          //print_r($this->gtree->top_element);
 378          $this->fill_table_recursive($this->gtree->top_element);
 379          //print_r($this->tabledata);
 380          //print "</pre>";
 381          return true;
 382      }
 383  
 384      /**
 385       * Fill the table with data.
 386       *
 387       * @param $element - An array containing the table data for the current row.
 388       */
 389      private function fill_table_recursive(&$element) {
 390          global $DB, $CFG;
 391  
 392          $type = $element['type'];
 393          $depth = $element['depth'];
 394          $grade_object = $element['object'];
 395          $eid = $grade_object->id;
 396          $element['userid'] = $this->user->id;
 397          $fullname = $this->gtree->get_element_header($element, true, true, true, true, true);
 398          $data = array();
 399          $gradeitemdata = array();
 400          $hidden = '';
 401          $excluded = '';
 402          $itemlevel = ($type == 'categoryitem' || $type == 'category' || $type == 'courseitem') ? $depth : ($depth + 1);
 403          $class = 'level' . $itemlevel . ' level' . ($itemlevel % 2 ? 'odd' : 'even');
 404          $classfeedback = '';
 405  
 406          // If this is a hidden grade category, hide it completely from the user
 407          if ($type == 'category' && $grade_object->is_hidden() && !$this->canviewhidden && (
 408                  $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
 409                  ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_object->is_hiddenuntil()))) {
 410              return false;
 411          }
 412  
 413          if ($type == 'category') {
 414              $this->evenodd[$depth] = (($this->evenodd[$depth] + 1) % 2);
 415          }
 416          $alter = ($this->evenodd[$depth] == 0) ? 'even' : 'odd';
 417  
 418          /// Process those items that have scores associated
 419          if ($type == 'item' or $type == 'categoryitem' or $type == 'courseitem') {
 420              $header_row = "row_{$eid}_{$this->user->id}";
 421              $header_cat = "cat_{$grade_object->categoryid}_{$this->user->id}";
 422  
 423              if (! $grade_grade = grade_grade::fetch(array('itemid'=>$grade_object->id,'userid'=>$this->user->id))) {
 424                  $grade_grade = new grade_grade();
 425                  $grade_grade->userid = $this->user->id;
 426                  $grade_grade->itemid = $grade_object->id;
 427              }
 428  
 429              $grade_grade->load_grade_item();
 430  
 431              /// Hidden Items
 432              if ($grade_grade->grade_item->is_hidden()) {
 433                  $hidden = ' dimmed_text';
 434              }
 435  
 436              $hide = false;
 437              // If this is a hidden grade item, hide it completely from the user.
 438              if ($grade_grade->is_hidden() && !$this->canviewhidden && (
 439                      $this->showhiddenitems == GRADE_REPORT_USER_HIDE_HIDDEN ||
 440                      ($this->showhiddenitems == GRADE_REPORT_USER_HIDE_UNTIL && !$grade_grade->is_hiddenuntil()))) {
 441                  $hide = true;
 442              } else if (!empty($grade_object->itemmodule) && !empty($grade_object->iteminstance)) {
 443                  // The grade object can be marked visible but still be hidden if
 444                  // the student cannot see the activity due to conditional access
 445                  // and it's set to be hidden entirely.
 446                  $instances = $this->modinfo->get_instances_of($grade_object->itemmodule);
 447                  if (!empty($instances[$grade_object->iteminstance])) {
 448                      $cm = $instances[$grade_object->iteminstance];
 449                      $gradeitemdata['cmid'] = $cm->id;
 450                      if (!$cm->uservisible) {
 451                          // If there is 'availableinfo' text then it is only greyed
 452                          // out and not entirely hidden.
 453                          if (!$cm->availableinfo) {
 454                              $hide = true;
 455                          }
 456                      }
 457                  }
 458              }
 459  
 460              // Actual Grade - We need to calculate this whether the row is hidden or not.
 461              $gradeval = $grade_grade->finalgrade;
 462              $hint = $grade_grade->get_aggregation_hint();
 463              if (!$this->canviewhidden) {
 464                  /// Virtual Grade (may be calculated excluding hidden items etc).
 465                  $adjustedgrade = $this->blank_hidden_total_and_adjust_bounds($this->courseid,
 466                                                                               $grade_grade->grade_item,
 467                                                                               $gradeval);
 468  
 469                  $gradeval = $adjustedgrade['grade'];
 470  
 471                  // We temporarily adjust the view of this grade item - because the min and
 472                  // max are affected by the hidden values in the aggregation.
 473                  $grade_grade->grade_item->grademax = $adjustedgrade['grademax'];
 474                  $grade_grade->grade_item->grademin = $adjustedgrade['grademin'];
 475                  $hint['status'] = $adjustedgrade['aggregationstatus'];
 476                  $hint['weight'] = $adjustedgrade['aggregationweight'];
 477              } else {
 478                  // The max and min for an aggregation may be different to the grade_item.
 479                  if (!is_null($gradeval)) {
 480                      $grade_grade->grade_item->grademax = $grade_grade->get_grade_max();
 481                      $grade_grade->grade_item->grademin = $grade_grade->get_grade_min();
 482                  }
 483              }
 484  
 485  
 486              if (!$hide) {
 487                  /// Excluded Item
 488                  /**
 489                  if ($grade_grade->is_excluded()) {
 490                      $fullname .= ' ['.get_string('excluded', 'grades').']';
 491                      $excluded = ' excluded';
 492                  }
 493                  **/
 494                  $canviewall = has_capability('moodle/grade:viewall', $this->context);
 495                  /// Other class information
 496                  $class .= $hidden . $excluded;
 497                  if ($this->switch) { // alter style based on whether aggregation is first or last
 498                     $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggt b2b" : " item b1b";
 499                  } else {
 500                     $class .= ($type == 'categoryitem' or $type == 'courseitem') ? " ".$alter."d$depth baggb" : " item b1b";
 501                  }
 502                  if ($type == 'categoryitem' or $type == 'courseitem') {
 503                      $header_cat = "cat_{$grade_object->iteminstance}_{$this->user->id}";
 504                  }
 505  
 506                  /// Name
 507                  $data['itemname']['content'] = $fullname;
 508                  $data['itemname']['class'] = $class;
 509                  $data['itemname']['colspan'] = ($this->maxdepth - $depth);
 510                  $data['itemname']['celltype'] = 'th';
 511                  $data['itemname']['id'] = $header_row;
 512  
 513                  // Basic grade item information.
 514                  $gradeitemdata['id'] = $grade_object->id;
 515                  $gradeitemdata['itemname'] = $grade_object->itemname;
 516                  $gradeitemdata['itemtype'] = $grade_object->itemtype;
 517                  $gradeitemdata['itemmodule'] = $grade_object->itemmodule;
 518                  $gradeitemdata['iteminstance'] = $grade_object->iteminstance;
 519                  $gradeitemdata['itemnumber'] = $grade_object->itemnumber;
 520                  $gradeitemdata['idnumber'] = $grade_object->idnumber;
 521                  $gradeitemdata['categoryid'] = $grade_object->categoryid;
 522                  $gradeitemdata['outcomeid'] = $grade_object->outcomeid;
 523                  $gradeitemdata['scaleid'] = $grade_object->outcomeid;
 524                  $gradeitemdata['locked'] = $canviewall ? $grade_grade->grade_item->is_locked() : null;
 525  
 526                  if ($this->showfeedback) {
 527                      // Copy $class before appending itemcenter as feedback should not be centered
 528                      $classfeedback = $class;
 529                  }
 530                  $class .= " itemcenter ";
 531                  if ($this->showweight) {
 532                      $data['weight']['class'] = $class;
 533                      $data['weight']['content'] = '-';
 534                      $data['weight']['headers'] = "$header_cat $header_row weight";
 535                      // has a weight assigned, might be extra credit
 536  
 537                      // This obliterates the weight because it provides a more informative description.
 538                      if (is_numeric($hint['weight'])) {
 539                          $data['weight']['content'] = format_float($hint['weight'] * 100.0, 2) . ' %';
 540                          $gradeitemdata['weightraw'] = $hint['weight'];
 541                          $gradeitemdata['weightformatted'] = $data['weight']['content'];
 542                      }
 543                      if ($hint['status'] != 'used' && $hint['status'] != 'unknown') {
 544                          $data['weight']['content'] .= '<br>' . get_string('aggregationhint' . $hint['status'], 'grades');
 545                          $gradeitemdata['status'] = $hint['status'];
 546                      }
 547                  }
 548  
 549                  if ($this->showgrade) {
 550                      $gradeitemdata['graderaw'] = null;
 551                      $gradeitemdata['gradehiddenbydate'] = false;
 552                      $gradeitemdata['gradeneedsupdate'] = $grade_grade->grade_item->needsupdate;
 553                      $gradeitemdata['gradeishidden'] = $grade_grade->is_hidden();
 554                      $gradeitemdata['gradedatesubmitted'] = $grade_grade->get_datesubmitted();
 555                      $gradeitemdata['gradedategraded'] = $grade_grade->get_dategraded();
 556                      $gradeitemdata['gradeislocked'] = $canviewall ? $grade_grade->is_locked() : null;
 557                      $gradeitemdata['gradeisoverridden'] = $canviewall ? $grade_grade->is_overridden() : null;
 558  
 559                      if ($grade_grade->grade_item->needsupdate) {
 560                          $data['grade']['class'] = $class.' gradingerror';
 561                          $data['grade']['content'] = get_string('error');
 562                      } else if (!empty($CFG->grade_hiddenasdate) and $grade_grade->get_datesubmitted() and !$this->canviewhidden and $grade_grade->is_hidden()
 563                             and !$grade_grade->grade_item->is_category_item() and !$grade_grade->grade_item->is_course_item()) {
 564                          // the problem here is that we do not have the time when grade value was modified, 'timemodified' is general modification date for grade_grades records
 565                          $class .= ' datesubmitted';
 566                          $data['grade']['class'] = $class;
 567                          $data['grade']['content'] = get_string('submittedon', 'grades', userdate($grade_grade->get_datesubmitted(), get_string('strftimedatetimeshort')));
 568                          $gradeitemdata['gradehiddenbydate'] = true;
 569                      } else if ($grade_grade->is_hidden()) {
 570                          $data['grade']['class'] = $class.' dimmed_text';
 571                          $data['grade']['content'] = '-';
 572  
 573                          if ($this->canviewhidden) {
 574                              $gradeitemdata['graderaw'] = $gradeval;
 575                              $data['grade']['content'] = grade_format_gradevalue($gradeval,
 576                                                                                  $grade_grade->grade_item,
 577                                                                                  true);
 578                          }
 579                      } else {
 580                          $data['grade']['class'] = $class;
 581                          $data['grade']['content'] = grade_format_gradevalue($gradeval,
 582                                                                              $grade_grade->grade_item,
 583                                                                              true);
 584                          $gradeitemdata['graderaw'] = $gradeval;
 585                      }
 586                      $data['grade']['headers'] = "$header_cat $header_row grade";
 587                      $gradeitemdata['gradeformatted'] = $data['grade']['content'];
 588                  }
 589  
 590                  // Range
 591                  if ($this->showrange) {
 592                      $data['range']['class'] = $class;
 593                      $data['range']['content'] = $grade_grade->grade_item->get_formatted_range(GRADE_DISPLAY_TYPE_REAL, $this->rangedecimals);
 594                      $data['range']['headers'] = "$header_cat $header_row range";
 595  
 596                      $gradeitemdata['rangeformatted'] = $data['range']['content'];
 597                      $gradeitemdata['grademin'] = $grade_grade->grade_item->grademin;
 598                      $gradeitemdata['grademax'] = $grade_grade->grade_item->grademax;
 599                  }
 600  
 601                  // Percentage
 602                  if ($this->showpercentage) {
 603                      if ($grade_grade->grade_item->needsupdate) {
 604                          $data['percentage']['class'] = $class.' gradingerror';
 605                          $data['percentage']['content'] = get_string('error');
 606                      } else if ($grade_grade->is_hidden()) {
 607                          $data['percentage']['class'] = $class.' dimmed_text';
 608                          $data['percentage']['content'] = '-';
 609                          if ($this->canviewhidden) {
 610                              $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
 611                          }
 612                      } else {
 613                          $data['percentage']['class'] = $class;
 614                          $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
 615                      }
 616                      $data['percentage']['headers'] = "$header_cat $header_row percentage";
 617                      $gradeitemdata['percentageformatted'] = $data['percentage']['content'];
 618                  }
 619  
 620                  // Lettergrade
 621                  if ($this->showlettergrade) {
 622                      if ($grade_grade->grade_item->needsupdate) {
 623                          $data['lettergrade']['class'] = $class.' gradingerror';
 624                          $data['lettergrade']['content'] = get_string('error');
 625                      } else if ($grade_grade->is_hidden()) {
 626                          $data['lettergrade']['class'] = $class.' dimmed_text';
 627                          if (!$this->canviewhidden) {
 628                              $data['lettergrade']['content'] = '-';
 629                          } else {
 630                              $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
 631                          }
 632                      } else {
 633                          $data['lettergrade']['class'] = $class;
 634                          $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
 635                      }
 636                      $data['lettergrade']['headers'] = "$header_cat $header_row lettergrade";
 637                      $gradeitemdata['lettergradeformatted'] = $data['lettergrade']['content'];
 638                  }
 639  
 640                  // Rank
 641                  if ($this->showrank) {
 642                      $gradeitemdata['rank'] = 0;
 643                      if ($grade_grade->grade_item->needsupdate) {
 644                          $data['rank']['class'] = $class.' gradingerror';
 645                          $data['rank']['content'] = get_string('error');
 646                          } elseif ($grade_grade->is_hidden()) {
 647                              $data['rank']['class'] = $class.' dimmed_text';
 648                              $data['rank']['content'] = '-';
 649                      } else if (is_null($gradeval)) {
 650                          // no grade, no rank
 651                          $data['rank']['class'] = $class;
 652                          $data['rank']['content'] = '-';
 653  
 654                      } else {
 655                          /// find the number of users with a higher grade
 656                          $sql = "SELECT COUNT(DISTINCT(userid))
 657                                    FROM {grade_grades}
 658                                   WHERE finalgrade > ?
 659                                         AND itemid = ?
 660                                         AND hidden = 0";
 661                          $rank = $DB->count_records_sql($sql, array($grade_grade->finalgrade, $grade_grade->grade_item->id)) + 1;
 662  
 663                          $data['rank']['class'] = $class;
 664                          $numusers = $this->get_numusers(false);
 665                          $data['rank']['content'] = "$rank/$numusers"; // Total course users.
 666  
 667                          $gradeitemdata['rank'] = $rank;
 668                          $gradeitemdata['numusers'] = $numusers;
 669                      }
 670                      $data['rank']['headers'] = "$header_cat $header_row rank";
 671                  }
 672  
 673                  // Average
 674                  if ($this->showaverage) {
 675                      $gradeitemdata['averageformatted'] = '';
 676  
 677                      $data['average']['class'] = $class;
 678                      if (!empty($this->gtree->items[$eid]->avg)) {
 679                          $data['average']['content'] = $this->gtree->items[$eid]->avg;
 680                          $gradeitemdata['averageformatted'] = $this->gtree->items[$eid]->avg;
 681                      } else {
 682                          $data['average']['content'] = '-';
 683                      }
 684                      $data['average']['headers'] = "$header_cat $header_row average";
 685                  }
 686  
 687                  // Feedback
 688                  if ($this->showfeedback) {
 689                      $gradeitemdata['feedback'] = '';
 690                      $gradeitemdata['feedbackformat'] = $grade_grade->feedbackformat;
 691  
 692                      if ($grade_grade->feedback) {
 693                          $grade_grade->feedback = file_rewrite_pluginfile_urls(
 694                              $grade_grade->feedback,
 695                              'pluginfile.php',
 696                              $grade_grade->get_context()->id,
 697                              GRADE_FILE_COMPONENT,
 698                              GRADE_FEEDBACK_FILEAREA,
 699                              $grade_grade->id
 700                          );
 701                      }
 702  
 703                      if ($grade_grade->overridden > 0 AND ($type == 'categoryitem' OR $type == 'courseitem')) {
 704                      $data['feedback']['class'] = $classfeedback.' feedbacktext';
 705                          $data['feedback']['content'] = get_string('overridden', 'grades').': ' .
 706                              format_text($grade_grade->feedback, $grade_grade->feedbackformat,
 707                                  ['context' => $grade_grade->get_context()]);
 708                          $gradeitemdata['feedback'] = $grade_grade->feedback;
 709                      } else if (empty($grade_grade->feedback) or (!$this->canviewhidden and $grade_grade->is_hidden())) {
 710                          $data['feedback']['class'] = $classfeedback.' feedbacktext';
 711                          $data['feedback']['content'] = '&nbsp;';
 712                      } else {
 713                          $data['feedback']['class'] = $classfeedback.' feedbacktext';
 714                          $data['feedback']['content'] = format_text($grade_grade->feedback, $grade_grade->feedbackformat,
 715                              ['context' => $grade_grade->get_context()]);
 716                          $gradeitemdata['feedback'] = $grade_grade->feedback;
 717                      }
 718                      $data['feedback']['headers'] = "$header_cat $header_row feedback";
 719                  }
 720                  // Contribution to the course total column.
 721                  if ($this->showcontributiontocoursetotal) {
 722                      $data['contributiontocoursetotal']['class'] = $class;
 723                      $data['contributiontocoursetotal']['content'] = '-';
 724                      $data['contributiontocoursetotal']['headers'] = "$header_cat $header_row contributiontocoursetotal";
 725  
 726                  }
 727                  $this->gradeitemsdata[] = $gradeitemdata;
 728              }
 729              // We collect the aggregation hints whether they are hidden or not.
 730              if ($this->showcontributiontocoursetotal) {
 731                  $hint['grademax'] = $grade_grade->grade_item->grademax;
 732                  $hint['grademin'] = $grade_grade->grade_item->grademin;
 733                  $hint['grade'] = $gradeval;
 734                  $parent = $grade_object->load_parent_category();
 735                  if ($grade_object->is_category_item()) {
 736                      $parent = $parent->load_parent_category();
 737                  }
 738                  $hint['parent'] = $parent->load_grade_item()->id;
 739                  $this->aggregationhints[$grade_grade->itemid] = $hint;
 740              }
 741          }
 742  
 743          /// Category
 744          if ($type == 'category') {
 745              $data['leader']['class'] = $class.' '.$alter."d$depth b1t b2b b1l";
 746              $data['leader']['rowspan'] = $element['rowspan'];
 747  
 748              if ($this->switch) { // alter style based on whether aggregation is first or last
 749                 $data['itemname']['class'] = $class.' '.$alter."d$depth b1b b1t";
 750              } else {
 751                 $data['itemname']['class'] = $class.' '.$alter."d$depth b2t";
 752              }
 753              $data['itemname']['colspan'] = ($this->maxdepth - $depth + count($this->tablecolumns) - 1);
 754              $data['itemname']['content'] = $fullname;
 755              $data['itemname']['celltype'] = 'th';
 756              $data['itemname']['id'] = "cat_{$grade_object->id}_{$this->user->id}";
 757          }
 758  
 759          /// Add this row to the overall system
 760          foreach ($data as $key => $celldata) {
 761              $data[$key]['class'] .= ' column-' . $key;
 762          }
 763          $this->tabledata[] = $data;
 764  
 765          /// Recursively iterate through all child elements
 766          if (isset($element['children'])) {
 767              foreach ($element['children'] as $key=>$child) {
 768                  $this->fill_table_recursive($element['children'][$key]);
 769              }
 770          }
 771  
 772          // Check we are showing this column, and we are looking at the root of the table.
 773          // This should be the very last thing this fill_table_recursive function does.
 774          if ($this->showcontributiontocoursetotal && ($type == 'category' && $depth == 1)) {
 775              // We should have collected all the hints by now - walk the tree again and build the contributions column.
 776  
 777              $this->fill_contributions_column($element);
 778          }
 779      }
 780  
 781      /**
 782       * This function is called after the table has been built and the aggregationhints
 783       * have been collected. We need this info to walk up the list of parents of each
 784       * grade_item.
 785       *
 786       * @param $element - An array containing the table data for the current row.
 787       */
 788      public function fill_contributions_column($element) {
 789  
 790          // Recursively iterate through all child elements.
 791          if (isset($element['children'])) {
 792              foreach ($element['children'] as $key=>$child) {
 793                  $this->fill_contributions_column($element['children'][$key]);
 794              }
 795          } else if ($element['type'] == 'item') {
 796              // This is a grade item (We don't do this for categories or we would double count).
 797              $grade_object = $element['object'];
 798              $itemid = $grade_object->id;
 799  
 800              // Ignore anything with no hint - e.g. a hidden row.
 801              if (isset($this->aggregationhints[$itemid])) {
 802  
 803                  // Normalise the gradeval.
 804                  $gradecat = $grade_object->load_parent_category();
 805                  if ($gradecat->aggregation == GRADE_AGGREGATE_SUM) {
 806                      // Natural aggregation/Sum of grades does not consider the mingrade, cannot traditionnally normalise it.
 807                      $graderange = $this->aggregationhints[$itemid]['grademax'];
 808  
 809                      if ($graderange != 0) {
 810                          $gradeval = $this->aggregationhints[$itemid]['grade'] / $graderange;
 811                      } else {
 812                          $gradeval = 0;
 813                      }
 814                  } else {
 815                      $gradeval = grade_grade::standardise_score($this->aggregationhints[$itemid]['grade'],
 816                          $this->aggregationhints[$itemid]['grademin'], $this->aggregationhints[$itemid]['grademax'], 0, 1);
 817                  }
 818  
 819                  // Multiply the normalised value by the weight
 820                  // of all the categories higher in the tree.
 821                  $parent = null;
 822                  do {
 823                      if (!is_null($this->aggregationhints[$itemid]['weight'])) {
 824                          $gradeval *= $this->aggregationhints[$itemid]['weight'];
 825                      } else if (empty($parent)) {
 826                          // If we are in the first loop, and the weight is null, then we cannot calculate the contribution.
 827                          $gradeval = null;
 828                          break;
 829                      }
 830  
 831                      // The second part of this if is to prevent infinite loops
 832                      // in case of crazy data.
 833                      if (isset($this->aggregationhints[$itemid]['parent']) &&
 834                              $this->aggregationhints[$itemid]['parent'] != $itemid) {
 835                          $parent = $this->aggregationhints[$itemid]['parent'];
 836                          $itemid = $parent;
 837                      } else {
 838                          // We are at the top of the tree.
 839                          $parent = false;
 840                      }
 841                  } while ($parent);
 842  
 843                  // Finally multiply by the course grademax.
 844                  if (!is_null($gradeval)) {
 845                      // Convert to percent.
 846                      $gradeval *= 100;
 847                  }
 848  
 849                  // Now we need to loop through the "built" table data and update the
 850                  // contributions column for the current row.
 851                  $header_row = "row_{$grade_object->id}_{$this->user->id}";
 852                  foreach ($this->tabledata as $key => $row) {
 853                      if (isset($row['itemname']) && ($row['itemname']['id'] == $header_row)) {
 854                          // Found it - update the column.
 855                          $content = '-';
 856                          if (!is_null($gradeval)) {
 857                              $decimals = $grade_object->get_decimals();
 858                              $content = format_float($gradeval, $decimals, true) . ' %';
 859                          }
 860                          $this->tabledata[$key]['contributiontocoursetotal']['content'] = $content;
 861                          break;
 862                      }
 863                  }
 864              }
 865          }
 866      }
 867  
 868      /**
 869       * Prints or returns the HTML from the flexitable.
 870       * @param bool $return Whether or not to return the data instead of printing it directly.
 871       * @return string
 872       */
 873      public function print_table($return=false) {
 874           $maxspan = $this->maxdepth;
 875  
 876          /// Build table structure
 877          $html = "
 878              <table cellspacing='0'
 879                     cellpadding='0'
 880                     summary='" . s($this->get_lang_string('tablesummary', 'gradereport_user')) . "'
 881                     class='boxaligncenter generaltable user-grade'>
 882              <thead>
 883                  <tr>
 884                      <th id='".$this->tablecolumns[0]."' class=\"header column-{$this->tablecolumns[0]}\" colspan='$maxspan'>".$this->tableheaders[0]."</th>\n";
 885  
 886          for ($i = 1; $i < count($this->tableheaders); $i++) {
 887              $html .= "<th id='".$this->tablecolumns[$i]."' class=\"header column-{$this->tablecolumns[$i]}\">".$this->tableheaders[$i]."</th>\n";
 888          }
 889  
 890          $html .= "
 891                  </tr>
 892              </thead>
 893              <tbody>\n";
 894  
 895          /// Print out the table data
 896          for ($i = 0; $i < count($this->tabledata); $i++) {
 897              $html .= "<tr>\n";
 898              if (isset($this->tabledata[$i]['leader'])) {
 899                  $rowspan = $this->tabledata[$i]['leader']['rowspan'];
 900                  $class = $this->tabledata[$i]['leader']['class'];
 901                  $html .= "<td class='$class' rowspan='$rowspan'></td>\n";
 902              }
 903              for ($j = 0; $j < count($this->tablecolumns); $j++) {
 904                  $name = $this->tablecolumns[$j];
 905                  $class = (isset($this->tabledata[$i][$name]['class'])) ? $this->tabledata[$i][$name]['class'] : '';
 906                  $colspan = (isset($this->tabledata[$i][$name]['colspan'])) ? "colspan='".$this->tabledata[$i][$name]['colspan']."'" : '';
 907                  $content = (isset($this->tabledata[$i][$name]['content'])) ? $this->tabledata[$i][$name]['content'] : null;
 908                  $celltype = (isset($this->tabledata[$i][$name]['celltype'])) ? $this->tabledata[$i][$name]['celltype'] : 'td';
 909                  $id = (isset($this->tabledata[$i][$name]['id'])) ? "id='{$this->tabledata[$i][$name]['id']}'" : '';
 910                  $headers = (isset($this->tabledata[$i][$name]['headers'])) ? "headers='{$this->tabledata[$i][$name]['headers']}'" : '';
 911                  if (isset($content)) {
 912                      $html .= "<$celltype $id $headers class='$class' $colspan>$content</$celltype>\n";
 913                  }
 914              }
 915              $html .= "</tr>\n";
 916          }
 917  
 918          $html .= "</tbody></table>";
 919  
 920          if ($return) {
 921              return $html;
 922          } else {
 923              echo $html;
 924          }
 925      }
 926  
 927      /**
 928       * Processes the data sent by the form (grades and feedbacks).
 929       * @var array $data
 930       * @return bool Success or Failure (array of errors).
 931       */
 932      function process_data($data) {
 933      }
 934      function process_action($target, $action) {
 935      }
 936  
 937      /**
 938       * Builds the grade item averages.
 939       */
 940      function calculate_averages() {
 941          global $USER, $DB, $CFG;
 942  
 943          if ($this->showaverage) {
 944              // This settings are actually grader report settings (not user report)
 945              // however we're using them as having two separate but identical settings the
 946              // user would have to keep in sync would be annoying.
 947              $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
 948              $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
 949              $meanselection         = $this->get_pref('meanselection');
 950              $shownumberofgrades    = $this->get_pref('shownumberofgrades');
 951  
 952              $avghtml = '';
 953              $groupsql = $this->groupsql;
 954              $groupwheresql = $this->groupwheresql;
 955              $totalcount = $this->get_numusers(false);
 956  
 957              // We want to query both the current context and parent contexts.
 958              list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
 959  
 960              // Limit to users with a gradeable role ie students.
 961              list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
 962  
 963              // Limit to users with an active enrolment.
 964              $coursecontext = $this->context->get_course_context(true);
 965              $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
 966              $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
 967              $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
 968              list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
 969  
 970              $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams, $relatedctxparams);
 971              $params['courseid'] = $this->courseid;
 972  
 973              // find sums of all grade items in course
 974              $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
 975                        FROM {grade_items} gi
 976                        JOIN {grade_grades} gg ON gg.itemid = gi.id
 977                        JOIN {user} u ON u.id = gg.userid
 978                        JOIN ($enrolledsql) je ON je.id = gg.userid
 979                        JOIN (
 980                                     SELECT DISTINCT ra.userid
 981                                       FROM {role_assignments} ra
 982                                      WHERE ra.roleid $gradebookrolessql
 983                                        AND ra.contextid $relatedctxsql
 984                             ) rainner ON rainner.userid = u.id
 985                        $groupsql
 986                       WHERE gi.courseid = :courseid
 987                         AND u.deleted = 0
 988                         AND gg.finalgrade IS NOT NULL
 989                         AND gg.hidden = 0
 990                         $groupwheresql
 991                    GROUP BY gg.itemid";
 992  
 993              $sum_array = array();
 994              $sums = $DB->get_recordset_sql($sql, $params);
 995              foreach ($sums as $itemid => $csum) {
 996                  $sum_array[$itemid] = $csum->sum;
 997              }
 998              $sums->close();
 999  
1000              $columncount=0;
1001  
1002              // Empty grades must be evaluated as grademin, NOT always 0
1003              // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1004              // No join condition when joining grade_items and user to get a grade item row for every user
1005              // Then left join with grade_grades and look for rows with null final grade (which includes grade items with no grade_grade)
1006              $sql = "SELECT gi.id, COUNT(u.id) AS count
1007                        FROM {grade_items} gi
1008                        JOIN {user} u ON u.deleted = 0
1009                        JOIN ($enrolledsql) je ON je.id = u.id
1010                        JOIN (
1011                                 SELECT DISTINCT ra.userid
1012                                   FROM {role_assignments} ra
1013                                  WHERE ra.roleid $gradebookrolessql
1014                                    AND ra.contextid $relatedctxsql
1015                             ) rainner ON rainner.userid = u.id
1016                        LEFT JOIN {grade_grades} gg
1017                               ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL AND gg.hidden = 0)
1018                        $groupsql
1019                       WHERE gi.courseid = :courseid
1020                             AND gg.finalgrade IS NULL
1021                             $groupwheresql
1022                    GROUP BY gi.id";
1023  
1024              $ungraded_counts = $DB->get_records_sql($sql, $params);
1025  
1026              foreach ($this->gtree->items as $itemid=>$unused) {
1027                  if (!empty($this->gtree->items[$itemid]->avg)) {
1028                      continue;
1029                  }
1030                  $item = $this->gtree->items[$itemid];
1031  
1032                  if ($item->needsupdate) {
1033                      $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
1034                      continue;
1035                  }
1036  
1037                  if (empty($sum_array[$item->id])) {
1038                      $sum_array[$item->id] = 0;
1039                  }
1040  
1041                  if (empty($ungraded_counts[$itemid])) {
1042                      $ungraded_count = 0;
1043                  } else {
1044                      $ungraded_count = $ungraded_counts[$itemid]->count;
1045                  }
1046  
1047                  //do they want the averages to include all grade items
1048                  if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1049                      $mean_count = $totalcount - $ungraded_count;
1050                  } else { // Bump up the sum by the number of ungraded items * grademin
1051                      $sum_array[$item->id] += ($ungraded_count * $item->grademin);
1052                      $mean_count = $totalcount;
1053                  }
1054  
1055                  // Determine which display type to use for this average
1056                  if (!empty($USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
1057                      $displaytype = GRADE_DISPLAY_TYPE_REAL;
1058  
1059                  } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1060                      $displaytype = $item->get_displaytype();
1061  
1062                  } else {
1063                      $displaytype = $averagesdisplaytype;
1064                  }
1065  
1066                  // Override grade_item setting if a display preference (not inherit) was set for the averages
1067                  if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1068                      $decimalpoints = $item->get_decimals();
1069                  } else {
1070                      $decimalpoints = $averagesdecimalpoints;
1071                  }
1072  
1073                  if (empty($sum_array[$item->id]) || $mean_count == 0) {
1074                      $this->gtree->items[$itemid]->avg = '-';
1075                  } else {
1076                      $sum = $sum_array[$item->id];
1077                      $avgradeval = $sum/$mean_count;
1078                      $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1079  
1080                      $numberofgrades = '';
1081                      if ($shownumberofgrades) {
1082                          $numberofgrades = " ($mean_count)";
1083                      }
1084  
1085                      $this->gtree->items[$itemid]->avg = $gradehtml.$numberofgrades;
1086                  }
1087              }
1088          }
1089      }
1090  
1091      /**
1092       * Trigger the grade_report_viewed event
1093       *
1094       * @since Moodle 2.9
1095       */
1096      public function viewed() {
1097          $event = \gradereport_user\event\grade_report_viewed::create(
1098              array(
1099                  'context' => $this->context,
1100                  'courseid' => $this->courseid,
1101                  'relateduserid' => $this->user->id,
1102              )
1103          );
1104          $event->trigger();
1105      }
1106  }
1107  
1108  function grade_report_user_settings_definition(&$mform) {
1109      global $CFG;
1110  
1111      $options = array(-1 => get_string('default', 'grades'),
1112                        0 => get_string('hide'),
1113                        1 => get_string('show'));
1114  
1115      if (empty($CFG->grade_report_user_showrank)) {
1116          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1117      } else {
1118          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1119      }
1120  
1121      $mform->addElement('select', 'report_user_showrank', get_string('showrank', 'grades'), $options);
1122      $mform->addHelpButton('report_user_showrank', 'showrank', 'grades');
1123  
1124      if (empty($CFG->grade_report_user_showpercentage)) {
1125          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1126      } else {
1127          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1128      }
1129  
1130      $mform->addElement('select', 'report_user_showpercentage', get_string('showpercentage', 'grades'), $options);
1131      $mform->addHelpButton('report_user_showpercentage', 'showpercentage', 'grades');
1132  
1133      if (empty($CFG->grade_report_user_showgrade)) {
1134          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1135      } else {
1136          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1137      }
1138  
1139      $mform->addElement('select', 'report_user_showgrade', get_string('showgrade', 'grades'), $options);
1140  
1141      if (empty($CFG->grade_report_user_showfeedback)) {
1142          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1143      } else {
1144          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1145      }
1146  
1147      $mform->addElement('select', 'report_user_showfeedback', get_string('showfeedback', 'grades'), $options);
1148  
1149      if (empty($CFG->grade_report_user_showweight)) {
1150          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1151      } else {
1152          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1153      }
1154  
1155      $mform->addElement('select', 'report_user_showweight', get_string('showweight', 'grades'), $options);
1156  
1157      if (empty($CFG->grade_report_user_showaverage)) {
1158          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1159      } else {
1160          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1161      }
1162  
1163      $mform->addElement('select', 'report_user_showaverage', get_string('showaverage', 'grades'), $options);
1164      $mform->addHelpButton('report_user_showaverage', 'showaverage', 'grades');
1165  
1166      if (empty($CFG->grade_report_user_showlettergrade)) {
1167          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1168      } else {
1169          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1170      }
1171  
1172      $mform->addElement('select', 'report_user_showlettergrade', get_string('showlettergrade', 'grades'), $options);
1173      if (empty($CFG->grade_report_user_showcontributiontocoursetotal)) {
1174          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1175      } else {
1176          $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showcontributiontocoursetotal]);
1177      }
1178  
1179      $mform->addElement('select', 'report_user_showcontributiontocoursetotal', get_string('showcontributiontocoursetotal', 'grades'), $options);
1180      $mform->addHelpButton('report_user_showcontributiontocoursetotal', 'showcontributiontocoursetotal', 'grades');
1181  
1182      if (empty($CFG->grade_report_user_showrange)) {
1183          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1184      } else {
1185          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1186      }
1187  
1188      $mform->addElement('select', 'report_user_showrange', get_string('showrange', 'grades'), $options);
1189  
1190      $options = array(0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5);
1191      if (! empty($CFG->grade_report_user_rangedecimals)) {
1192          $options[-1] = $options[$CFG->grade_report_user_rangedecimals];
1193      }
1194      $mform->addElement('select', 'report_user_rangedecimals', get_string('rangedecimals', 'grades'), $options);
1195  
1196      $options = array(-1 => get_string('default', 'grades'),
1197                        0 => get_string('shownohidden', 'grades'),
1198                        1 => get_string('showhiddenuntilonly', 'grades'),
1199                        2 => get_string('showallhidden', 'grades'));
1200  
1201      if (empty($CFG->grade_report_user_showhiddenitems)) {
1202          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1203      } else {
1204          $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showhiddenitems]);
1205      }
1206  
1207      $mform->addElement('select', 'report_user_showhiddenitems', get_string('showhiddenitems', 'grades'), $options);
1208      $mform->addHelpButton('report_user_showhiddenitems', 'showhiddenitems', 'grades');
1209  
1210      //showtotalsifcontainhidden
1211      $options = array(-1 => get_string('default', 'grades'),
1212                        GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN => get_string('hide'),
1213                        GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowexhiddenitems', 'grades'),
1214                        GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowinchiddenitems', 'grades') );
1215  
1216      if (empty($CFG->grade_report_user_showtotalsifcontainhidden)) {
1217          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1218      } else {
1219          $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showtotalsifcontainhidden]);
1220      }
1221  
1222      $mform->addElement('select', 'report_user_showtotalsifcontainhidden', get_string('hidetotalifhiddenitems', 'grades'), $options);
1223      $mform->addHelpButton('report_user_showtotalsifcontainhidden', 'hidetotalifhiddenitems', 'grades');
1224  
1225  }
1226  
1227  /**
1228   * Profile report callback.
1229   *
1230   * @param object $course The course.
1231   * @param object $user The user.
1232   * @param boolean $viewasuser True when we are viewing this as the targetted user sees it.
1233   */
1234  function grade_report_user_profilereport($course, $user, $viewasuser = false) {
1235      global $OUTPUT;
1236      if (!empty($course->showgrades)) {
1237  
1238          $context = context_course::instance($course->id);
1239  
1240          /// return tracking object
1241          $gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'user', 'courseid'=>$course->id, 'userid'=>$user->id));
1242          // Create a report instance
1243          $report = new grade_report_user($course->id, $gpr, $context, $user->id, $viewasuser);
1244  
1245          // print the page
1246          echo '<div class="grade-report-user">'; // css fix to share styles with real report page
1247          if ($report->fill_table()) {
1248              echo $report->print_table(true);
1249          }
1250          echo '</div>';
1251      }
1252  }
1253  
1254  /**
1255   * Add nodes to myprofile page.
1256   *
1257   * @param \core_user\output\myprofile\tree $tree Tree object
1258   * @param stdClass $user user object
1259   * @param bool $iscurrentuser
1260   * @param stdClass $course Course object
1261   */
1262  function gradereport_user_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
1263      global $CFG, $USER;
1264      if (empty($course)) {
1265          // We want to display these reports under the site context.
1266          $course = get_fast_modinfo(SITEID)->get_course();
1267      }
1268      $usercontext = context_user::instance($user->id);
1269      $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1270  
1271      // Start capability checks.
1272      if ($anyreport || $iscurrentuser) {
1273          // Add grade hardcoded grade report if necessary.
1274          $gradeaccess = false;
1275          $coursecontext = context_course::instance($course->id);
1276          if (has_capability('moodle/grade:viewall', $coursecontext)) {
1277              // Can view all course grades.
1278              $gradeaccess = true;
1279          } else if ($course->showgrades) {
1280              if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1281                  // Can view own grades.
1282                  $gradeaccess = true;
1283              } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1284                  // Can view grades of this user - parent most probably.
1285                  $gradeaccess = true;
1286              } else if ($anyreport) {
1287                  // Can view grades of this user - parent most probably.
1288                  $gradeaccess = true;
1289              }
1290          }
1291          if ($gradeaccess) {
1292              $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
1293              $node = new core_user\output\myprofile\node('reports', 'grade', get_string('grades'), null, $url);
1294              $tree->add_node($node);
1295          }
1296      }
1297  }