Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * 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['categoryid'] = $grade_object->categoryid;
 521                  $gradeitemdata['outcomeid'] = $grade_object->outcomeid;
 522                  $gradeitemdata['scaleid'] = $grade_object->outcomeid;
 523                  $gradeitemdata['locked'] = $canviewall ? $grade_grade->grade_item->is_locked() : null;
 524  
 525                  if ($this->showfeedback) {
 526                      // Copy $class before appending itemcenter as feedback should not be centered
 527                      $classfeedback = $class;
 528                  }
 529                  $class .= " itemcenter ";
 530                  if ($this->showweight) {
 531                      $data['weight']['class'] = $class;
 532                      $data['weight']['content'] = '-';
 533                      $data['weight']['headers'] = "$header_cat $header_row weight";
 534                      // has a weight assigned, might be extra credit
 535  
 536                      // This obliterates the weight because it provides a more informative description.
 537                      if (is_numeric($hint['weight'])) {
 538                          $data['weight']['content'] = format_float($hint['weight'] * 100.0, 2) . ' %';
 539                          $gradeitemdata['weightraw'] = $hint['weight'];
 540                          $gradeitemdata['weightformatted'] = $data['weight']['content'];
 541                      }
 542                      if ($hint['status'] != 'used' && $hint['status'] != 'unknown') {
 543                          $data['weight']['content'] .= '<br>' . get_string('aggregationhint' . $hint['status'], 'grades');
 544                          $gradeitemdata['status'] = $hint['status'];
 545                      }
 546                  }
 547  
 548                  if ($this->showgrade) {
 549                      $gradeitemdata['graderaw'] = null;
 550                      $gradeitemdata['gradehiddenbydate'] = false;
 551                      $gradeitemdata['gradeneedsupdate'] = $grade_grade->grade_item->needsupdate;
 552                      $gradeitemdata['gradeishidden'] = $grade_grade->is_hidden();
 553                      $gradeitemdata['gradedatesubmitted'] = $grade_grade->get_datesubmitted();
 554                      $gradeitemdata['gradedategraded'] = $grade_grade->get_dategraded();
 555                      $gradeitemdata['gradeislocked'] = $canviewall ? $grade_grade->is_locked() : null;
 556                      $gradeitemdata['gradeisoverridden'] = $canviewall ? $grade_grade->is_overridden() : null;
 557  
 558                      if ($grade_grade->grade_item->needsupdate) {
 559                          $data['grade']['class'] = $class.' gradingerror';
 560                          $data['grade']['content'] = get_string('error');
 561                      } else if (!empty($CFG->grade_hiddenasdate) and $grade_grade->get_datesubmitted() and !$this->canviewhidden and $grade_grade->is_hidden()
 562                             and !$grade_grade->grade_item->is_category_item() and !$grade_grade->grade_item->is_course_item()) {
 563                          // 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
 564                          $class .= ' datesubmitted';
 565                          $data['grade']['class'] = $class;
 566                          $data['grade']['content'] = get_string('submittedon', 'grades', userdate($grade_grade->get_datesubmitted(), get_string('strftimedatetimeshort')));
 567                          $gradeitemdata['gradehiddenbydate'] = true;
 568                      } else if ($grade_grade->is_hidden()) {
 569                          $data['grade']['class'] = $class.' dimmed_text';
 570                          $data['grade']['content'] = '-';
 571  
 572                          if ($this->canviewhidden) {
 573                              $gradeitemdata['graderaw'] = $gradeval;
 574                              $data['grade']['content'] = grade_format_gradevalue($gradeval,
 575                                                                                  $grade_grade->grade_item,
 576                                                                                  true);
 577                          }
 578                      } else {
 579                          $data['grade']['class'] = $class;
 580                          $data['grade']['content'] = grade_format_gradevalue($gradeval,
 581                                                                              $grade_grade->grade_item,
 582                                                                              true);
 583                          $gradeitemdata['graderaw'] = $gradeval;
 584                      }
 585                      $data['grade']['headers'] = "$header_cat $header_row grade";
 586                      $gradeitemdata['gradeformatted'] = $data['grade']['content'];
 587                  }
 588  
 589                  // Range
 590                  if ($this->showrange) {
 591                      $data['range']['class'] = $class;
 592                      $data['range']['content'] = $grade_grade->grade_item->get_formatted_range(GRADE_DISPLAY_TYPE_REAL, $this->rangedecimals);
 593                      $data['range']['headers'] = "$header_cat $header_row range";
 594  
 595                      $gradeitemdata['rangeformatted'] = $data['range']['content'];
 596                      $gradeitemdata['grademin'] = $grade_grade->grade_item->grademin;
 597                      $gradeitemdata['grademax'] = $grade_grade->grade_item->grademax;
 598                  }
 599  
 600                  // Percentage
 601                  if ($this->showpercentage) {
 602                      if ($grade_grade->grade_item->needsupdate) {
 603                          $data['percentage']['class'] = $class.' gradingerror';
 604                          $data['percentage']['content'] = get_string('error');
 605                      } else if ($grade_grade->is_hidden()) {
 606                          $data['percentage']['class'] = $class.' dimmed_text';
 607                          $data['percentage']['content'] = '-';
 608                          if ($this->canviewhidden) {
 609                              $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
 610                          }
 611                      } else {
 612                          $data['percentage']['class'] = $class;
 613                          $data['percentage']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_PERCENTAGE);
 614                      }
 615                      $data['percentage']['headers'] = "$header_cat $header_row percentage";
 616                      $gradeitemdata['percentageformatted'] = $data['percentage']['content'];
 617                  }
 618  
 619                  // Lettergrade
 620                  if ($this->showlettergrade) {
 621                      if ($grade_grade->grade_item->needsupdate) {
 622                          $data['lettergrade']['class'] = $class.' gradingerror';
 623                          $data['lettergrade']['content'] = get_string('error');
 624                      } else if ($grade_grade->is_hidden()) {
 625                          $data['lettergrade']['class'] = $class.' dimmed_text';
 626                          if (!$this->canviewhidden) {
 627                              $data['lettergrade']['content'] = '-';
 628                          } else {
 629                              $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
 630                          }
 631                      } else {
 632                          $data['lettergrade']['class'] = $class;
 633                          $data['lettergrade']['content'] = grade_format_gradevalue($gradeval, $grade_grade->grade_item, true, GRADE_DISPLAY_TYPE_LETTER);
 634                      }
 635                      $data['lettergrade']['headers'] = "$header_cat $header_row lettergrade";
 636                      $gradeitemdata['lettergradeformatted'] = $data['lettergrade']['content'];
 637                  }
 638  
 639                  // Rank
 640                  if ($this->showrank) {
 641                      $gradeitemdata['rank'] = 0;
 642                      if ($grade_grade->grade_item->needsupdate) {
 643                          $data['rank']['class'] = $class.' gradingerror';
 644                          $data['rank']['content'] = get_string('error');
 645                          } elseif ($grade_grade->is_hidden()) {
 646                              $data['rank']['class'] = $class.' dimmed_text';
 647                              $data['rank']['content'] = '-';
 648                      } else if (is_null($gradeval)) {
 649                          // no grade, no rank
 650                          $data['rank']['class'] = $class;
 651                          $data['rank']['content'] = '-';
 652  
 653                      } else {
 654                          /// find the number of users with a higher grade
 655                          $sql = "SELECT COUNT(DISTINCT(userid))
 656                                    FROM {grade_grades}
 657                                   WHERE finalgrade > ?
 658                                         AND itemid = ?
 659                                         AND hidden = 0";
 660                          $rank = $DB->count_records_sql($sql, array($grade_grade->finalgrade, $grade_grade->grade_item->id)) + 1;
 661  
 662                          $data['rank']['class'] = $class;
 663                          $numusers = $this->get_numusers(false);
 664                          $data['rank']['content'] = "$rank/$numusers"; // Total course users.
 665  
 666                          $gradeitemdata['rank'] = $rank;
 667                          $gradeitemdata['numusers'] = $numusers;
 668                      }
 669                      $data['rank']['headers'] = "$header_cat $header_row rank";
 670                  }
 671  
 672                  // Average
 673                  if ($this->showaverage) {
 674                      $gradeitemdata['averageformatted'] = '';
 675  
 676                      $data['average']['class'] = $class;
 677                      if (!empty($this->gtree->items[$eid]->avg)) {
 678                          $data['average']['content'] = $this->gtree->items[$eid]->avg;
 679                          $gradeitemdata['averageformatted'] = $this->gtree->items[$eid]->avg;
 680                      } else {
 681                          $data['average']['content'] = '-';
 682                      }
 683                      $data['average']['headers'] = "$header_cat $header_row average";
 684                  }
 685  
 686                  // Feedback
 687                  if ($this->showfeedback) {
 688                      $gradeitemdata['feedback'] = '';
 689                      $gradeitemdata['feedbackformat'] = $grade_grade->feedbackformat;
 690  
 691                      if ($grade_grade->feedback) {
 692                          $grade_grade->feedback = file_rewrite_pluginfile_urls(
 693                              $grade_grade->feedback,
 694                              'pluginfile.php',
 695                              $grade_grade->get_context()->id,
 696                              GRADE_FILE_COMPONENT,
 697                              GRADE_FEEDBACK_FILEAREA,
 698                              $grade_grade->id
 699                          );
 700                      }
 701  
 702                      if ($grade_grade->overridden > 0 AND ($type == 'categoryitem' OR $type == 'courseitem')) {
 703                      $data['feedback']['class'] = $classfeedback.' feedbacktext';
 704                          $data['feedback']['content'] = get_string('overridden', 'grades').': ' .
 705                              format_text($grade_grade->feedback, $grade_grade->feedbackformat,
 706                                  ['context' => $grade_grade->get_context()]);
 707                          $gradeitemdata['feedback'] = $grade_grade->feedback;
 708                      } else if (empty($grade_grade->feedback) or (!$this->canviewhidden and $grade_grade->is_hidden())) {
 709                          $data['feedback']['class'] = $classfeedback.' feedbacktext';
 710                          $data['feedback']['content'] = '&nbsp;';
 711                      } else {
 712                          $data['feedback']['class'] = $classfeedback.' feedbacktext';
 713                          $data['feedback']['content'] = format_text($grade_grade->feedback, $grade_grade->feedbackformat,
 714                              ['context' => $grade_grade->get_context()]);
 715                          $gradeitemdata['feedback'] = $grade_grade->feedback;
 716                      }
 717                      $data['feedback']['headers'] = "$header_cat $header_row feedback";
 718                  }
 719                  // Contribution to the course total column.
 720                  if ($this->showcontributiontocoursetotal) {
 721                      $data['contributiontocoursetotal']['class'] = $class;
 722                      $data['contributiontocoursetotal']['content'] = '-';
 723                      $data['contributiontocoursetotal']['headers'] = "$header_cat $header_row contributiontocoursetotal";
 724  
 725                  }
 726                  $this->gradeitemsdata[] = $gradeitemdata;
 727              }
 728              // We collect the aggregation hints whether they are hidden or not.
 729              if ($this->showcontributiontocoursetotal) {
 730                  $hint['grademax'] = $grade_grade->grade_item->grademax;
 731                  $hint['grademin'] = $grade_grade->grade_item->grademin;
 732                  $hint['grade'] = $gradeval;
 733                  $parent = $grade_object->load_parent_category();
 734                  if ($grade_object->is_category_item()) {
 735                      $parent = $parent->load_parent_category();
 736                  }
 737                  $hint['parent'] = $parent->load_grade_item()->id;
 738                  $this->aggregationhints[$grade_grade->itemid] = $hint;
 739              }
 740          }
 741  
 742          /// Category
 743          if ($type == 'category') {
 744              $data['leader']['class'] = $class.' '.$alter."d$depth b1t b2b b1l";
 745              $data['leader']['rowspan'] = $element['rowspan'];
 746  
 747              if ($this->switch) { // alter style based on whether aggregation is first or last
 748                 $data['itemname']['class'] = $class.' '.$alter."d$depth b1b b1t";
 749              } else {
 750                 $data['itemname']['class'] = $class.' '.$alter."d$depth b2t";
 751              }
 752              $data['itemname']['colspan'] = ($this->maxdepth - $depth + count($this->tablecolumns) - 1);
 753              $data['itemname']['content'] = $fullname;
 754              $data['itemname']['celltype'] = 'th';
 755              $data['itemname']['id'] = "cat_{$grade_object->id}_{$this->user->id}";
 756          }
 757  
 758          /// Add this row to the overall system
 759          foreach ($data as $key => $celldata) {
 760              $data[$key]['class'] .= ' column-' . $key;
 761          }
 762          $this->tabledata[] = $data;
 763  
 764          /// Recursively iterate through all child elements
 765          if (isset($element['children'])) {
 766              foreach ($element['children'] as $key=>$child) {
 767                  $this->fill_table_recursive($element['children'][$key]);
 768              }
 769          }
 770  
 771          // Check we are showing this column, and we are looking at the root of the table.
 772          // This should be the very last thing this fill_table_recursive function does.
 773          if ($this->showcontributiontocoursetotal && ($type == 'category' && $depth == 1)) {
 774              // We should have collected all the hints by now - walk the tree again and build the contributions column.
 775  
 776              $this->fill_contributions_column($element);
 777          }
 778      }
 779  
 780      /**
 781       * This function is called after the table has been built and the aggregationhints
 782       * have been collected. We need this info to walk up the list of parents of each
 783       * grade_item.
 784       *
 785       * @param $element - An array containing the table data for the current row.
 786       */
 787      public function fill_contributions_column($element) {
 788  
 789          // Recursively iterate through all child elements.
 790          if (isset($element['children'])) {
 791              foreach ($element['children'] as $key=>$child) {
 792                  $this->fill_contributions_column($element['children'][$key]);
 793              }
 794          } else if ($element['type'] == 'item') {
 795              // This is a grade item (We don't do this for categories or we would double count).
 796              $grade_object = $element['object'];
 797              $itemid = $grade_object->id;
 798  
 799              // Ignore anything with no hint - e.g. a hidden row.
 800              if (isset($this->aggregationhints[$itemid])) {
 801  
 802                  // Normalise the gradeval.
 803                  $gradecat = $grade_object->load_parent_category();
 804                  if ($gradecat->aggregation == GRADE_AGGREGATE_SUM) {
 805                      // Natural aggregation/Sum of grades does not consider the mingrade, cannot traditionnally normalise it.
 806                      $graderange = $this->aggregationhints[$itemid]['grademax'];
 807  
 808                      if ($graderange != 0) {
 809                          $gradeval = $this->aggregationhints[$itemid]['grade'] / $graderange;
 810                      } else {
 811                          $gradeval = 0;
 812                      }
 813                  } else {
 814                      $gradeval = grade_grade::standardise_score($this->aggregationhints[$itemid]['grade'],
 815                          $this->aggregationhints[$itemid]['grademin'], $this->aggregationhints[$itemid]['grademax'], 0, 1);
 816                  }
 817  
 818                  // Multiply the normalised value by the weight
 819                  // of all the categories higher in the tree.
 820                  $parent = null;
 821                  do {
 822                      if (!is_null($this->aggregationhints[$itemid]['weight'])) {
 823                          $gradeval *= $this->aggregationhints[$itemid]['weight'];
 824                      } else if (empty($parent)) {
 825                          // If we are in the first loop, and the weight is null, then we cannot calculate the contribution.
 826                          $gradeval = null;
 827                          break;
 828                      }
 829  
 830                      // The second part of this if is to prevent infinite loops
 831                      // in case of crazy data.
 832                      if (isset($this->aggregationhints[$itemid]['parent']) &&
 833                              $this->aggregationhints[$itemid]['parent'] != $itemid) {
 834                          $parent = $this->aggregationhints[$itemid]['parent'];
 835                          $itemid = $parent;
 836                      } else {
 837                          // We are at the top of the tree.
 838                          $parent = false;
 839                      }
 840                  } while ($parent);
 841  
 842                  // Finally multiply by the course grademax.
 843                  if (!is_null($gradeval)) {
 844                      // Convert to percent.
 845                      $gradeval *= 100;
 846                  }
 847  
 848                  // Now we need to loop through the "built" table data and update the
 849                  // contributions column for the current row.
 850                  $header_row = "row_{$grade_object->id}_{$this->user->id}";
 851                  foreach ($this->tabledata as $key => $row) {
 852                      if (isset($row['itemname']) && ($row['itemname']['id'] == $header_row)) {
 853                          // Found it - update the column.
 854                          $content = '-';
 855                          if (!is_null($gradeval)) {
 856                              $decimals = $grade_object->get_decimals();
 857                              $content = format_float($gradeval, $decimals, true) . ' %';
 858                          }
 859                          $this->tabledata[$key]['contributiontocoursetotal']['content'] = $content;
 860                          break;
 861                      }
 862                  }
 863              }
 864          }
 865      }
 866  
 867      /**
 868       * Prints or returns the HTML from the flexitable.
 869       * @param bool $return Whether or not to return the data instead of printing it directly.
 870       * @return string
 871       */
 872      public function print_table($return=false) {
 873           $maxspan = $this->maxdepth;
 874  
 875          /// Build table structure
 876          $html = "
 877              <table cellspacing='0'
 878                     cellpadding='0'
 879                     summary='" . s($this->get_lang_string('tablesummary', 'gradereport_user')) . "'
 880                     class='boxaligncenter generaltable user-grade'>
 881              <thead>
 882                  <tr>
 883                      <th id='".$this->tablecolumns[0]."' class=\"header column-{$this->tablecolumns[0]}\" colspan='$maxspan'>".$this->tableheaders[0]."</th>\n";
 884  
 885          for ($i = 1; $i < count($this->tableheaders); $i++) {
 886              $html .= "<th id='".$this->tablecolumns[$i]."' class=\"header column-{$this->tablecolumns[$i]}\">".$this->tableheaders[$i]."</th>\n";
 887          }
 888  
 889          $html .= "
 890                  </tr>
 891              </thead>
 892              <tbody>\n";
 893  
 894          /// Print out the table data
 895          for ($i = 0; $i < count($this->tabledata); $i++) {
 896              $html .= "<tr>\n";
 897              if (isset($this->tabledata[$i]['leader'])) {
 898                  $rowspan = $this->tabledata[$i]['leader']['rowspan'];
 899                  $class = $this->tabledata[$i]['leader']['class'];
 900                  $html .= "<td class='$class' rowspan='$rowspan'></td>\n";
 901              }
 902              for ($j = 0; $j < count($this->tablecolumns); $j++) {
 903                  $name = $this->tablecolumns[$j];
 904                  $class = (isset($this->tabledata[$i][$name]['class'])) ? $this->tabledata[$i][$name]['class'] : '';
 905                  $colspan = (isset($this->tabledata[$i][$name]['colspan'])) ? "colspan='".$this->tabledata[$i][$name]['colspan']."'" : '';
 906                  $content = (isset($this->tabledata[$i][$name]['content'])) ? $this->tabledata[$i][$name]['content'] : null;
 907                  $celltype = (isset($this->tabledata[$i][$name]['celltype'])) ? $this->tabledata[$i][$name]['celltype'] : 'td';
 908                  $id = (isset($this->tabledata[$i][$name]['id'])) ? "id='{$this->tabledata[$i][$name]['id']}'" : '';
 909                  $headers = (isset($this->tabledata[$i][$name]['headers'])) ? "headers='{$this->tabledata[$i][$name]['headers']}'" : '';
 910                  if (isset($content)) {
 911                      $html .= "<$celltype $id $headers class='$class' $colspan>$content</$celltype>\n";
 912                  }
 913              }
 914              $html .= "</tr>\n";
 915          }
 916  
 917          $html .= "</tbody></table>";
 918  
 919          if ($return) {
 920              return $html;
 921          } else {
 922              echo $html;
 923          }
 924      }
 925  
 926      /**
 927       * Processes the data sent by the form (grades and feedbacks).
 928       * @var array $data
 929       * @return bool Success or Failure (array of errors).
 930       */
 931      function process_data($data) {
 932      }
 933      function process_action($target, $action) {
 934      }
 935  
 936      /**
 937       * Builds the grade item averages.
 938       */
 939      function calculate_averages() {
 940          global $USER, $DB, $CFG;
 941  
 942          if ($this->showaverage) {
 943              // This settings are actually grader report settings (not user report)
 944              // however we're using them as having two separate but identical settings the
 945              // user would have to keep in sync would be annoying.
 946              $averagesdisplaytype   = $this->get_pref('averagesdisplaytype');
 947              $averagesdecimalpoints = $this->get_pref('averagesdecimalpoints');
 948              $meanselection         = $this->get_pref('meanselection');
 949              $shownumberofgrades    = $this->get_pref('shownumberofgrades');
 950  
 951              $avghtml = '';
 952              $groupsql = $this->groupsql;
 953              $groupwheresql = $this->groupwheresql;
 954              $totalcount = $this->get_numusers(false);
 955  
 956              // We want to query both the current context and parent contexts.
 957              list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
 958  
 959              // Limit to users with a gradeable role ie students.
 960              list($gradebookrolessql, $gradebookrolesparams) = $DB->get_in_or_equal(explode(',', $this->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
 961  
 962              // Limit to users with an active enrolment.
 963              $coursecontext = $this->context->get_course_context(true);
 964              $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
 965              $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
 966              $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
 967              list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->context, '', 0, $showonlyactiveenrol);
 968  
 969              $params = array_merge($this->groupwheresql_params, $gradebookrolesparams, $enrolledparams, $relatedctxparams);
 970              $params['courseid'] = $this->courseid;
 971  
 972              // find sums of all grade items in course
 973              $sql = "SELECT gg.itemid, SUM(gg.finalgrade) AS sum
 974                        FROM {grade_items} gi
 975                        JOIN {grade_grades} gg ON gg.itemid = gi.id
 976                        JOIN {user} u ON u.id = gg.userid
 977                        JOIN ($enrolledsql) je ON je.id = gg.userid
 978                        JOIN (
 979                                     SELECT DISTINCT ra.userid
 980                                       FROM {role_assignments} ra
 981                                      WHERE ra.roleid $gradebookrolessql
 982                                        AND ra.contextid $relatedctxsql
 983                             ) rainner ON rainner.userid = u.id
 984                        $groupsql
 985                       WHERE gi.courseid = :courseid
 986                         AND u.deleted = 0
 987                         AND gg.finalgrade IS NOT NULL
 988                         AND gg.hidden = 0
 989                         $groupwheresql
 990                    GROUP BY gg.itemid";
 991  
 992              $sum_array = array();
 993              $sums = $DB->get_recordset_sql($sql, $params);
 994              foreach ($sums as $itemid => $csum) {
 995                  $sum_array[$itemid] = $csum->sum;
 996              }
 997              $sums->close();
 998  
 999              $columncount=0;
1000  
1001              // Empty grades must be evaluated as grademin, NOT always 0
1002              // This query returns a count of ungraded grades (NULL finalgrade OR no matching record in grade_grades table)
1003              // No join condition when joining grade_items and user to get a grade item row for every user
1004              // Then left join with grade_grades and look for rows with null final grade (which includes grade items with no grade_grade)
1005              $sql = "SELECT gi.id, COUNT(u.id) AS count
1006                        FROM {grade_items} gi
1007                        JOIN {user} u ON u.deleted = 0
1008                        JOIN ($enrolledsql) je ON je.id = u.id
1009                        JOIN (
1010                                 SELECT DISTINCT ra.userid
1011                                   FROM {role_assignments} ra
1012                                  WHERE ra.roleid $gradebookrolessql
1013                                    AND ra.contextid $relatedctxsql
1014                             ) rainner ON rainner.userid = u.id
1015                        LEFT JOIN {grade_grades} gg
1016                               ON (gg.itemid = gi.id AND gg.userid = u.id AND gg.finalgrade IS NOT NULL AND gg.hidden = 0)
1017                        $groupsql
1018                       WHERE gi.courseid = :courseid
1019                             AND gg.finalgrade IS NULL
1020                             $groupwheresql
1021                    GROUP BY gi.id";
1022  
1023              $ungraded_counts = $DB->get_records_sql($sql, $params);
1024  
1025              foreach ($this->gtree->items as $itemid=>$unused) {
1026                  if (!empty($this->gtree->items[$itemid]->avg)) {
1027                      continue;
1028                  }
1029                  $item = $this->gtree->items[$itemid];
1030  
1031                  if ($item->needsupdate) {
1032                      $avghtml .= '<td class="cell c' . $columncount++.'"><span class="gradingerror">'.get_string('error').'</span></td>';
1033                      continue;
1034                  }
1035  
1036                  if (empty($sum_array[$item->id])) {
1037                      $sum_array[$item->id] = 0;
1038                  }
1039  
1040                  if (empty($ungraded_counts[$itemid])) {
1041                      $ungraded_count = 0;
1042                  } else {
1043                      $ungraded_count = $ungraded_counts[$itemid]->count;
1044                  }
1045  
1046                  //do they want the averages to include all grade items
1047                  if ($meanselection == GRADE_REPORT_MEAN_GRADED) {
1048                      $mean_count = $totalcount - $ungraded_count;
1049                  } else { // Bump up the sum by the number of ungraded items * grademin
1050                      $sum_array[$item->id] += ($ungraded_count * $item->grademin);
1051                      $mean_count = $totalcount;
1052                  }
1053  
1054                  // Determine which display type to use for this average
1055                  if (!empty($USER->gradeediting) && $USER->gradeediting[$this->courseid]) {
1056                      $displaytype = GRADE_DISPLAY_TYPE_REAL;
1057  
1058                  } else if ($averagesdisplaytype == GRADE_REPORT_PREFERENCE_INHERIT) { // no ==0 here, please resave the report and user preferences
1059                      $displaytype = $item->get_displaytype();
1060  
1061                  } else {
1062                      $displaytype = $averagesdisplaytype;
1063                  }
1064  
1065                  // Override grade_item setting if a display preference (not inherit) was set for the averages
1066                  if ($averagesdecimalpoints == GRADE_REPORT_PREFERENCE_INHERIT) {
1067                      $decimalpoints = $item->get_decimals();
1068                  } else {
1069                      $decimalpoints = $averagesdecimalpoints;
1070                  }
1071  
1072                  if (empty($sum_array[$item->id]) || $mean_count == 0) {
1073                      $this->gtree->items[$itemid]->avg = '-';
1074                  } else {
1075                      $sum = $sum_array[$item->id];
1076                      $avgradeval = $sum/$mean_count;
1077                      $gradehtml = grade_format_gradevalue($avgradeval, $item, true, $displaytype, $decimalpoints);
1078  
1079                      $numberofgrades = '';
1080                      if ($shownumberofgrades) {
1081                          $numberofgrades = " ($mean_count)";
1082                      }
1083  
1084                      $this->gtree->items[$itemid]->avg = $gradehtml.$numberofgrades;
1085                  }
1086              }
1087          }
1088      }
1089  
1090      /**
1091       * Trigger the grade_report_viewed event
1092       *
1093       * @since Moodle 2.9
1094       */
1095      public function viewed() {
1096          $event = \gradereport_user\event\grade_report_viewed::create(
1097              array(
1098                  'context' => $this->context,
1099                  'courseid' => $this->courseid,
1100                  'relateduserid' => $this->user->id,
1101              )
1102          );
1103          $event->trigger();
1104      }
1105  }
1106  
1107  function grade_report_user_settings_definition(&$mform) {
1108      global $CFG;
1109  
1110      $options = array(-1 => get_string('default', 'grades'),
1111                        0 => get_string('hide'),
1112                        1 => get_string('show'));
1113  
1114      if (empty($CFG->grade_report_user_showrank)) {
1115          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1116      } else {
1117          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1118      }
1119  
1120      $mform->addElement('select', 'report_user_showrank', get_string('showrank', 'grades'), $options);
1121      $mform->addHelpButton('report_user_showrank', 'showrank', 'grades');
1122  
1123      if (empty($CFG->grade_report_user_showpercentage)) {
1124          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1125      } else {
1126          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1127      }
1128  
1129      $mform->addElement('select', 'report_user_showpercentage', get_string('showpercentage', 'grades'), $options);
1130      $mform->addHelpButton('report_user_showpercentage', 'showpercentage', 'grades');
1131  
1132      if (empty($CFG->grade_report_user_showgrade)) {
1133          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1134      } else {
1135          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1136      }
1137  
1138      $mform->addElement('select', 'report_user_showgrade', get_string('showgrade', 'grades'), $options);
1139  
1140      if (empty($CFG->grade_report_user_showfeedback)) {
1141          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1142      } else {
1143          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1144      }
1145  
1146      $mform->addElement('select', 'report_user_showfeedback', get_string('showfeedback', 'grades'), $options);
1147  
1148      if (empty($CFG->grade_report_user_showweight)) {
1149          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1150      } else {
1151          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1152      }
1153  
1154      $mform->addElement('select', 'report_user_showweight', get_string('showweight', 'grades'), $options);
1155  
1156      if (empty($CFG->grade_report_user_showaverage)) {
1157          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1158      } else {
1159          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1160      }
1161  
1162      $mform->addElement('select', 'report_user_showaverage', get_string('showaverage', 'grades'), $options);
1163      $mform->addHelpButton('report_user_showaverage', 'showaverage', 'grades');
1164  
1165      if (empty($CFG->grade_report_user_showlettergrade)) {
1166          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1167      } else {
1168          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1169      }
1170  
1171      $mform->addElement('select', 'report_user_showlettergrade', get_string('showlettergrade', 'grades'), $options);
1172      if (empty($CFG->grade_report_user_showcontributiontocoursetotal)) {
1173          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1174      } else {
1175          $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showcontributiontocoursetotal]);
1176      }
1177  
1178      $mform->addElement('select', 'report_user_showcontributiontocoursetotal', get_string('showcontributiontocoursetotal', 'grades'), $options);
1179      $mform->addHelpButton('report_user_showcontributiontocoursetotal', 'showcontributiontocoursetotal', 'grades');
1180  
1181      if (empty($CFG->grade_report_user_showrange)) {
1182          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1183      } else {
1184          $options[-1] = get_string('defaultprev', 'grades', $options[1]);
1185      }
1186  
1187      $mform->addElement('select', 'report_user_showrange', get_string('showrange', 'grades'), $options);
1188  
1189      $options = array(0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5);
1190      if (! empty($CFG->grade_report_user_rangedecimals)) {
1191          $options[-1] = $options[$CFG->grade_report_user_rangedecimals];
1192      }
1193      $mform->addElement('select', 'report_user_rangedecimals', get_string('rangedecimals', 'grades'), $options);
1194  
1195      $options = array(-1 => get_string('default', 'grades'),
1196                        0 => get_string('shownohidden', 'grades'),
1197                        1 => get_string('showhiddenuntilonly', 'grades'),
1198                        2 => get_string('showallhidden', 'grades'));
1199  
1200      if (empty($CFG->grade_report_user_showhiddenitems)) {
1201          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1202      } else {
1203          $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showhiddenitems]);
1204      }
1205  
1206      $mform->addElement('select', 'report_user_showhiddenitems', get_string('showhiddenitems', 'grades'), $options);
1207      $mform->addHelpButton('report_user_showhiddenitems', 'showhiddenitems', 'grades');
1208  
1209      //showtotalsifcontainhidden
1210      $options = array(-1 => get_string('default', 'grades'),
1211                        GRADE_REPORT_HIDE_TOTAL_IF_CONTAINS_HIDDEN => get_string('hide'),
1212                        GRADE_REPORT_SHOW_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowexhiddenitems', 'grades'),
1213                        GRADE_REPORT_SHOW_REAL_TOTAL_IF_CONTAINS_HIDDEN => get_string('hidetotalshowinchiddenitems', 'grades') );
1214  
1215      if (empty($CFG->grade_report_user_showtotalsifcontainhidden)) {
1216          $options[-1] = get_string('defaultprev', 'grades', $options[0]);
1217      } else {
1218          $options[-1] = get_string('defaultprev', 'grades', $options[$CFG->grade_report_user_showtotalsifcontainhidden]);
1219      }
1220  
1221      $mform->addElement('select', 'report_user_showtotalsifcontainhidden', get_string('hidetotalifhiddenitems', 'grades'), $options);
1222      $mform->addHelpButton('report_user_showtotalsifcontainhidden', 'hidetotalifhiddenitems', 'grades');
1223  
1224  }
1225  
1226  /**
1227   * Profile report callback.
1228   *
1229   * @param object $course The course.
1230   * @param object $user The user.
1231   * @param boolean $viewasuser True when we are viewing this as the targetted user sees it.
1232   */
1233  function grade_report_user_profilereport($course, $user, $viewasuser = false) {
1234      global $OUTPUT;
1235      if (!empty($course->showgrades)) {
1236  
1237          $context = context_course::instance($course->id);
1238  
1239          /// return tracking object
1240          $gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'user', 'courseid'=>$course->id, 'userid'=>$user->id));
1241          // Create a report instance
1242          $report = new grade_report_user($course->id, $gpr, $context, $user->id, $viewasuser);
1243  
1244          // print the page
1245          echo '<div class="grade-report-user">'; // css fix to share styles with real report page
1246          if ($report->fill_table()) {
1247              echo $report->print_table(true);
1248          }
1249          echo '</div>';
1250      }
1251  }
1252  
1253  /**
1254   * Add nodes to myprofile page.
1255   *
1256   * @param \core_user\output\myprofile\tree $tree Tree object
1257   * @param stdClass $user user object
1258   * @param bool $iscurrentuser
1259   * @param stdClass $course Course object
1260   */
1261  function gradereport_user_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
1262      global $CFG, $USER;
1263      if (empty($course)) {
1264          // We want to display these reports under the site context.
1265          $course = get_fast_modinfo(SITEID)->get_course();
1266      }
1267      $usercontext = context_user::instance($user->id);
1268      $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext);
1269  
1270      // Start capability checks.
1271      if ($anyreport || $iscurrentuser) {
1272          // Add grade hardcoded grade report if necessary.
1273          $gradeaccess = false;
1274          $coursecontext = context_course::instance($course->id);
1275          if (has_capability('moodle/grade:viewall', $coursecontext)) {
1276              // Can view all course grades.
1277              $gradeaccess = true;
1278          } else if ($course->showgrades) {
1279              if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) {
1280                  // Can view own grades.
1281                  $gradeaccess = true;
1282              } else if (has_capability('moodle/grade:viewall', $usercontext)) {
1283                  // Can view grades of this user - parent most probably.
1284                  $gradeaccess = true;
1285              } else if ($anyreport) {
1286                  // Can view grades of this user - parent most probably.
1287                  $gradeaccess = true;
1288              }
1289          }
1290          if ($gradeaccess) {
1291              $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
1292              $node = new core_user\output\myprofile\node('reports', 'grade', get_string('grade'), null, $url);
1293              $tree->add_node($node);
1294          }
1295      }
1296  }