Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • /grade/ -> lib.php (source)

    Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

       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   * Functions used by gradebook plugins and reports.
      19   *
      20   * @package   core_grades
      21   * @copyright 2009 Petr Skoda and Nicolas Connault
      22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      23   */
      24  
      25  require_once($CFG->libdir . '/gradelib.php');
      26  require_once($CFG->dirroot . '/grade/export/lib.php');
      27  
      28  /**
      29   * This class iterates over all users that are graded in a course.
      30   * Returns detailed info about users and their grades.
      31   *
      32   * @author Petr Skoda <skodak@moodle.org>
      33   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
      34   */
      35  class graded_users_iterator {
      36  
      37      /**
      38       * The couse whose users we are interested in
      39       */
      40      protected $course;
      41  
      42      /**
      43       * An array of grade items or null if only user data was requested
      44       */
      45      protected $grade_items;
      46  
      47      /**
      48       * The group ID we are interested in. 0 means all groups.
      49       */
      50      protected $groupid;
      51  
      52      /**
      53       * A recordset of graded users
      54       */
      55      protected $users_rs;
      56  
      57      /**
      58       * A recordset of user grades (grade_grade instances)
      59       */
      60      protected $grades_rs;
      61  
      62      /**
      63       * Array used when moving to next user while iterating through the grades recordset
      64       */
      65      protected $gradestack;
      66  
      67      /**
      68       * The first field of the users table by which the array of users will be sorted
      69       */
      70      protected $sortfield1;
      71  
      72      /**
      73       * Should sortfield1 be ASC or DESC
      74       */
      75      protected $sortorder1;
      76  
      77      /**
      78       * The second field of the users table by which the array of users will be sorted
      79       */
      80      protected $sortfield2;
      81  
      82      /**
      83       * Should sortfield2 be ASC or DESC
      84       */
      85      protected $sortorder2;
      86  
      87      /**
      88       * Should users whose enrolment has been suspended be ignored?
      89       */
      90      protected $onlyactive = false;
      91  
      92      /**
      93       * Enable user custom fields
      94       */
      95      protected $allowusercustomfields = false;
      96  
      97      /**
      98       * List of suspended users in course. This includes users whose enrolment status is suspended
      99       * or enrolment has expired or not started.
     100       */
     101      protected $suspendedusers = array();
     102  
     103      /**
     104       * Constructor
     105       *
     106       * @param object $course A course object
     107       * @param array  $grade_items array of grade items, if not specified only user info returned
     108       * @param int    $groupid iterate only group users if present
     109       * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
     110       * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
     111       * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
     112       * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
     113       */
     114      public function __construct($course, $grade_items=null, $groupid=0,
     115                                            $sortfield1='lastname', $sortorder1='ASC',
     116                                            $sortfield2='firstname', $sortorder2='ASC') {
     117          $this->course      = $course;
     118          $this->grade_items = $grade_items;
     119          $this->groupid     = $groupid;
     120          $this->sortfield1  = $sortfield1;
     121          $this->sortorder1  = $sortorder1;
     122          $this->sortfield2  = $sortfield2;
     123          $this->sortorder2  = $sortorder2;
     124  
     125          $this->gradestack  = array();
     126      }
     127  
     128      /**
     129       * Initialise the iterator
     130       *
     131       * @return boolean success
     132       */
     133      public function init() {
     134          global $CFG, $DB;
     135  
     136          $this->close();
     137  
     138          export_verify_grades($this->course->id);
     139          $course_item = grade_item::fetch_course_item($this->course->id);
     140          if ($course_item->needsupdate) {
     141              // Can not calculate all final grades - sorry.
     142              return false;
     143          }
     144  
     145          $coursecontext = context_course::instance($this->course->id);
     146  
     147          list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
     148          list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
     149          list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
     150  
     151          $params = array_merge($params, $enrolledparams, $relatedctxparams);
     152  
     153          if ($this->groupid) {
     154              $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
     155              $groupwheresql = "AND gm.groupid = :groupid";
     156              // $params contents: gradebookroles
     157              $params['groupid'] = $this->groupid;
     158          } else {
     159              $groupsql = "";
     160              $groupwheresql = "";
     161          }
     162  
     163          if (empty($this->sortfield1)) {
     164              // We must do some sorting even if not specified.
     165              $ofields = ", u.id AS usrt";
     166              $order   = "usrt ASC";
     167  
     168          } else {
     169              $ofields = ", u.$this->sortfield1 AS usrt1";
     170              $order   = "usrt1 $this->sortorder1";
     171              if (!empty($this->sortfield2)) {
     172                  $ofields .= ", u.$this->sortfield2 AS usrt2";
     173                  $order   .= ", usrt2 $this->sortorder2";
     174              }
     175              if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
     176                  // User order MUST be the same in both queries,
     177                  // must include the only unique user->id if not already present.
     178                  $ofields .= ", u.id AS usrt";
     179                  $order   .= ", usrt ASC";
     180              }
     181          }
     182  
     183          $userfields = 'u.*';
     184          $customfieldssql = '';
     185          if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
     186              $customfieldscount = 0;
     187              $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
     188              foreach ($customfieldsarray as $field) {
     189                  if (!empty($field->customid)) {
     190                      $customfieldssql .= "
     191                              LEFT JOIN (SELECT * FROM {user_info_data}
     192                                  WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
     193                              ON u.id = cf$customfieldscount.userid";
     194                      $userfields .= ", cf$customfieldscount.data AS customfield_{$field->shortname}";
     195                      $params['cf'.$customfieldscount] = $field->customid;
     196                      $customfieldscount++;
     197                  }
     198              }
     199          }
     200  
     201          $users_sql = "SELECT $userfields $ofields
     202                          FROM {user} u
     203                          JOIN ($enrolledsql) je ON je.id = u.id
     204                               $groupsql $customfieldssql
     205                          JOIN (
     206                                    SELECT DISTINCT ra.userid
     207                                      FROM {role_assignments} ra
     208                                     WHERE ra.roleid $gradebookroles_sql
     209                                       AND ra.contextid $relatedctxsql
     210                               ) rainner ON rainner.userid = u.id
     211                           WHERE u.deleted = 0
     212                               $groupwheresql
     213                      ORDER BY $order";
     214          $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
     215  
     216          if (!$this->onlyactive) {
     217              $context = context_course::instance($this->course->id);
     218              $this->suspendedusers = get_suspended_userids($context);
     219          } else {
     220              $this->suspendedusers = array();
     221          }
     222  
     223          if (!empty($this->grade_items)) {
     224              $itemids = array_keys($this->grade_items);
     225              list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
     226              $params = array_merge($params, $grades_params);
     227  
     228              $grades_sql = "SELECT g.* $ofields
     229                               FROM {grade_grades} g
     230                               JOIN {user} u ON g.userid = u.id
     231                               JOIN ($enrolledsql) je ON je.id = u.id
     232                                    $groupsql
     233                               JOIN (
     234                                        SELECT DISTINCT ra.userid
     235                                          FROM {role_assignments} ra
     236                                         WHERE ra.roleid $gradebookroles_sql
     237                                           AND ra.contextid $relatedctxsql
     238                                    ) rainner ON rainner.userid = u.id
     239                                WHERE u.deleted = 0
     240                                AND g.itemid $itemidsql
     241                                $groupwheresql
     242                           ORDER BY $order, g.itemid ASC";
     243              $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
     244          } else {
     245              $this->grades_rs = false;
     246          }
     247  
     248          return true;
     249      }
     250  
     251      /**
     252       * Returns information about the next user
     253       * @return mixed array of user info, all grades and feedback or null when no more users found
     254       */
     255      public function next_user() {
     256          if (!$this->users_rs) {
     257              return false; // no users present
     258          }
     259  
     260          if (!$this->users_rs->valid()) {
     261              if ($current = $this->_pop()) {
     262                  // this is not good - user or grades updated between the two reads above :-(
     263              }
     264  
     265              return false; // no more users
     266          } else {
     267              $user = $this->users_rs->current();
     268              $this->users_rs->next();
     269          }
     270  
     271          // find grades of this user
     272          $grade_records = array();
     273          while (true) {
     274              if (!$current = $this->_pop()) {
     275                  break; // no more grades
     276              }
     277  
     278              if (empty($current->userid)) {
     279                  break;
     280              }
     281  
     282              if ($current->userid != $user->id) {
     283                  // grade of the next user, we have all for this user
     284                  $this->_push($current);
     285                  break;
     286              }
     287  
     288              $grade_records[$current->itemid] = $current;
     289          }
     290  
     291          $grades = array();
     292          $feedbacks = array();
     293  
     294          if (!empty($this->grade_items)) {
     295              foreach ($this->grade_items as $grade_item) {
     296                  if (!isset($feedbacks[$grade_item->id])) {
     297                      $feedbacks[$grade_item->id] = new stdClass();
     298                  }
     299                  if (array_key_exists($grade_item->id, $grade_records)) {
     300                      $feedbacks[$grade_item->id]->feedback       = $grade_records[$grade_item->id]->feedback;
     301                      $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
     302                      unset($grade_records[$grade_item->id]->feedback);
     303                      unset($grade_records[$grade_item->id]->feedbackformat);
     304                      $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
     305                  } else {
     306                      $feedbacks[$grade_item->id]->feedback       = '';
     307                      $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
     308                      $grades[$grade_item->id] =
     309                          new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
     310                  }
     311                  $grades[$grade_item->id]->grade_item = $grade_item;
     312              }
     313          }
     314  
     315          // Set user suspended status.
     316          $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
     317          $result = new stdClass();
     318          $result->user      = $user;
     319          $result->grades    = $grades;
     320          $result->feedbacks = $feedbacks;
     321          return $result;
     322      }
     323  
     324      /**
     325       * Close the iterator, do not forget to call this function
     326       */
     327      public function close() {
     328          if ($this->users_rs) {
     329              $this->users_rs->close();
     330              $this->users_rs = null;
     331          }
     332          if ($this->grades_rs) {
     333              $this->grades_rs->close();
     334              $this->grades_rs = null;
     335          }
     336          $this->gradestack = array();
     337      }
     338  
     339      /**
     340       * Should all enrolled users be exported or just those with an active enrolment?
     341       *
     342       * @param bool $onlyactive True to limit the export to users with an active enrolment
     343       */
     344      public function require_active_enrolment($onlyactive = true) {
     345          if (!empty($this->users_rs)) {
     346              debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
     347          }
     348          $this->onlyactive  = $onlyactive;
     349      }
     350  
     351      /**
     352       * Allow custom fields to be included
     353       *
     354       * @param bool $allow Whether to allow custom fields or not
     355       * @return void
     356       */
     357      public function allow_user_custom_fields($allow = true) {
     358          if ($allow) {
     359              $this->allowusercustomfields = true;
     360          } else {
     361              $this->allowusercustomfields = false;
     362          }
     363      }
     364  
     365      /**
     366       * Add a grade_grade instance to the grade stack
     367       *
     368       * @param grade_grade $grade Grade object
     369       *
     370       * @return void
     371       */
     372      private function _push($grade) {
     373          array_push($this->gradestack, $grade);
     374      }
     375  
     376  
     377      /**
     378       * Remove a grade_grade instance from the grade stack
     379       *
     380       * @return grade_grade current grade object
     381       */
     382      private function _pop() {
     383          global $DB;
     384          if (empty($this->gradestack)) {
     385              if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
     386                  return null; // no grades present
     387              }
     388  
     389              $current = $this->grades_rs->current();
     390  
     391              $this->grades_rs->next();
     392  
     393              return $current;
     394          } else {
     395              return array_pop($this->gradestack);
     396          }
     397      }
     398  }
     399  
     400  /**
     401   * Print a selection popup form of the graded users in a course.
     402   *
     403   * @deprecated since 2.0
     404   *
     405   * @param int    $course id of the course
     406   * @param string $actionpage The page receiving the data from the popoup form
     407   * @param int    $userid   id of the currently selected user (or 'all' if they are all selected)
     408   * @param int    $groupid id of requested group, 0 means all
     409   * @param int    $includeall bool include all option
     410   * @param bool   $return If true, will return the HTML, otherwise, will print directly
     411   * @return null
     412   */
     413  function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
     414      global $CFG, $USER, $OUTPUT;
     415      return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
     416  }
     417  
     418  function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
     419      global $USER, $CFG;
     420  
     421      if (is_null($userid)) {
     422          $userid = $USER->id;
     423      }
     424      $coursecontext = context_course::instance($course->id);
     425      $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
     426      $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
     427      $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
     428      $menu = array(); // Will be a list of userid => user name
     429      $menususpendedusers = array(); // Suspended users go to a separate optgroup.
     430      $gui = new graded_users_iterator($course, null, $groupid);
     431      $gui->require_active_enrolment($showonlyactiveenrol);
     432      $gui->init();
     433      $label = get_string('selectauser', 'grades');
     434      if ($includeall) {
     435          $menu[0] = get_string('allusers', 'grades');
     436          $label = get_string('selectalloroneuser', 'grades');
     437      }
     438      while ($userdata = $gui->next_user()) {
     439          $user = $userdata->user;
     440          $userfullname = fullname($user);
     441          if ($user->suspendedenrolment) {
     442              $menususpendedusers[$user->id] = $userfullname;
     443          } else {
     444              $menu[$user->id] = $userfullname;
     445          }
     446      }
     447      $gui->close();
     448  
     449      if ($includeall) {
     450          $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
     451      }
     452  
     453      if (!empty($menususpendedusers)) {
     454          $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
     455      }
     456      $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
     457      $select->label = $label;
     458      $select->formid = 'choosegradeuser';
     459      return $select;
     460  }
     461  
     462  /**
     463   * Hide warning about changed grades during upgrade to 2.8.
     464   *
     465   * @param int $courseid The current course id.
     466   */
     467  function hide_natural_aggregation_upgrade_notice($courseid) {
     468      unset_config('show_sumofgrades_upgrade_' . $courseid);
     469  }
     470  
     471  /**
     472   * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
     473   *
     474   * @param int $courseid The current course id.
     475   */
     476  function grade_hide_min_max_grade_upgrade_notice($courseid) {
     477      unset_config('show_min_max_grades_changed_' . $courseid);
     478  }
     479  
     480  /**
     481   * Use the grade min and max from the grade_grade.
     482   *
     483   * This is reserved for core use after an upgrade.
     484   *
     485   * @param int $courseid The current course id.
     486   */
     487  function grade_upgrade_use_min_max_from_grade_grade($courseid) {
     488      grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
     489  
     490      grade_force_full_regrading($courseid);
     491      // Do this now, because it probably happened to late in the page load to be happen automatically.
     492      grade_regrade_final_grades($courseid);
     493  }
     494  
     495  /**
     496   * Use the grade min and max from the grade_item.
     497   *
     498   * This is reserved for core use after an upgrade.
     499   *
     500   * @param int $courseid The current course id.
     501   */
     502  function grade_upgrade_use_min_max_from_grade_item($courseid) {
     503      grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
     504  
     505      grade_force_full_regrading($courseid);
     506      // Do this now, because it probably happened to late in the page load to be happen automatically.
     507      grade_regrade_final_grades($courseid);
     508  }
     509  
     510  /**
     511   * Hide warning about changed grades during upgrade to 2.8.
     512   *
     513   * @param int $courseid The current course id.
     514   */
     515  function hide_aggregatesubcats_upgrade_notice($courseid) {
     516      unset_config('show_aggregatesubcats_upgrade_' . $courseid);
     517  }
     518  
     519  /**
     520   * Hide warning about changed grades due to bug fixes
     521   *
     522   * @param int $courseid The current course id.
     523   */
     524  function hide_gradebook_calculations_freeze_notice($courseid) {
     525      unset_config('gradebook_calculations_freeze_' . $courseid);
     526  }
     527  
     528  /**
     529   * Print warning about changed grades during upgrade to 2.8.
     530   *
     531   * @param int $courseid The current course id.
     532   * @param context $context The course context.
     533   * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
     534   * @param boolean $return return as string
     535   *
     536   * @return nothing or string if $return true
     537   */
     538  function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
     539      global $CFG, $OUTPUT;
     540      $html = '';
     541  
     542      // Do not do anything if they cannot manage the grades of this course.
     543      if (!has_capability('moodle/grade:manage', $context)) {
     544          return $html;
     545      }
     546  
     547      $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
     548      $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
     549      $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
     550      $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
     551  
     552      $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
     553      $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
     554  
     555      $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
     556      $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
     557  
     558      $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
     559  
     560      $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
     561      $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
     562  
     563      // Hide the warning if the user told it to go away.
     564      if ($hidenaturalwarning) {
     565          hide_natural_aggregation_upgrade_notice($courseid);
     566      }
     567      // Hide the warning if the user told it to go away.
     568      if ($hidesubcatswarning) {
     569          hide_aggregatesubcats_upgrade_notice($courseid);
     570      }
     571  
     572      // Hide the min/max warning if the user told it to go away.
     573      if ($hideminmaxwarning) {
     574          grade_hide_min_max_grade_upgrade_notice($courseid);
     575          $showminmaxwarning = false;
     576      }
     577  
     578      if ($useminmaxfromgradegrade) {
     579          // Revert to the new behaviour, we now use the grade_grade for min/max.
     580          grade_upgrade_use_min_max_from_grade_grade($courseid);
     581          grade_hide_min_max_grade_upgrade_notice($courseid);
     582          $showminmaxwarning = false;
     583  
     584      } else if ($useminmaxfromgradeitem) {
     585          // Apply the new logic, we now use the grade_item for min/max.
     586          grade_upgrade_use_min_max_from_grade_item($courseid);
     587          grade_hide_min_max_grade_upgrade_notice($courseid);
     588          $showminmaxwarning = false;
     589      }
     590  
     591  
     592      if (!$hidenaturalwarning && $shownaturalwarning) {
     593          $message = get_string('sumofgradesupgradedgrades', 'grades');
     594          $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
     595          $urlparams = array( 'id' => $courseid,
     596                              'seensumofgradesupgradedgrades' => true,
     597                              'sesskey' => sesskey());
     598          $goawayurl = new moodle_url($thispage, $urlparams);
     599          $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
     600          $html .= $OUTPUT->notification($message, 'notifysuccess');
     601          $html .= $goawaybutton;
     602      }
     603  
     604      if (!$hidesubcatswarning && $showsubcatswarning) {
     605          $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
     606          $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
     607          $urlparams = array( 'id' => $courseid,
     608                              'seenaggregatesubcatsupgradedgrades' => true,
     609                              'sesskey' => sesskey());
     610          $goawayurl = new moodle_url($thispage, $urlparams);
     611          $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
     612          $html .= $OUTPUT->notification($message, 'notifysuccess');
     613          $html .= $goawaybutton;
     614      }
     615  
     616      if ($showminmaxwarning) {
     617          $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
     618          $urlparams = array( 'id' => $courseid,
     619                              'seenminmaxupgradedgrades' => true,
     620                              'sesskey' => sesskey());
     621  
     622          $goawayurl = new moodle_url($thispage, $urlparams);
     623          $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
     624          $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
     625              array('target' => '_blank'));
     626  
     627          if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
     628              // Show the message that there were min/max issues that have been resolved.
     629              $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
     630  
     631              $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
     632              $urlparams = array('id' => $courseid,
     633                                 'useminmaxfromgradegrade' => true,
     634                                 'sesskey' => sesskey());
     635              $reverturl = new moodle_url($thispage, $urlparams);
     636              $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
     637  
     638              $html .= $OUTPUT->notification($message);
     639              $html .= $revertbutton . $hideminmaxbutton;
     640  
     641          } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
     642              // Show the warning that there are min/max issues that have not be resolved.
     643              $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
     644  
     645              $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
     646              $urlparams = array('id' => $courseid,
     647                                 'useminmaxfromgradeitem' => true,
     648                                 'sesskey' => sesskey());
     649              $fixurl = new moodle_url($thispage, $urlparams);
     650              $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
     651  
     652              $html .= $OUTPUT->notification($message);
     653              $html .= $fixbutton . $hideminmaxbutton;
     654          }
     655      }
     656  
     657      if ($gradebookcalculationsfreeze) {
     658          if ($acceptgradebookchanges) {
     659              // Accept potential changes in grades caused by extra credit bug MDL-49257.
     660              hide_gradebook_calculations_freeze_notice($courseid);
     661              $courseitem = grade_item::fetch_course_item($courseid);
     662              $courseitem->force_regrading();
     663              grade_regrade_final_grades($courseid);
     664  
     665              $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
     666          } else {
     667              // Show the warning that there may be extra credit weights problems.
     668              $a = new stdClass();
     669              $a->gradebookversion = $gradebookcalculationsfreeze;
     670              if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
     671                  $a->currentversion = $matches[1];
     672              } else {
     673                  $a->currentversion = $CFG->release;
     674              }
     675              $a->url = get_docs_url('Gradebook_calculation_changes');
     676              $message = get_string('gradebookcalculationswarning', 'grades', $a);
     677  
     678              $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
     679              $urlparams = array('id' => $courseid,
     680                  'acceptgradebookchanges' => true,
     681                  'sesskey' => sesskey());
     682              $fixurl = new moodle_url($thispage, $urlparams);
     683              $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
     684  
     685              $html .= $OUTPUT->notification($message);
     686              $html .= $fixbutton;
     687          }
     688      }
     689  
     690      if (!empty($html)) {
     691          $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
     692      }
     693  
     694      if ($return) {
     695          return $html;
     696      } else {
     697          echo $html;
     698      }
     699  }
     700  
     701  /**
     702   * Print grading plugin selection popup form.
     703   *
     704   * @param array   $plugin_info An array of plugins containing information for the selector
     705   * @param boolean $return return as string
     706   *
     707   * @return nothing or string if $return true
     708   */
     709  function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
     710      global $CFG, $OUTPUT, $PAGE;
     711  
     712      $menu = array();
     713      $count = 0;
     714      $active = '';
     715  
     716      foreach ($plugin_info as $plugin_type => $plugins) {
     717          if ($plugin_type == 'strings') {
     718              continue;
     719          }
     720  
     721          $first_plugin = reset($plugins);
     722  
     723          $sectionname = $plugin_info['strings'][$plugin_type];
     724          $section = array();
     725  
     726          foreach ($plugins as $plugin) {
     727              $link = $plugin->link->out(false);
     728              $section[$link] = $plugin->string;
     729              $count++;
     730              if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
     731                  $active = $link;
     732              }
     733          }
     734  
     735          if ($section) {
     736              $menu[] = array($sectionname=>$section);
     737          }
     738      }
     739  
     740      // finally print/return the popup form
     741      if ($count > 1) {
     742          $select = new url_select($menu, $active, null, 'choosepluginreport');
     743          $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
     744          if ($return) {
     745              return $OUTPUT->render($select);
     746          } else {
     747              echo $OUTPUT->render($select);
     748          }
     749      } else {
     750          // only one option - no plugin selector needed
     751          return '';
     752      }
     753  }
     754  
     755  /**
     756   * Print grading plugin selection tab-based navigation.
     757   *
     758   * @param string  $active_type type of plugin on current page - import, export, report or edit
     759   * @param string  $active_plugin active plugin type - grader, user, cvs, ...
     760   * @param array   $plugin_info Array of plugins
     761   * @param boolean $return return as string
     762   *
     763   * @return nothing or string if $return true
     764   */
     765  function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
     766      global $CFG, $COURSE;
     767  
     768      if (!isset($currenttab)) { //TODO: this is weird
     769          $currenttab = '';
     770      }
     771  
     772      $tabs = array();
     773      $top_row  = array();
     774      $bottom_row = array();
     775      $inactive = array($active_plugin);
     776      $activated = array($active_type);
     777  
     778      $count = 0;
     779      $active = '';
     780  
     781      foreach ($plugin_info as $plugin_type => $plugins) {
     782          if ($plugin_type == 'strings') {
     783              continue;
     784          }
     785  
     786          // If $plugins is actually the definition of a child-less parent link:
     787          if (!empty($plugins->id)) {
     788              $string = $plugins->string;
     789              if (!empty($plugin_info[$active_type]->parent)) {
     790                  $string = $plugin_info[$active_type]->parent->string;
     791              }
     792  
     793              $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
     794              continue;
     795          }
     796  
     797          $first_plugin = reset($plugins);
     798          $url = $first_plugin->link;
     799  
     800          if ($plugin_type == 'report') {
     801              $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
     802          }
     803  
     804          $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
     805  
     806          if ($active_type == $plugin_type) {
     807              foreach ($plugins as $plugin) {
     808                  $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
     809                  if ($plugin->id == $active_plugin) {
     810                      $inactive = array($plugin->id);
     811                  }
     812              }
     813          }
     814      }
     815  
     816      $tabs[] = $top_row;
     817      $tabs[] = $bottom_row;
     818  
     819      if ($return) {
     820          return print_tabs($tabs, $active_plugin, $inactive, $activated, true);
     821      } else {
     822          print_tabs($tabs, $active_plugin, $inactive, $activated);
     823      }
     824  }
     825  
     826  /**
     827   * grade_get_plugin_info
     828   *
     829   * @param int    $courseid The course id
     830   * @param string $active_type type of plugin on current page - import, export, report or edit
     831   * @param string $active_plugin active plugin type - grader, user, cvs, ...
     832   *
     833   * @return array
     834   */
     835  function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
     836      global $CFG, $SITE;
     837  
     838      $context = context_course::instance($courseid);
     839  
     840      $plugin_info = array();
     841      $count = 0;
     842      $active = '';
     843      $url_prefix = $CFG->wwwroot . '/grade/';
     844  
     845      // Language strings
     846      $plugin_info['strings'] = grade_helper::get_plugin_strings();
     847  
     848      if ($reports = grade_helper::get_plugins_reports($courseid)) {
     849          $plugin_info['report'] = $reports;
     850      }
     851  
     852      if ($settings = grade_helper::get_info_manage_settings($courseid)) {
     853          $plugin_info['settings'] = $settings;
     854      }
     855  
     856      if ($scale = grade_helper::get_info_scales($courseid)) {
     857          $plugin_info['scale'] = array('view'=>$scale);
     858      }
     859  
     860      if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
     861          $plugin_info['outcome'] = $outcomes;
     862      }
     863  
     864      if ($letters = grade_helper::get_info_letters($courseid)) {
     865          $plugin_info['letter'] = $letters;
     866      }
     867  
     868      if ($imports = grade_helper::get_plugins_import($courseid)) {
     869          $plugin_info['import'] = $imports;
     870      }
     871  
     872      if ($exports = grade_helper::get_plugins_export($courseid)) {
     873          $plugin_info['export'] = $exports;
     874      }
     875  
     876      foreach ($plugin_info as $plugin_type => $plugins) {
     877          if (!empty($plugins->id) && $active_plugin == $plugins->id) {
     878              $plugin_info['strings']['active_plugin_str'] = $plugins->string;
     879              break;
     880          }
     881          foreach ($plugins as $plugin) {
     882              if (is_a($plugin, 'grade_plugin_info')) {
     883                  if ($active_plugin == $plugin->id) {
     884                      $plugin_info['strings']['active_plugin_str'] = $plugin->string;
     885                  }
     886              }
     887          }
     888      }
     889  
     890      foreach ($plugin_info as $plugin_type => $plugins) {
     891          if (!empty($plugins->id) && $active_plugin == $plugins->id) {
     892              $plugin_info['strings']['active_plugin_str'] = $plugins->string;
     893              break;
     894          }
     895          foreach ($plugins as $plugin) {
     896              if (is_a($plugin, 'grade_plugin_info')) {
     897                  if ($active_plugin == $plugin->id) {
     898                      $plugin_info['strings']['active_plugin_str'] = $plugin->string;
     899                  }
     900              }
     901          }
     902      }
     903  
     904      return $plugin_info;
     905  }
     906  
     907  /**
     908   * A simple class containing info about grade plugins.
     909   * Can be subclassed for special rules
     910   *
     911   * @package core_grades
     912   * @copyright 2009 Nicolas Connault
     913   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
     914   */
     915  class grade_plugin_info {
     916      /**
     917       * A unique id for this plugin
     918       *
     919       * @var mixed
     920       */
     921      public $id;
     922      /**
     923       * A URL to access this plugin
     924       *
     925       * @var mixed
     926       */
     927      public $link;
     928      /**
     929       * The name of this plugin
     930       *
     931       * @var mixed
     932       */
     933      public $string;
     934      /**
     935       * Another grade_plugin_info object, parent of the current one
     936       *
     937       * @var mixed
     938       */
     939      public $parent;
     940  
     941      /**
     942       * Constructor
     943       *
     944       * @param int $id A unique id for this plugin
     945       * @param string $link A URL to access this plugin
     946       * @param string $string The name of this plugin
     947       * @param object $parent Another grade_plugin_info object, parent of the current one
     948       *
     949       * @return void
     950       */
     951      public function __construct($id, $link, $string, $parent=null) {
     952          $this->id = $id;
     953          $this->link = $link;
     954          $this->string = $string;
     955          $this->parent = $parent;
     956      }
     957  }
     958  
     959  /**
     960   * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
     961   * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
     962   * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
     963   * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
     964   * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
     965   *
     966   * @param int     $courseid Course id
     967   * @param string  $active_type The type of the current page (report, settings,
     968   *                             import, export, scales, outcomes, letters)
     969   * @param string  $active_plugin The plugin of the current page (grader, fullview etc...)
     970   * @param string  $heading The heading of the page. Tries to guess if none is given
     971   * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
     972   * @param string  $bodytags Additional attributes that will be added to the <body> tag
     973   * @param string  $buttons Additional buttons to display on the page
     974   * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
     975   * @param string  $headerhelpidentifier The help string identifier if required.
     976   * @param string  $headerhelpcomponent The component for the help string.
     977   *
     978   * @return string HTML code or nothing if $return == false
     979   */
     980  function print_grade_page_head($courseid, $active_type, $active_plugin=null,
     981                                 $heading = false, $return=false,
     982                                 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null) {
     983      global $CFG, $OUTPUT, $PAGE;
     984  
     985      if ($active_type === 'preferences') {
     986          // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
     987          $active_type = 'settings';
     988      }
     989  
     990      $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
     991  
     992      // Determine the string of the active plugin
     993      $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
     994      $stractive_type = $plugin_info['strings'][$active_type];
     995  
     996      if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
     997          $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
     998      } else {
     999          $title = $PAGE->course->fullname.': ' . $stractive_plugin;
    1000      }
    1001  
    1002      if ($active_type == 'report') {
    1003          $PAGE->set_pagelayout('report');
    1004      } else {
    1005          $PAGE->set_pagelayout('admin');
    1006      }
    1007      $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
    1008      $PAGE->set_heading($title);
    1009      if ($buttons instanceof single_button) {
    1010          $buttons = $OUTPUT->render($buttons);
    1011      }
    1012      $PAGE->set_button($buttons);
    1013      if ($courseid != SITEID) {
    1014          grade_extend_settings($plugin_info, $courseid);
    1015      }
    1016  
    1017      $returnval = $OUTPUT->header();
    1018  
    1019      if (!$return) {
    1020          echo $returnval;
    1021      }
    1022  
    1023      // Guess heading if not given explicitly
    1024      if (!$heading) {
    1025          $heading = $stractive_plugin;
    1026      }
    1027  
    1028      if ($shownavigation) {
    1029          if ($courseid != SITEID &&
    1030                  ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
    1031              $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
    1032          }
    1033  
    1034          $output = '';
    1035          // Add a help dialogue box if provided.
    1036          if (isset($headerhelpidentifier)) {
    1037              $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
    1038          } else {
    1039              $output = $OUTPUT->heading($heading);
    1040          }
    1041  
    1042          if ($return) {
    1043              $returnval .= $output;
    1044          } else {
    1045              echo $output;
    1046          }
    1047  
    1048          if ($courseid != SITEID &&
    1049                  ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
    1050              $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
    1051          }
    1052      }
    1053  
    1054      $returnval .= print_natural_aggregation_upgrade_notice($courseid,
    1055                                                             context_course::instance($courseid),
    1056                                                             $PAGE->url,
    1057                                                             $return);
    1058  
    1059      if ($return) {
    1060          return $returnval;
    1061      }
    1062  }
    1063  
    1064  /**
    1065   * Utility class used for return tracking when using edit and other forms in grade plugins
    1066   *
    1067   * @package core_grades
    1068   * @copyright 2009 Nicolas Connault
    1069   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1070   */
    1071  class grade_plugin_return {
    1072      public $type;
    1073      public $plugin;
    1074      public $courseid;
    1075      public $userid;
    1076      public $page;
    1077  
    1078      /**
    1079       * Constructor
    1080       *
    1081       * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
    1082       */
    1083      public function grade_plugin_return($params = null) {
    1084          if (empty($params)) {
    1085              $this->type     = optional_param('gpr_type', null, PARAM_SAFEDIR);
    1086              $this->plugin   = optional_param('gpr_plugin', null, PARAM_PLUGIN);
    1087              $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
    1088              $this->userid   = optional_param('gpr_userid', null, PARAM_INT);
    1089              $this->page     = optional_param('gpr_page', null, PARAM_INT);
    1090  
    1091          } else {
    1092              foreach ($params as $key=>$value) {
    1093                  if (property_exists($this, $key)) {
    1094                      $this->$key = $value;
    1095                  }
    1096              }
    1097          }
    1098      }
    1099  
    1100      /**
    1101       * Returns return parameters as options array suitable for buttons.
    1102       * @return array options
    1103       */
    1104      public function get_options() {
    1105          if (empty($this->type)) {
    1106              return array();
    1107          }
    1108  
    1109          $params = array();
    1110  
    1111          if (!empty($this->plugin)) {
    1112              $params['plugin'] = $this->plugin;
    1113          }
    1114  
    1115          if (!empty($this->courseid)) {
    1116              $params['id'] = $this->courseid;
    1117          }
    1118  
    1119          if (!empty($this->userid)) {
    1120              $params['userid'] = $this->userid;
    1121          }
    1122  
    1123          if (!empty($this->page)) {
    1124              $params['page'] = $this->page;
    1125          }
    1126  
    1127          return $params;
    1128      }
    1129  
    1130      /**
    1131       * Returns return url
    1132       *
    1133       * @param string $default default url when params not set
    1134       * @param array  $extras Extra URL parameters
    1135       *
    1136       * @return string url
    1137       */
    1138      public function get_return_url($default, $extras=null) {
    1139          global $CFG;
    1140  
    1141          if (empty($this->type) or empty($this->plugin)) {
    1142              return $default;
    1143          }
    1144  
    1145          $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
    1146          $glue = '?';
    1147  
    1148          if (!empty($this->courseid)) {
    1149              $url .= $glue.'id='.$this->courseid;
    1150              $glue = '&amp;';
    1151          }
    1152  
    1153          if (!empty($this->userid)) {
    1154              $url .= $glue.'userid='.$this->userid;
    1155              $glue = '&amp;';
    1156          }
    1157  
    1158          if (!empty($this->page)) {
    1159              $url .= $glue.'page='.$this->page;
    1160              $glue = '&amp;';
    1161          }
    1162  
    1163          if (!empty($extras)) {
    1164              foreach ($extras as $key=>$value) {
    1165                  $url .= $glue.$key.'='.$value;
    1166                  $glue = '&amp;';
    1167              }
    1168          }
    1169  
    1170          return $url;
    1171      }
    1172  
    1173      /**
    1174       * Returns string with hidden return tracking form elements.
    1175       * @return string
    1176       */
    1177      public function get_form_fields() {
    1178          if (empty($this->type)) {
    1179              return '';
    1180          }
    1181  
    1182          $result  = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
    1183  
    1184          if (!empty($this->plugin)) {
    1185              $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
    1186          }
    1187  
    1188          if (!empty($this->courseid)) {
    1189              $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
    1190          }
    1191  
    1192          if (!empty($this->userid)) {
    1193              $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
    1194          }
    1195  
    1196          if (!empty($this->page)) {
    1197              $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
    1198          }
    1199      }
    1200  
    1201      /**
    1202       * Add hidden elements into mform
    1203       *
    1204       * @param object &$mform moodle form object
    1205       *
    1206       * @return void
    1207       */
    1208      public function add_mform_elements(&$mform) {
    1209          if (empty($this->type)) {
    1210              return;
    1211          }
    1212  
    1213          $mform->addElement('hidden', 'gpr_type', $this->type);
    1214          $mform->setType('gpr_type', PARAM_SAFEDIR);
    1215  
    1216          if (!empty($this->plugin)) {
    1217              $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
    1218              $mform->setType('gpr_plugin', PARAM_PLUGIN);
    1219          }
    1220  
    1221          if (!empty($this->courseid)) {
    1222              $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
    1223              $mform->setType('gpr_courseid', PARAM_INT);
    1224          }
    1225  
    1226          if (!empty($this->userid)) {
    1227              $mform->addElement('hidden', 'gpr_userid', $this->userid);
    1228              $mform->setType('gpr_userid', PARAM_INT);
    1229          }
    1230  
    1231          if (!empty($this->page)) {
    1232              $mform->addElement('hidden', 'gpr_page', $this->page);
    1233              $mform->setType('gpr_page', PARAM_INT);
    1234          }
    1235      }
    1236  
    1237      /**
    1238       * Add return tracking params into url
    1239       *
    1240       * @param moodle_url $url A URL
    1241       *
    1242       * @return string $url with return tracking params
    1243       */
    1244      public function add_url_params(moodle_url $url) {
    1245          if (empty($this->type)) {
    1246              return $url;
    1247          }
    1248  
    1249          $url->param('gpr_type', $this->type);
    1250  
    1251          if (!empty($this->plugin)) {
    1252              $url->param('gpr_plugin', $this->plugin);
    1253          }
    1254  
    1255          if (!empty($this->courseid)) {
    1256              $url->param('gpr_courseid' ,$this->courseid);
    1257          }
    1258  
    1259          if (!empty($this->userid)) {
    1260              $url->param('gpr_userid', $this->userid);
    1261          }
    1262  
    1263          if (!empty($this->page)) {
    1264              $url->param('gpr_page', $this->page);
    1265          }
    1266  
    1267          return $url;
    1268      }
    1269  }
    1270  
    1271  /**
    1272   * Function central to gradebook for building and printing the navigation (breadcrumb trail).
    1273   *
    1274   * @param string $path The path of the calling script (using __FILE__?)
    1275   * @param string $pagename The language string to use as the last part of the navigation (non-link)
    1276   * @param mixed  $id Either a plain integer (assuming the key is 'id') or
    1277   *                   an array of keys and values (e.g courseid => $courseid, itemid...)
    1278   *
    1279   * @return string
    1280   */
    1281  function grade_build_nav($path, $pagename=null, $id=null) {
    1282      global $CFG, $COURSE, $PAGE;
    1283  
    1284      $strgrades = get_string('grades', 'grades');
    1285  
    1286      // Parse the path and build navlinks from its elements
    1287      $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
    1288      $path = substr($path, $dirroot_length);
    1289      $path = str_replace('\\', '/', $path);
    1290  
    1291      $path_elements = explode('/', $path);
    1292  
    1293      $path_elements_count = count($path_elements);
    1294  
    1295      // First link is always 'grade'
    1296      $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
    1297  
    1298      $link = null;
    1299      $numberofelements = 3;
    1300  
    1301      // Prepare URL params string
    1302      $linkparams = array();
    1303      if (!is_null($id)) {
    1304          if (is_array($id)) {
    1305              foreach ($id as $idkey => $idvalue) {
    1306                  $linkparams[$idkey] = $idvalue;
    1307              }
    1308          } else {
    1309              $linkparams['id'] = $id;
    1310          }
    1311      }
    1312  
    1313      $navlink4 = null;
    1314  
    1315      // Remove file extensions from filenames
    1316      foreach ($path_elements as $key => $filename) {
    1317          $path_elements[$key] = str_replace('.php', '', $filename);
    1318      }
    1319  
    1320      // Second level links
    1321      switch ($path_elements[1]) {
    1322          case 'edit': // No link
    1323              if ($path_elements[3] != 'index.php') {
    1324                  $numberofelements = 4;
    1325              }
    1326              break;
    1327          case 'import': // No link
    1328              break;
    1329          case 'export': // No link
    1330              break;
    1331          case 'report':
    1332              // $id is required for this link. Do not print it if $id isn't given
    1333              if (!is_null($id)) {
    1334                  $link = new moodle_url('/grade/report/index.php', $linkparams);
    1335              }
    1336  
    1337              if ($path_elements[2] == 'grader') {
    1338                  $numberofelements = 4;
    1339              }
    1340              break;
    1341  
    1342          default:
    1343              // If this element isn't among the ones already listed above, it isn't supported, throw an error.
    1344              debugging("grade_build_nav() doesn't support ". $path_elements[1] .
    1345                      " as the second path element after 'grade'.");
    1346              return false;
    1347      }
    1348      $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
    1349  
    1350      // Third level links
    1351      if (empty($pagename)) {
    1352          $pagename = get_string($path_elements[2], 'grades');
    1353      }
    1354  
    1355      switch ($numberofelements) {
    1356          case 3:
    1357              $PAGE->navbar->add($pagename, $link);
    1358              break;
    1359          case 4:
    1360              if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
    1361                  $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
    1362              }
    1363              $PAGE->navbar->add($pagename);
    1364              break;
    1365      }
    1366  
    1367      return '';
    1368  }
    1369  
    1370  /**
    1371   * General structure representing grade items in course
    1372   *
    1373   * @package core_grades
    1374   * @copyright 2009 Nicolas Connault
    1375   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1376   */
    1377  class grade_structure {
    1378      public $context;
    1379  
    1380      public $courseid;
    1381  
    1382      /**
    1383      * Reference to modinfo for current course (for performance, to save
    1384      * retrieving it from courseid every time). Not actually set except for
    1385      * the grade_tree type.
    1386      * @var course_modinfo
    1387      */
    1388      public $modinfo;
    1389  
    1390      /**
    1391       * 1D array of grade items only
    1392       */
    1393      public $items;
    1394  
    1395      /**
    1396       * Returns icon of element
    1397       *
    1398       * @param array &$element An array representing an element in the grade_tree
    1399       * @param bool  $spacerifnone return spacer if no icon found
    1400       *
    1401       * @return string icon or spacer
    1402       */
    1403      public function get_element_icon(&$element, $spacerifnone=false) {
    1404          global $CFG, $OUTPUT;
    1405          require_once $CFG->libdir.'/filelib.php';
    1406  
    1407          switch ($element['type']) {
    1408              case 'item':
    1409              case 'courseitem':
    1410              case 'categoryitem':
    1411                  $is_course   = $element['object']->is_course_item();
    1412                  $is_category = $element['object']->is_category_item();
    1413                  $is_scale    = $element['object']->gradetype == GRADE_TYPE_SCALE;
    1414                  $is_value    = $element['object']->gradetype == GRADE_TYPE_VALUE;
    1415                  $is_outcome  = !empty($element['object']->outcomeid);
    1416  
    1417                  if ($element['object']->is_calculated()) {
    1418                      $strcalc = get_string('calculatedgrade', 'grades');
    1419                      return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
    1420                              s($strcalc).'" alt="'.s($strcalc).'"/>';
    1421  
    1422                  } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
    1423                      if ($category = $element['object']->get_item_category()) {
    1424                          $aggrstrings = grade_helper::get_aggregation_strings();
    1425                          $stragg = $aggrstrings[$category->aggregation];
    1426                          switch ($category->aggregation) {
    1427                              case GRADE_AGGREGATE_MEAN:
    1428                              case GRADE_AGGREGATE_MEDIAN:
    1429                              case GRADE_AGGREGATE_WEIGHTED_MEAN:
    1430                              case GRADE_AGGREGATE_WEIGHTED_MEAN2:
    1431                              case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
    1432                                  return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
    1433                                          'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
    1434                              case GRADE_AGGREGATE_SUM:
    1435                                  return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
    1436                                          'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
    1437                              default:
    1438                                  return '<img src="'.$OUTPUT->pix_url('i/calc') . '" ' .
    1439                                          'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
    1440                          }
    1441                      }
    1442  
    1443                  } else if ($element['object']->itemtype == 'mod') {
    1444                      //prevent outcomes being displaying the same icon as the activity they are attached to
    1445                      if ($is_outcome) {
    1446                          $stroutcome = s(get_string('outcome', 'grades'));
    1447                          return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
    1448                              'class="icon itemicon" title="'.$stroutcome.
    1449                              '" alt="'.$stroutcome.'"/>';
    1450                      } else {
    1451                          $strmodname = get_string('modulename', $element['object']->itemmodule);
    1452                          return '<img src="'.$OUTPUT->pix_url('icon',
    1453                              $element['object']->itemmodule) . '" ' .
    1454                              'class="icon itemicon" title="' .s($strmodname).
    1455                              '" alt="' .s($strmodname).'"/>';
    1456                      }
    1457                  } else if ($element['object']->itemtype == 'manual') {
    1458                      if ($element['object']->is_outcome_item()) {
    1459                          $stroutcome = get_string('outcome', 'grades');
    1460                          return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
    1461                                  'class="icon itemicon" title="'.s($stroutcome).
    1462                                  '" alt="'.s($stroutcome).'"/>';
    1463                      } else {
    1464                          $strmanual = get_string('manualitem', 'grades');
    1465                          return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
    1466                                  'class="icon itemicon" title="'.s($strmanual).
    1467                                  '" alt="'.s($strmanual).'"/>';
    1468                      }
    1469                  }
    1470                  break;
    1471  
    1472              case 'category':
    1473                  $strcat = get_string('category', 'grades');
    1474                  return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
    1475                          'title="'.s($strcat).'" alt="'.s($strcat).'" />';
    1476          }
    1477  
    1478          if ($spacerifnone) {
    1479              return $OUTPUT->spacer().' ';
    1480          } else {
    1481              return '';
    1482          }
    1483      }
    1484  
    1485      /**
    1486       * Returns name of element optionally with icon and link
    1487       *
    1488       * @param array &$element An array representing an element in the grade_tree
    1489       * @param bool  $withlink Whether or not this header has a link
    1490       * @param bool  $icon Whether or not to display an icon with this header
    1491       * @param bool  $spacerifnone return spacer if no icon found
    1492       * @param bool  $withdescription Show description if defined by this item.
    1493       * @param bool  $fulltotal If the item is a category total, returns $categoryname."total"
    1494       *                         instead of "Category total" or "Course total"
    1495       *
    1496       * @return string header
    1497       */
    1498      public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
    1499          $withdescription = false, $fulltotal = false) {
    1500          $header = '';
    1501  
    1502          if ($icon) {
    1503              $header .= $this->get_element_icon($element, $spacerifnone);
    1504          }
    1505  
    1506          $header .= $element['object']->get_name($fulltotal);
    1507  
    1508          if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
    1509              $element['type'] != 'courseitem') {
    1510              return $header;
    1511          }
    1512  
    1513          if ($withlink && $url = $this->get_activity_link($element)) {
    1514              $a = new stdClass();
    1515              $a->name = get_string('modulename', $element['object']->itemmodule);
    1516              $title = get_string('linktoactivity', 'grades', $a);
    1517  
    1518              $header = html_writer::link($url, $header, array('title' => $title));
    1519          } else {
    1520              $header = html_writer::span($header);
    1521          }
    1522  
    1523          if ($withdescription) {
    1524              $desc = $element['object']->get_description();
    1525              if (!empty($desc)) {
    1526                  $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
    1527              }
    1528          }
    1529  
    1530          return $header;
    1531      }
    1532  
    1533      private function get_activity_link($element) {
    1534          global $CFG;
    1535          /** @var array static cache of the grade.php file existence flags */
    1536          static $hasgradephp = array();
    1537  
    1538          $itemtype = $element['object']->itemtype;
    1539          $itemmodule = $element['object']->itemmodule;
    1540          $iteminstance = $element['object']->iteminstance;
    1541          $itemnumber = $element['object']->itemnumber;
    1542  
    1543          // Links only for module items that have valid instance, module and are
    1544          // called from grade_tree with valid modinfo
    1545          if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
    1546              return null;
    1547          }
    1548  
    1549          // Get $cm efficiently and with visibility information using modinfo
    1550          $instances = $this->modinfo->get_instances();
    1551          if (empty($instances[$itemmodule][$iteminstance])) {
    1552              return null;
    1553          }
    1554          $cm = $instances[$itemmodule][$iteminstance];
    1555  
    1556          // Do not add link if activity is not visible to the current user
    1557          if (!$cm->uservisible) {
    1558              return null;
    1559          }
    1560  
    1561          if (!array_key_exists($itemmodule, $hasgradephp)) {
    1562              if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
    1563                  $hasgradephp[$itemmodule] = true;
    1564              } else {
    1565                  $hasgradephp[$itemmodule] = false;
    1566              }
    1567          }
    1568  
    1569          // If module has grade.php, link to that, otherwise view.php
    1570          if ($hasgradephp[$itemmodule]) {
    1571              $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
    1572              if (isset($element['userid'])) {
    1573                  $args['userid'] = $element['userid'];
    1574              }
    1575              return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
    1576          } else {
    1577              return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
    1578          }
    1579      }
    1580  
    1581      /**
    1582       * Returns URL of a page that is supposed to contain detailed grade analysis
    1583       *
    1584       * At the moment, only activity modules are supported. The method generates link
    1585       * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
    1586       * gradeid and userid. If the grade.php does not exist, null is returned.
    1587       *
    1588       * @return moodle_url|null URL or null if unable to construct it
    1589       */
    1590      public function get_grade_analysis_url(grade_grade $grade) {
    1591          global $CFG;
    1592          /** @var array static cache of the grade.php file existence flags */
    1593          static $hasgradephp = array();
    1594  
    1595          if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
    1596              throw new coding_exception('Passed grade without the associated grade item');
    1597          }
    1598          $item = $grade->grade_item;
    1599  
    1600          if (!$item->is_external_item()) {
    1601              // at the moment, only activity modules are supported
    1602              return null;
    1603          }
    1604          if ($item->itemtype !== 'mod') {
    1605              throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
    1606          }
    1607          if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
    1608              return null;
    1609          }
    1610  
    1611          if (!array_key_exists($item->itemmodule, $hasgradephp)) {
    1612              if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
    1613                  $hasgradephp[$item->itemmodule] = true;
    1614              } else {
    1615                  $hasgradephp[$item->itemmodule] = false;
    1616              }
    1617          }
    1618  
    1619          if (!$hasgradephp[$item->itemmodule]) {
    1620              return null;
    1621          }
    1622  
    1623          $instances = $this->modinfo->get_instances();
    1624          if (empty($instances[$item->itemmodule][$item->iteminstance])) {
    1625              return null;
    1626          }
    1627          $cm = $instances[$item->itemmodule][$item->iteminstance];
    1628          if (!$cm->uservisible) {
    1629              return null;
    1630          }
    1631  
    1632          $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
    1633              'id'         => $cm->id,
    1634              'itemid'     => $item->id,
    1635              'itemnumber' => $item->itemnumber,
    1636              'gradeid'    => $grade->id,
    1637              'userid'     => $grade->userid,
    1638          ));
    1639  
    1640          return $url;
    1641      }
    1642  
    1643      /**
    1644       * Returns an action icon leading to the grade analysis page
    1645       *
    1646       * @param grade_grade $grade
    1647       * @return string
    1648       */
    1649      public function get_grade_analysis_icon(grade_grade $grade) {
    1650          global $OUTPUT;
    1651  
    1652          $url = $this->get_grade_analysis_url($grade);
    1653          if (is_null($url)) {
    1654              return '';
    1655          }
    1656  
    1657          return $OUTPUT->action_icon($url, new pix_icon('t/preview',
    1658              get_string('gradeanalysis', 'core_grades')));
    1659      }
    1660  
    1661      /**
    1662       * Returns the grade eid - the grade may not exist yet.
    1663       *
    1664       * @param grade_grade $grade_grade A grade_grade object
    1665       *
    1666       * @return string eid
    1667       */
    1668      public function get_grade_eid($grade_grade) {
    1669          if (empty($grade_grade->id)) {
    1670              return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
    1671          } else {
    1672              return 'g'.$grade_grade->id;
    1673          }
    1674      }
    1675  
    1676      /**
    1677       * Returns the grade_item eid
    1678       * @param grade_item $grade_item A grade_item object
    1679       * @return string eid
    1680       */
    1681      public function get_item_eid($grade_item) {
    1682          return 'ig'.$grade_item->id;
    1683      }
    1684  
    1685      /**
    1686       * Given a grade_tree element, returns an array of parameters
    1687       * used to build an icon for that element.
    1688       *
    1689       * @param array $element An array representing an element in the grade_tree
    1690       *
    1691       * @return array
    1692       */
    1693      public function get_params_for_iconstr($element) {
    1694          $strparams = new stdClass();
    1695          $strparams->category = '';
    1696          $strparams->itemname = '';
    1697          $strparams->itemmodule = '';
    1698  
    1699          if (!method_exists($element['object'], 'get_name')) {
    1700              return $strparams;
    1701          }
    1702  
    1703          $strparams->itemname = html_to_text($element['object']->get_name());
    1704  
    1705          // If element name is categorytotal, get the name of the parent category
    1706          if ($strparams->itemname == get_string('categorytotal', 'grades')) {
    1707              $parent = $element['object']->get_parent_category();
    1708              $strparams->category = $parent->get_name() . ' ';
    1709          } else {
    1710              $strparams->category = '';
    1711          }
    1712  
    1713          $strparams->itemmodule = null;
    1714          if (isset($element['object']->itemmodule)) {
    1715              $strparams->itemmodule = $element['object']->itemmodule;
    1716          }
    1717          return $strparams;
    1718      }
    1719  
    1720      /**
    1721       * Return a reset icon for the given element.
    1722       *
    1723       * @param array  $element An array representing an element in the grade_tree
    1724       * @param object $gpr A grade_plugin_return object
    1725       * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
    1726       * @return string|action_menu_link
    1727       */
    1728      public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
    1729          global $CFG, $OUTPUT;
    1730  
    1731          // Limit to category items set to use the natural weights aggregation method, and users
    1732          // with the capability to manage grades.
    1733          if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
    1734                  !has_capability('moodle/grade:manage', $this->context)) {
    1735              return $returnactionmenulink ? null : '';
    1736          }
    1737  
    1738          $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
    1739          $url = new moodle_url('/grade/edit/tree/action.php', array(
    1740              'id' => $this->courseid,
    1741              'action' => 'resetweights',
    1742              'eid' => $element['eid'],
    1743              'sesskey' => sesskey(),
    1744          ));
    1745  
    1746          if ($returnactionmenulink) {
    1747              return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
    1748                  get_string('resetweightsshort', 'grades'));
    1749          } else {
    1750              return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
    1751          }
    1752      }
    1753  
    1754      /**
    1755       * Return edit icon for give element
    1756       *
    1757       * @param array  $element An array representing an element in the grade_tree
    1758       * @param object $gpr A grade_plugin_return object
    1759       * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
    1760       * @return string|action_menu_link
    1761       */
    1762      public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
    1763          global $CFG, $OUTPUT;
    1764  
    1765          if (!has_capability('moodle/grade:manage', $this->context)) {
    1766              if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
    1767                  // oki - let them override grade
    1768              } else {
    1769                  return $returnactionmenulink ? null : '';
    1770              }
    1771          }
    1772  
    1773          static $strfeedback   = null;
    1774          static $streditgrade = null;
    1775          if (is_null($streditgrade)) {
    1776              $streditgrade = get_string('editgrade', 'grades');
    1777              $strfeedback  = get_string('feedback');
    1778          }
    1779  
    1780          $strparams = $this->get_params_for_iconstr($element);
    1781  
    1782          $object = $element['object'];
    1783  
    1784          switch ($element['type']) {
    1785              case 'item':
    1786              case 'categoryitem':
    1787              case 'courseitem':
    1788                  $stredit = get_string('editverbose', 'grades', $strparams);
    1789                  if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
    1790                      $url = new moodle_url('/grade/edit/tree/item.php',
    1791                              array('courseid' => $this->courseid, 'id' => $object->id));
    1792                  } else {
    1793                      $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
    1794                              array('courseid' => $this->courseid, 'id' => $object->id));
    1795                  }
    1796                  break;
    1797  
    1798              case 'category':
    1799                  $stredit = get_string('editverbose', 'grades', $strparams);
    1800                  $url = new moodle_url('/grade/edit/tree/category.php',
    1801                          array('courseid' => $this->courseid, 'id' => $object->id));
    1802                  break;
    1803  
    1804              case 'grade':
    1805                  $stredit = $streditgrade;
    1806                  if (empty($object->id)) {
    1807                      $url = new moodle_url('/grade/edit/tree/grade.php',
    1808                              array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
    1809                  } else {
    1810                      $url = new moodle_url('/grade/edit/tree/grade.php',
    1811                              array('courseid' => $this->courseid, 'id' => $object->id));
    1812                  }
    1813                  if (!empty($object->feedback)) {
    1814                      $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
    1815                  }
    1816                  break;
    1817  
    1818              default:
    1819                  $url = null;
    1820          }
    1821  
    1822          if ($url) {
    1823              if ($returnactionmenulink) {
    1824                  return new action_menu_link_secondary($gpr->add_url_params($url),
    1825                      new pix_icon('t/edit', $stredit),
    1826                      get_string('editsettings'));
    1827              } else {
    1828                  return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
    1829              }
    1830  
    1831          } else {
    1832              return $returnactionmenulink ? null : '';
    1833          }
    1834      }
    1835  
    1836      /**
    1837       * Return hiding icon for give element
    1838       *
    1839       * @param array  $element An array representing an element in the grade_tree
    1840       * @param object $gpr A grade_plugin_return object
    1841       * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
    1842       * @return string|action_menu_link
    1843       */
    1844      public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
    1845          global $CFG, $OUTPUT;
    1846  
    1847          if (!$element['object']->can_control_visibility()) {
    1848              return $returnactionmenulink ? null : '';
    1849          }
    1850  
    1851          if (!has_capability('moodle/grade:manage', $this->context) and
    1852              !has_capability('moodle/grade:hide', $this->context)) {
    1853              return $returnactionmenulink ? null : '';
    1854          }
    1855  
    1856          $strparams = $this->get_params_for_iconstr($element);
    1857          $strshow = get_string('showverbose', 'grades', $strparams);
    1858          $strhide = get_string('hideverbose', 'grades', $strparams);
    1859  
    1860          $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
    1861          $url = $gpr->add_url_params($url);
    1862  
    1863          if ($element['object']->is_hidden()) {
    1864              $type = 'show';
    1865              $tooltip = $strshow;
    1866  
    1867              // Change the icon and add a tooltip showing the date
    1868              if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
    1869                  $type = 'hiddenuntil';
    1870                  $tooltip = get_string('hiddenuntildate', 'grades',
    1871                          userdate($element['object']->get_hidden()));
    1872              }
    1873  
    1874              $url->param('action', 'show');
    1875  
    1876              if ($returnactionmenulink) {
    1877                  $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
    1878              } else {
    1879                  $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
    1880              }
    1881  
    1882          } else {
    1883              $url->param('action', 'hide');
    1884              if ($returnactionmenulink) {
    1885                  $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
    1886              } else {
    1887                  $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
    1888              }
    1889          }
    1890  
    1891          return $hideicon;
    1892      }
    1893  
    1894      /**
    1895       * Return locking icon for given element
    1896       *
    1897       * @param array  $element An array representing an element in the grade_tree
    1898       * @param object $gpr A grade_plugin_return object
    1899       *
    1900       * @return string
    1901       */
    1902      public function get_locking_icon($element, $gpr) {
    1903          global $CFG, $OUTPUT;
    1904  
    1905          $strparams = $this->get_params_for_iconstr($element);
    1906          $strunlock = get_string('unlockverbose', 'grades', $strparams);
    1907          $strlock = get_string('lockverbose', 'grades', $strparams);
    1908  
    1909          $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
    1910          $url = $gpr->add_url_params($url);
    1911  
    1912          // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
    1913          if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
    1914              $strparamobj = new stdClass();
    1915              $strparamobj->itemname = $element['object']->grade_item->itemname;
    1916              $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
    1917  
    1918              $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
    1919                      array('class' => 'action-icon'));
    1920  
    1921          } else if ($element['object']->is_locked()) {
    1922              $type = 'unlock';
    1923              $tooltip = $strunlock;
    1924  
    1925              // Change the icon and add a tooltip showing the date
    1926              if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
    1927                  $type = 'locktime';
    1928                  $tooltip = get_string('locktimedate', 'grades',
    1929                          userdate($element['object']->get_locktime()));
    1930              }
    1931  
    1932              if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
    1933                  $action = '';
    1934              } else {
    1935                  $url->param('action', 'unlock');
    1936                  $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
    1937              }
    1938  
    1939          } else {
    1940              if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
    1941                  $action = '';
    1942              } else {
    1943                  $url->param('action', 'lock');
    1944                  $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
    1945              }
    1946          }
    1947  
    1948          return $action;
    1949      }
    1950  
    1951      /**
    1952       * Return calculation icon for given element
    1953       *
    1954       * @param array  $element An array representing an element in the grade_tree
    1955       * @param object $gpr A grade_plugin_return object
    1956       * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
    1957       * @return string|action_menu_link
    1958       */
    1959      public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
    1960          global $CFG, $OUTPUT;
    1961          if (!has_capability('moodle/grade:manage', $this->context)) {
    1962              return $returnactionmenulink ? null : '';
    1963          }
    1964  
    1965          $type   = $element['type'];
    1966          $object = $element['object'];
    1967  
    1968          if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
    1969              $strparams = $this->get_params_for_iconstr($element);
    1970              $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
    1971  
    1972              $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
    1973              $is_value = $object->gradetype == GRADE_TYPE_VALUE;
    1974  
    1975              // show calculation icon only when calculation possible
    1976              if (!$object->is_external_item() and ($is_scale or $is_value)) {
    1977                  if ($object->is_calculated()) {
    1978                      $icon = 't/calc';
    1979                  } else {
    1980                      $icon = 't/calc_off';
    1981                  }
    1982  
    1983                  $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
    1984                  $url = $gpr->add_url_params($url);
    1985                  if ($returnactionmenulink) {
    1986                      return new action_menu_link_secondary($url,
    1987                          new pix_icon($icon, $streditcalculation),
    1988                          get_string('editcalculation', 'grades'));
    1989                  } else {
    1990                      return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
    1991                  }
    1992              }
    1993          }
    1994  
    1995          return $returnactionmenulink ? null : '';
    1996      }
    1997  }
    1998  
    1999  /**
    2000   * Flat structure similar to grade tree.
    2001   *
    2002   * @uses grade_structure
    2003   * @package core_grades
    2004   * @copyright 2009 Nicolas Connault
    2005   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2006   */
    2007  class grade_seq extends grade_structure {
    2008  
    2009      /**
    2010       * 1D array of elements
    2011       */
    2012      public $elements;
    2013  
    2014      /**
    2015       * Constructor, retrieves and stores array of all grade_category and grade_item
    2016       * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
    2017       *
    2018       * @param int  $courseid The course id
    2019       * @param bool $category_grade_last category grade item is the last child
    2020       * @param bool $nooutcomes Whether or not outcomes should be included
    2021       */
    2022      public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
    2023          global $USER, $CFG;
    2024  
    2025          $this->courseid   = $courseid;
    2026          $this->context    = context_course::instance($courseid);
    2027  
    2028          // get course grade tree
    2029          $top_element = grade_category::fetch_course_tree($courseid, true);
    2030  
    2031          $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
    2032  
    2033          foreach ($this->elements as $key=>$unused) {
    2034              $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
    2035          }
    2036      }
    2037  
    2038      /**
    2039       * Static recursive helper - makes the grade_item for category the last children
    2040       *
    2041       * @param array &$element The seed of the recursion
    2042       * @param bool $category_grade_last category grade item is the last child
    2043       * @param bool $nooutcomes Whether or not outcomes should be included
    2044       *
    2045       * @return array
    2046       */
    2047      public function flatten(&$element, $category_grade_last, $nooutcomes) {
    2048          if (empty($element['children'])) {
    2049              return array();
    2050          }
    2051          $children = array();
    2052  
    2053          foreach ($element['children'] as $sortorder=>$unused) {
    2054              if ($nooutcomes and $element['type'] != 'category' and
    2055                  $element['children'][$sortorder]['object']->is_outcome_item()) {
    2056                  continue;
    2057              }
    2058              $children[] = $element['children'][$sortorder];
    2059          }
    2060          unset($element['children']);
    2061  
    2062          if ($category_grade_last and count($children) > 1) {
    2063              $cat_item = array_shift($children);
    2064              array_push($children, $cat_item);
    2065          }
    2066  
    2067          $result = array();
    2068          foreach ($children as $child) {
    2069              if ($child['type'] == 'category') {
    2070                  $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
    2071              } else {
    2072                  $child['eid'] = 'i'.$child['object']->id;
    2073                  $result[$child['object']->id] = $child;
    2074              }
    2075          }
    2076  
    2077          return $result;
    2078      }
    2079  
    2080      /**
    2081       * Parses the array in search of a given eid and returns a element object with
    2082       * information about the element it has found.
    2083       *
    2084       * @param int $eid Gradetree Element ID
    2085       *
    2086       * @return object element
    2087       */
    2088      public function locate_element($eid) {
    2089          // it is a grade - construct a new object
    2090          if (strpos($eid, 'n') === 0) {
    2091              if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
    2092                  return null;
    2093              }
    2094  
    2095              $itemid = $matches[1];
    2096              $userid = $matches[2];
    2097  
    2098              //extra security check - the grade item must be in this tree
    2099              if (!$item_el = $this->locate_element('ig'.$itemid)) {
    2100                  return null;
    2101              }
    2102  
    2103              // $gradea->id may be null - means does not exist yet
    2104              $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
    2105  
    2106              $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
    2107              return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
    2108  
    2109          } else if (strpos($eid, 'g') === 0) {
    2110              $id = (int) substr($eid, 1);
    2111              if (!$grade = grade_grade::fetch(array('id'=>$id))) {
    2112                  return null;
    2113              }
    2114              //extra security check - the grade item must be in this tree
    2115              if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
    2116                  return null;
    2117              }
    2118              $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
    2119              return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
    2120          }
    2121  
    2122          // it is a category or item
    2123          foreach ($this->elements as $element) {
    2124              if ($element['eid'] == $eid) {
    2125                  return $element;
    2126              }
    2127          }
    2128  
    2129          return null;
    2130      }
    2131  }
    2132  
    2133  /**
    2134   * This class represents a complete tree of categories, grade_items and final grades,
    2135   * organises as an array primarily, but which can also be converted to other formats.
    2136   * It has simple method calls with complex implementations, allowing for easy insertion,
    2137   * deletion and moving of items and categories within the tree.
    2138   *
    2139   * @uses grade_structure
    2140   * @package core_grades
    2141   * @copyright 2009 Nicolas Connault
    2142   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2143   */
    2144  class grade_tree extends grade_structure {
    2145  
    2146      /**
    2147       * The basic representation of the tree as a hierarchical, 3-tiered array.
    2148       * @var object $top_element
    2149       */
    2150      public $top_element;
    2151  
    2152      /**
    2153       * 2D array of grade items and categories
    2154       * @var array $levels
    2155       */
    2156      public $levels;
    2157  
    2158      /**
    2159       * Grade items
    2160       * @var array $items
    2161       */
    2162      public $items;
    2163  
    2164      /**
    2165       * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
    2166       * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
    2167       *
    2168       * @param int   $courseid The Course ID
    2169       * @param bool  $fillers include fillers and colspans, make the levels var "rectangular"
    2170       * @param bool  $category_grade_last category grade item is the last child
    2171       * @param array $collapsed array of collapsed categories
    2172       * @param bool  $nooutcomes Whether or not outcomes should be included
    2173       */
    2174      public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
    2175                                 $collapsed=null, $nooutcomes=false) {
    2176          global $USER, $CFG, $COURSE, $DB;
    2177  
    2178          $this->courseid   = $courseid;
    2179          $this->levels     = array();
    2180          $this->context    = context_course::instance($courseid);
    2181  
    2182          if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
    2183              $course = $COURSE;
    2184          } else {
    2185              $course = $DB->get_record('course', array('id' => $this->courseid));
    2186          }
    2187          $this->modinfo = get_fast_modinfo($course);
    2188  
    2189          // get course grade tree
    2190          $this->top_element = grade_category::fetch_course_tree($courseid, true);
    2191  
    2192          // collapse the categories if requested
    2193          if (!empty($collapsed)) {
    2194              grade_tree::category_collapse($this->top_element, $collapsed);
    2195          }
    2196  
    2197          // no otucomes if requested
    2198          if (!empty($nooutcomes)) {
    2199              grade_tree::no_outcomes($this->top_element);
    2200          }
    2201  
    2202          // move category item to last position in category
    2203          if ($category_grade_last) {
    2204              grade_tree::category_grade_last($this->top_element);
    2205          }
    2206  
    2207          if ($fillers) {
    2208              // inject fake categories == fillers
    2209              grade_tree::inject_fillers($this->top_element, 0);
    2210              // add colspans to categories and fillers
    2211              grade_tree::inject_colspans($this->top_element);
    2212          }
    2213  
    2214          grade_tree::fill_levels($this->levels, $this->top_element, 0);
    2215  
    2216      }
    2217  
    2218      /**
    2219       * Static recursive helper - removes items from collapsed categories
    2220       *
    2221       * @param array &$element The seed of the recursion
    2222       * @param array $collapsed array of collapsed categories
    2223       *
    2224       * @return void
    2225       */
    2226      public function category_collapse(&$element, $collapsed) {
    2227          if ($element['type'] != 'category') {
    2228              return;
    2229          }
    2230          if (empty($element['children']) or count($element['children']) < 2) {
    2231              return;
    2232          }
    2233  
    2234          if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
    2235              $category_item = reset($element['children']); //keep only category item
    2236              $element['children'] = array(key($element['children'])=>$category_item);
    2237  
    2238          } else {
    2239              if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
    2240                  reset($element['children']);
    2241                  $first_key = key($element['children']);
    2242                  unset($element['children'][$first_key]);
    2243              }
    2244              foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
    2245                  grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
    2246              }
    2247          }
    2248      }
    2249  
    2250      /**
    2251       * Static recursive helper - removes all outcomes
    2252       *
    2253       * @param array &$element The seed of the recursion
    2254       *
    2255       * @return void
    2256       */
    2257      public function no_outcomes(&$element) {
    2258          if ($element['type'] != 'category') {
    2259              return;
    2260          }
    2261          foreach ($element['children'] as $sortorder=>$child) {
    2262              if ($element['children'][$sortorder]['type'] == 'item'
    2263                and $element['children'][$sortorder]['object']->is_outcome_item()) {
    2264                  unset($element['children'][$sortorder]);
    2265  
    2266              } else if ($element['children'][$sortorder]['type'] == 'category') {
    2267                  grade_tree::no_outcomes($element['children'][$sortorder]);
    2268              }
    2269          }
    2270      }
    2271  
    2272      /**
    2273       * Static recursive helper - makes the grade_item for category the last children
    2274       *
    2275       * @param array &$element The seed of the recursion
    2276       *
    2277       * @return void
    2278       */
    2279      public function category_grade_last(&$element) {
    2280          if (empty($element['children'])) {
    2281              return;
    2282          }
    2283          if (count($element['children']) < 2) {
    2284              return;
    2285          }
    2286          $first_item = reset($element['children']);
    2287          if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
    2288              // the category item might have been already removed
    2289              $order = key($element['children']);
    2290              unset($element['children'][$order]);
    2291              $element['children'][$order] =& $first_item;
    2292          }
    2293          foreach ($element['children'] as $sortorder => $child) {
    2294              grade_tree::category_grade_last($element['children'][$sortorder]);
    2295          }
    2296      }
    2297  
    2298      /**
    2299       * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
    2300       *
    2301       * @param array &$levels The levels of the grade tree through which to recurse
    2302       * @param array &$element The seed of the recursion
    2303       * @param int   $depth How deep are we?
    2304       * @return void
    2305       */
    2306      public function fill_levels(&$levels, &$element, $depth) {
    2307          if (!array_key_exists($depth, $levels)) {
    2308              $levels[$depth] = array();
    2309          }
    2310  
    2311          // prepare unique identifier
    2312          if ($element['type'] == 'category') {
    2313              $element['eid'] = 'cg'.$element['object']->id;
    2314          } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
    2315              $element['eid'] = 'ig'.$element['object']->id;
    2316              $this->items[$element['object']->id] =& $element['object'];
    2317          }
    2318  
    2319          $levels[$depth][] =& $element;
    2320          $depth++;
    2321          if (empty($element['children'])) {
    2322              return;
    2323          }
    2324          $prev = 0;
    2325          foreach ($element['children'] as $sortorder=>$child) {
    2326              grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
    2327              $element['children'][$sortorder]['prev'] = $prev;
    2328              $element['children'][$sortorder]['next'] = 0;
    2329              if ($prev) {
    2330                  $element['children'][$prev]['next'] = $sortorder;
    2331              }
    2332              $prev = $sortorder;
    2333          }
    2334      }
    2335  
    2336      /**
    2337       * Static recursive helper - makes full tree (all leafes are at the same level)
    2338       *
    2339       * @param array &$element The seed of the recursion
    2340       * @param int   $depth How deep are we?
    2341       *
    2342       * @return int
    2343       */
    2344      public function inject_fillers(&$element, $depth) {
    2345          $depth++;
    2346  
    2347          if (empty($element['children'])) {
    2348              return $depth;
    2349          }
    2350          $chdepths = array();
    2351          $chids = array_keys($element['children']);
    2352          $last_child  = end($chids);
    2353          $first_child = reset($chids);
    2354  
    2355          foreach ($chids as $chid) {
    2356              $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
    2357          }
    2358          arsort($chdepths);
    2359  
    2360          $maxdepth = reset($chdepths);
    2361          foreach ($chdepths as $chid=>$chd) {
    2362              if ($chd == $maxdepth) {
    2363                  continue;
    2364              }
    2365              for ($i=0; $i < $maxdepth-$chd; $i++) {
    2366                  if ($chid == $first_child) {
    2367                      $type = 'fillerfirst';
    2368                  } else if ($chid == $last_child) {
    2369                      $type = 'fillerlast';
    2370                  } else {
    2371                      $type = 'filler';
    2372                  }
    2373                  $oldchild =& $element['children'][$chid];
    2374                  $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
    2375                                                      'eid'=>'', 'depth'=>$element['object']->depth,
    2376                                                      'children'=>array($oldchild));
    2377              }
    2378          }
    2379  
    2380          return $maxdepth;
    2381      }
    2382  
    2383      /**
    2384       * Static recursive helper - add colspan information into categories
    2385       *
    2386       * @param array &$element The seed of the recursion
    2387       *
    2388       * @return int
    2389       */
    2390      public function inject_colspans(&$element) {
    2391          if (empty($element['children'])) {
    2392              return 1;
    2393          }
    2394          $count = 0;
    2395          foreach ($element['children'] as $key=>$child) {
    2396              $count += grade_tree::inject_colspans($element['children'][$key]);
    2397          }
    2398          $element['colspan'] = $count;
    2399          return $count;
    2400      }
    2401  
    2402      /**
    2403       * Parses the array in search of a given eid and returns a element object with
    2404       * information about the element it has found.
    2405       * @param int $eid Gradetree Element ID
    2406       * @return object element
    2407       */
    2408      public function locate_element($eid) {
    2409          // it is a grade - construct a new object
    2410          if (strpos($eid, 'n') === 0) {
    2411              if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
    2412                  return null;
    2413              }
    2414  
    2415              $itemid = $matches[1];
    2416              $userid = $matches[2];
    2417  
    2418              //extra security check - the grade item must be in this tree
    2419              if (!$item_el = $this->locate_element('ig'.$itemid)) {
    2420                  return null;
    2421              }
    2422  
    2423              // $gradea->id may be null - means does not exist yet
    2424              $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
    2425  
    2426              $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
    2427              return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
    2428  
    2429          } else if (strpos($eid, 'g') === 0) {
    2430              $id = (int) substr($eid, 1);
    2431              if (!$grade = grade_grade::fetch(array('id'=>$id))) {
    2432                  return null;
    2433              }
    2434              //extra security check - the grade item must be in this tree
    2435              if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
    2436                  return null;
    2437              }
    2438              $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
    2439              return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
    2440          }
    2441  
    2442          // it is a category or item
    2443          foreach ($this->levels as $row) {
    2444              foreach ($row as $element) {
    2445                  if ($element['type'] == 'filler') {
    2446                      continue;
    2447                  }
    2448                  if ($element['eid'] == $eid) {
    2449                      return $element;
    2450                  }
    2451              }
    2452          }
    2453  
    2454          return null;
    2455      }
    2456  
    2457      /**
    2458       * Returns a well-formed XML representation of the grade-tree using recursion.
    2459       *
    2460       * @param array  $root The current element in the recursion. If null, starts at the top of the tree.
    2461       * @param string $tabs The control character to use for tabs
    2462       *
    2463       * @return string $xml
    2464       */
    2465      public function exporttoxml($root=null, $tabs="\t") {
    2466          $xml = null;
    2467          $first = false;
    2468          if (is_null($root)) {
    2469              $root = $this->top_element;
    2470              $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
    2471              $xml .= "<gradetree>\n";
    2472              $first = true;
    2473          }
    2474  
    2475          $type = 'undefined';
    2476          if (strpos($root['object']->table, 'grade_categories') !== false) {
    2477              $type = 'category';
    2478          } else if (strpos($root['object']->table, 'grade_items') !== false) {
    2479              $type = 'item';
    2480          } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
    2481              $type = 'outcome';
    2482          }
    2483  
    2484          $xml .= "$tabs<element type=\"$type\">\n";
    2485          foreach ($root['object'] as $var => $value) {
    2486              if (!is_object($value) && !is_array($value) && !empty($value)) {
    2487                  $xml .= "$tabs\t<$var>$value</$var>\n";
    2488              }
    2489          }
    2490  
    2491          if (!empty($root['children'])) {
    2492              $xml .= "$tabs\t<children>\n";
    2493              foreach ($root['children'] as $sortorder => $child) {
    2494                  $xml .= $this->exportToXML($child, $tabs."\t\t");
    2495              }
    2496              $xml .= "$tabs\t</children>\n";
    2497          }
    2498  
    2499          $xml .= "$tabs</element>\n";
    2500  
    2501          if ($first) {
    2502              $xml .= "</gradetree>";
    2503          }
    2504  
    2505          return $xml;
    2506      }
    2507  
    2508      /**
    2509       * Returns a JSON representation of the grade-tree using recursion.
    2510       *
    2511       * @param array $root The current element in the recursion. If null, starts at the top of the tree.
    2512       * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
    2513       *
    2514       * @return string
    2515       */
    2516      public function exporttojson($root=null, $tabs="\t") {
    2517          $json = null;
    2518          $first = false;
    2519          if (is_null($root)) {
    2520              $root = $this->top_element;
    2521              $first = true;
    2522          }
    2523  
    2524          $name = '';
    2525  
    2526  
    2527          if (strpos($root['object']->table, 'grade_categories') !== false) {
    2528              $name = $root['object']->fullname;
    2529              if ($name == '?') {
    2530                  $name = $root['object']->get_name();
    2531              }
    2532          } else if (strpos($root['object']->table, 'grade_items') !== false) {
    2533              $name = $root['object']->itemname;
    2534          } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
    2535              $name = $root['object']->itemname;
    2536          }
    2537  
    2538          $json .= "$tabs {\n";
    2539          $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
    2540          $json .= "$tabs\t \"name\": \"$name\",\n";
    2541  
    2542          foreach ($root['object'] as $var => $value) {
    2543              if (!is_object($value) && !is_array($value) && !empty($value)) {
    2544                  $json .= "$tabs\t \"$var\": \"$value\",\n";
    2545              }
    2546          }
    2547  
    2548          $json = substr($json, 0, strrpos($json, ','));
    2549  
    2550          if (!empty($root['children'])) {
    2551              $json .= ",\n$tabs\t\"children\": [\n";
    2552              foreach ($root['children'] as $sortorder => $child) {
    2553                  $json .= $this->exportToJSON($child, $tabs."\t\t");
    2554              }
    2555              $json = substr($json, 0, strrpos($json, ','));
    2556              $json .= "\n$tabs\t]\n";
    2557          }
    2558  
    2559          if ($first) {
    2560              $json .= "\n}";
    2561          } else {
    2562              $json .= "\n$tabs},\n";
    2563          }
    2564  
    2565          return $json;
    2566      }
    2567  
    2568      /**
    2569       * Returns the array of levels
    2570       *
    2571       * @return array
    2572       */
    2573      public function get_levels() {
    2574          return $this->levels;
    2575      }
    2576  
    2577      /**
    2578       * Returns the array of grade items
    2579       *
    2580       * @return array
    2581       */
    2582      public function get_items() {
    2583          return $this->items;
    2584      }
    2585  
    2586      /**
    2587       * Returns a specific Grade Item
    2588       *
    2589       * @param int $itemid The ID of the grade_item object
    2590       *
    2591       * @return grade_item
    2592       */
    2593      public function get_item($itemid) {
    2594          if (array_key_exists($itemid, $this->items)) {
    2595              return $this->items[$itemid];
    2596          } else {
    2597              return false;
    2598          }
    2599      }
    2600  }
    2601  
    2602  /**
    2603   * Local shortcut function for creating an edit/delete button for a grade_* object.
    2604   * @param string $type 'edit' or 'delete'
    2605   * @param int $courseid The Course ID
    2606   * @param grade_* $object The grade_* object
    2607   * @return string html
    2608   */
    2609  function grade_button($type, $courseid, $object) {
    2610      global $CFG, $OUTPUT;
    2611      if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
    2612          $objectidstring = $matches[1] . 'id';
    2613      } else {
    2614          throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
    2615      }
    2616  
    2617      $strdelete = get_string('delete');
    2618      $stredit   = get_string('edit');
    2619  
    2620      if ($type == 'delete') {
    2621          $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
    2622      } else if ($type == 'edit') {
    2623          $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
    2624      }
    2625  
    2626      return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
    2627  
    2628  }
    2629  
    2630  /**
    2631   * This method adds settings to the settings block for the grade system and its
    2632   * plugins
    2633   *
    2634   * @global moodle_page $PAGE
    2635   */
    2636  function grade_extend_settings($plugininfo, $courseid) {
    2637      global $PAGE;
    2638  
    2639      $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
    2640  
    2641      $strings = array_shift($plugininfo);
    2642  
    2643      if ($reports = grade_helper::get_plugins_reports($courseid)) {
    2644          foreach ($reports as $report) {
    2645              $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
    2646          }
    2647      }
    2648  
    2649      if ($settings = grade_helper::get_info_manage_settings($courseid)) {
    2650          $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
    2651          foreach ($settings as $setting) {
    2652              $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
    2653          }
    2654      }
    2655  
    2656      if ($imports = grade_helper::get_plugins_import($courseid)) {
    2657          $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
    2658          foreach ($imports as $import) {
    2659              $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
    2660          }
    2661      }
    2662  
    2663      if ($exports = grade_helper::get_plugins_export($courseid)) {
    2664          $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
    2665          foreach ($exports as $export) {
    2666              $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
    2667          }
    2668      }
    2669  
    2670      if ($letters = grade_helper::get_info_letters($courseid)) {
    2671          $letters = array_shift($letters);
    2672          $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
    2673      }
    2674  
    2675      if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
    2676          $outcomes = array_shift($outcomes);
    2677          $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
    2678      }
    2679  
    2680      if ($scales = grade_helper::get_info_scales($courseid)) {
    2681          $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
    2682      }
    2683  
    2684      if ($gradenode->contains_active_node()) {
    2685          // If the gradenode is active include the settings base node (gradeadministration) in
    2686          // the navbar, typcially this is ignored.
    2687          $PAGE->navbar->includesettingsbase = true;
    2688  
    2689          // If we can get the course admin node make sure it is closed by default
    2690          // as in this case the gradenode will be opened
    2691          if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
    2692              $coursenode->make_inactive();
    2693              $coursenode->forceopen = false;
    2694          }
    2695      }
    2696  }
    2697  
    2698  /**
    2699   * Grade helper class
    2700   *
    2701   * This class provides several helpful functions that work irrespective of any
    2702   * current state.
    2703   *
    2704   * @copyright 2010 Sam Hemelryk
    2705   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    2706   */
    2707  abstract class grade_helper {
    2708      /**
    2709       * Cached manage settings info {@see get_info_settings}
    2710       * @var grade_plugin_info|false
    2711       */
    2712      protected static $managesetting = null;
    2713      /**
    2714       * Cached grade report plugins {@see get_plugins_reports}
    2715       * @var array|false
    2716       */
    2717      protected static $gradereports = null;
    2718      /**
    2719       * Cached grade report plugins preferences {@see get_info_scales}
    2720       * @var array|false
    2721       */
    2722      protected static $gradereportpreferences = null;
    2723      /**
    2724       * Cached scale info {@see get_info_scales}
    2725       * @var grade_plugin_info|false
    2726       */
    2727      protected static $scaleinfo = null;
    2728      /**
    2729       * Cached outcome info {@see get_info_outcomes}
    2730       * @var grade_plugin_info|false
    2731       */
    2732      protected static $outcomeinfo = null;
    2733      /**
    2734       * Cached leftter info {@see get_info_letters}
    2735       * @var grade_plugin_info|false
    2736       */
    2737      protected static $letterinfo = null;
    2738      /**
    2739       * Cached grade import plugins {@see get_plugins_import}
    2740       * @var array|false
    2741       */
    2742      protected static $importplugins = null;
    2743      /**
    2744       * Cached grade export plugins {@see get_plugins_export}
    2745       * @var array|false
    2746       */
    2747      protected static $exportplugins = null;
    2748      /**
    2749       * Cached grade plugin strings
    2750       * @var array
    2751       */
    2752      protected static $pluginstrings = null;
    2753      /**
    2754       * Cached grade aggregation strings
    2755       * @var array
    2756       */
    2757      protected static $aggregationstrings = null;
    2758  
    2759      /**
    2760       * Gets strings commonly used by the describe plugins
    2761       *
    2762       * report => get_string('view'),
    2763       * scale => get_string('scales'),
    2764       * outcome => get_string('outcomes', 'grades'),
    2765       * letter => get_string('letters', 'grades'),
    2766       * export => get_string('export', 'grades'),
    2767       * import => get_string('import'),
    2768       * preferences => get_string('mypreferences', 'grades'),
    2769       * settings => get_string('settings')
    2770       *
    2771       * @return array
    2772       */
    2773      public static function get_plugin_strings() {
    2774          if (self::$pluginstrings === null) {
    2775              self::$pluginstrings = array(
    2776                  'report' => get_string('view'),
    2777                  'scale' => get_string('scales'),
    2778                  'outcome' => get_string('outcomes', 'grades'),
    2779                  'letter' => get_string('letters', 'grades'),
    2780                  'export' => get_string('export', 'grades'),
    2781                  'import' => get_string('import'),
    2782                  'settings' => get_string('edittree', 'grades')
    2783              );
    2784          }
    2785          return self::$pluginstrings;
    2786      }
    2787  
    2788      /**
    2789       * Gets strings describing the available aggregation methods.
    2790       *
    2791       * @return array
    2792       */
    2793      public static function get_aggregation_strings() {
    2794          if (self::$aggregationstrings === null) {
    2795              self::$aggregationstrings = array(
    2796                  GRADE_AGGREGATE_MEAN             => get_string('aggregatemean', 'grades'),
    2797                  GRADE_AGGREGATE_WEIGHTED_MEAN    => get_string('aggregateweightedmean', 'grades'),
    2798                  GRADE_AGGREGATE_WEIGHTED_MEAN2   => get_string('aggregateweightedmean2', 'grades'),
    2799                  GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
    2800                  GRADE_AGGREGATE_MEDIAN           => get_string('aggregatemedian', 'grades'),
    2801                  GRADE_AGGREGATE_MIN              => get_string('aggregatemin', 'grades'),
    2802                  GRADE_AGGREGATE_MAX              => get_string('aggregatemax', 'grades'),
    2803                  GRADE_AGGREGATE_MODE             => get_string('aggregatemode', 'grades'),
    2804                  GRADE_AGGREGATE_SUM              => get_string('aggregatesum', 'grades')
    2805              );
    2806          }
    2807          return self::$aggregationstrings;
    2808      }
    2809  
    2810      /**
    2811       * Get grade_plugin_info object for managing settings if the user can
    2812       *
    2813       * @param int $courseid
    2814       * @return grade_plugin_info[]
    2815       */
    2816      public static function get_info_manage_settings($courseid) {
    2817          if (self::$managesetting !== null) {
    2818              return self::$managesetting;
    2819          }
    2820          $context = context_course::instance($courseid);
    2821          self::$managesetting = array();
    2822          if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
    2823              self::$managesetting['categoriesanditems'] = new grade_plugin_info('setup',
    2824                  new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
    2825                  get_string('categoriesanditems', 'grades'));
    2826              self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
    2827                  new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
    2828                  get_string('coursegradesettings', 'grades'));
    2829          }
    2830          if (self::$gradereportpreferences === null) {
    2831              self::get_plugins_reports($courseid);
    2832          }
    2833          if (self::$gradereportpreferences) {
    2834              self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
    2835          }
    2836          return self::$managesetting;
    2837      }
    2838      /**
    2839       * Returns an array of plugin reports as grade_plugin_info objects
    2840       *
    2841       * @param int $courseid
    2842       * @return array
    2843       */
    2844      public static function get_plugins_reports($courseid) {
    2845          global $SITE;
    2846  
    2847          if (self::$gradereports !== null) {
    2848              return self::$gradereports;
    2849          }
    2850          $context = context_course::instance($courseid);
    2851          $gradereports = array();
    2852          $gradepreferences = array();
    2853          foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
    2854              //some reports make no sense if we're not within a course
    2855              if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
    2856                  continue;
    2857              }
    2858  
    2859              // Remove ones we can't see
    2860              if (!has_capability('gradereport/'.$plugin.':view', $context)) {
    2861                  continue;
    2862              }
    2863  
    2864              // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
    2865              if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
    2866                      'moodle/grade:edit'), $context)) {
    2867                  continue;
    2868              }
    2869  
    2870              $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
    2871              $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
    2872              $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
    2873  
    2874              // Add link to preferences tab if such a page exists
    2875              if (file_exists($plugindir.'/preferences.php')) {
    2876                  $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
    2877                  $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
    2878                      get_string('mypreferences', 'grades') . ': ' . $pluginstr);
    2879              }
    2880          }
    2881          if (count($gradereports) == 0) {
    2882              $gradereports = false;
    2883              $gradepreferences = false;
    2884          } else if (count($gradepreferences) == 0) {
    2885              $gradepreferences = false;
    2886              asort($gradereports);
    2887          } else {
    2888              asort($gradereports);
    2889              asort($gradepreferences);
    2890          }
    2891          self::$gradereports = $gradereports;
    2892          self::$gradereportpreferences = $gradepreferences;
    2893          return self::$gradereports;
    2894      }
    2895  
    2896      /**
    2897       * Get information on scales
    2898       * @param int $courseid
    2899       * @return grade_plugin_info
    2900       */
    2901      public static function get_info_scales($courseid) {
    2902          if (self::$scaleinfo !== null) {
    2903              return self::$scaleinfo;
    2904          }
    2905          if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
    2906              $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
    2907              self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
    2908          } else {
    2909              self::$scaleinfo = false;
    2910          }
    2911          return self::$scaleinfo;
    2912      }
    2913      /**
    2914       * Get information on outcomes
    2915       * @param int $courseid
    2916       * @return grade_plugin_info
    2917       */
    2918      public static function get_info_outcomes($courseid) {
    2919          global $CFG, $SITE;
    2920  
    2921          if (self::$outcomeinfo !== null) {
    2922              return self::$outcomeinfo;
    2923          }
    2924          $context = context_course::instance($courseid);
    2925          $canmanage = has_capability('moodle/grade:manage', $context);
    2926          $canupdate = has_capability('moodle/course:update', $context);
    2927          if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
    2928              $outcomes = array();
    2929              if ($canupdate) {
    2930                  if ($courseid!=$SITE->id) {
    2931                      $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
    2932                      $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
    2933                  }
    2934                  $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
    2935                  $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
    2936                  $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
    2937                  $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
    2938              } else {
    2939                  if ($courseid!=$SITE->id) {
    2940                      $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
    2941                      $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
    2942                  }
    2943              }
    2944              self::$outcomeinfo = $outcomes;
    2945          } else {
    2946              self::$outcomeinfo = false;
    2947          }
    2948          return self::$outcomeinfo;
    2949      }
    2950      /**
    2951       * Get information on letters
    2952       * @param int $courseid
    2953       * @return array
    2954       */
    2955      public static function get_info_letters($courseid) {
    2956          global $SITE;
    2957          if (self::$letterinfo !== null) {
    2958              return self::$letterinfo;
    2959          }
    2960          $context = context_course::instance($courseid);
    2961          $canmanage = has_capability('moodle/grade:manage', $context);
    2962          $canmanageletters = has_capability('moodle/grade:manageletters', $context);
    2963          if ($canmanage || $canmanageletters) {
    2964              // Redirect to system context when report is accessed from admin settings MDL-31633
    2965              if ($context->instanceid == $SITE->id) {
    2966                  $param = array('edit' => 1);
    2967              } else {
    2968                  $param = array('edit' => 1,'id' => $context->id);
    2969              }
    2970              self::$letterinfo = array(
    2971                  'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
    2972                  'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
    2973              );
    2974          } else {
    2975              self::$letterinfo = false;
    2976          }
    2977          return self::$letterinfo;
    2978      }
    2979      /**
    2980       * Get information import plugins
    2981       * @param int $courseid
    2982       * @return array
    2983       */
    2984      public static function get_plugins_import($courseid) {
    2985          global $CFG;
    2986  
    2987          if (self::$importplugins !== null) {
    2988              return self::$importplugins;
    2989          }
    2990          $importplugins = array();
    2991          $context = context_course::instance($courseid);
    2992  
    2993          if (has_capability('moodle/grade:import', $context)) {
    2994              foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
    2995                  if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
    2996                      continue;
    2997                  }
    2998                  $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
    2999                  $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
    3000                  $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
    3001              }
    3002  
    3003  
    3004              if ($CFG->gradepublishing) {
    3005                  $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
    3006                  $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
    3007              }
    3008          }
    3009  
    3010          if (count($importplugins) > 0) {
    3011              asort($importplugins);
    3012              self::$importplugins = $importplugins;
    3013          } else {
    3014              self::$importplugins = false;
    3015          }
    3016          return self::$importplugins;
    3017      }
    3018      /**
    3019       * Get information export plugins
    3020       * @param int $courseid
    3021       * @return array
    3022       */
    3023      public static function get_plugins_export($courseid) {
    3024          global $CFG;
    3025  
    3026          if (self::$exportplugins !== null) {
    3027              return self::$exportplugins;
    3028          }
    3029          $context = context_course::instance($courseid);
    3030          $exportplugins = array();
    3031          if (has_capability('moodle/grade:export', $context)) {
    3032              foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
    3033                  if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
    3034                      continue;
    3035                  }
    3036                  $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
    3037                  $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
    3038                  $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
    3039              }
    3040  
    3041              if ($CFG->gradepublishing) {
    3042                  $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
    3043                  $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
    3044              }
    3045          }
    3046          if (count($exportplugins) > 0) {
    3047              asort($exportplugins);
    3048              self::$exportplugins = $exportplugins;
    3049          } else {
    3050              self::$exportplugins = false;
    3051          }
    3052          return self::$exportplugins;
    3053      }
    3054  
    3055      /**
    3056       * Returns the value of a field from a user record
    3057       *
    3058       * @param stdClass $user object
    3059       * @param stdClass $field object
    3060       * @return string value of the field
    3061       */
    3062      public static function get_user_field_value($user, $field) {
    3063          if (!empty($field->customid)) {
    3064              $fieldname = 'customfield_' . $field->shortname;
    3065              if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
    3066                  $fieldvalue = $user->{$fieldname};
    3067              } else {
    3068                  $fieldvalue = $field->default;
    3069              }
    3070          } else {
    3071              $fieldvalue = $user->{$field->shortname};
    3072          }
    3073          return $fieldvalue;
    3074      }
    3075  
    3076      /**
    3077       * Returns an array of user profile fields to be included in export
    3078       *
    3079       * @param int $courseid
    3080       * @param bool $includecustomfields
    3081       * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
    3082       */
    3083      public static function get_user_profile_fields($courseid, $includecustomfields = false) {
    3084          global $CFG, $DB;
    3085  
    3086          // Gets the fields that have to be hidden
    3087          $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
    3088          $context = context_course::instance($courseid);
    3089          $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
    3090          if ($canseehiddenfields) {
    3091              $hiddenfields = array();
    3092          }
    3093  
    3094          $fields = array();
    3095          require_once($CFG->dirroot.'/user/lib.php');                // Loads user_get_default_fields()
    3096          require_once($CFG->dirroot.'/user/profile/lib.php');        // Loads constants, such as PROFILE_VISIBLE_ALL
    3097          $userdefaultfields = user_get_default_fields();
    3098  
    3099          // Sets the list of profile fields
    3100          $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
    3101          if (!empty($userprofilefields)) {
    3102              foreach ($userprofilefields as $field) {
    3103                  $field = trim($field);
    3104                  if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
    3105                      continue;
    3106                  }
    3107                  $obj = new stdClass();
    3108                  $obj->customid  = 0;
    3109                  $obj->shortname = $field;
    3110                  $obj->fullname  = get_string($field);
    3111                  $fields[] = $obj;
    3112              }
    3113          }
    3114  
    3115          // Sets the list of custom profile fields
    3116          $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
    3117          if ($includecustomfields && !empty($customprofilefields)) {
    3118              list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
    3119              $customfields = $DB->get_records_sql("SELECT f.*
    3120                                                      FROM {user_info_field} f
    3121                                                      JOIN {user_info_category} c ON f.categoryid=c.id
    3122                                                      WHERE f.shortname $wherefields
    3123                                                      ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
    3124  
    3125              foreach ($customfields as $field) {
    3126                  // Make sure we can display this custom field
    3127                  if (!in_array($field->shortname, $customprofilefields)) {
    3128                      continue;
    3129                  } else if (in_array($field->shortname, $hiddenfields)) {
    3130                      continue;
    3131                  } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
    3132                      continue;
    3133                  }
    3134  
    3135                  $obj = new stdClass();
    3136                  $obj->customid  = $field->id;
    3137                  $obj->shortname = $field->shortname;
    3138                  $obj->fullname  = format_string($field->name);
    3139                  $obj->datatype  = $field->datatype;
    3140                  $obj->default   = $field->defaultdata;
    3141                  $fields[] = $obj;
    3142              }
    3143          }
    3144  
    3145          return $fields;
    3146      }
    3147  
    3148      /**
    3149       * This helper method gets a snapshot of all the weights for a course.
    3150       * It is used as a quick method to see if any wieghts have been automatically adjusted.
    3151       * @param int $courseid
    3152       * @return array of itemid -> aggregationcoef2
    3153       */
    3154      public static function fetch_all_natural_weights_for_course($courseid) {
    3155          global $DB;
    3156          $result = array();
    3157  
    3158          $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
    3159          foreach ($records as $record) {
    3160              $result[$record->id] = $record->aggregationcoef2;
    3161          }
    3162          return $result;
    3163      }
    3164  }
    3165