PageRenderTime 91ms CodeModel.GetById 3ms app.highlight 55ms RepoModel.GetById 1ms app.codeStats 1ms

/grade/lib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 2840 lines | 1843 code | 325 blank | 672 comment | 389 complexity | 2fea5cda5172928f8fd6dee352a6d6aa MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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
  25require_once($CFG->libdir . '/gradelib.php');
  26require_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 */
  35class 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            }
 312        }
 313
 314        // Set user suspended status.
 315        $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
 316        $result = new stdClass();
 317        $result->user      = $user;
 318        $result->grades    = $grades;
 319        $result->feedbacks = $feedbacks;
 320        return $result;
 321    }
 322
 323    /**
 324     * Close the iterator, do not forget to call this function
 325     */
 326    public function close() {
 327        if ($this->users_rs) {
 328            $this->users_rs->close();
 329            $this->users_rs = null;
 330        }
 331        if ($this->grades_rs) {
 332            $this->grades_rs->close();
 333            $this->grades_rs = null;
 334        }
 335        $this->gradestack = array();
 336    }
 337
 338    /**
 339     * Should all enrolled users be exported or just those with an active enrolment?
 340     *
 341     * @param bool $onlyactive True to limit the export to users with an active enrolment
 342     */
 343    public function require_active_enrolment($onlyactive = true) {
 344        if (!empty($this->users_rs)) {
 345            debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
 346        }
 347        $this->onlyactive  = $onlyactive;
 348    }
 349
 350    /**
 351     * Allow custom fields to be included
 352     *
 353     * @param bool $allow Whether to allow custom fields or not
 354     * @return void
 355     */
 356    public function allow_user_custom_fields($allow = true) {
 357        if ($allow) {
 358            $this->allowusercustomfields = true;
 359        } else {
 360            $this->allowusercustomfields = false;
 361        }
 362    }
 363
 364    /**
 365     * Add a grade_grade instance to the grade stack
 366     *
 367     * @param grade_grade $grade Grade object
 368     *
 369     * @return void
 370     */
 371    private function _push($grade) {
 372        array_push($this->gradestack, $grade);
 373    }
 374
 375
 376    /**
 377     * Remove a grade_grade instance from the grade stack
 378     *
 379     * @return grade_grade current grade object
 380     */
 381    private function _pop() {
 382        global $DB;
 383        if (empty($this->gradestack)) {
 384            if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
 385                return null; // no grades present
 386            }
 387
 388            $current = $this->grades_rs->current();
 389
 390            $this->grades_rs->next();
 391
 392            return $current;
 393        } else {
 394            return array_pop($this->gradestack);
 395        }
 396    }
 397}
 398
 399/**
 400 * Print a selection popup form of the graded users in a course.
 401 *
 402 * @deprecated since 2.0
 403 *
 404 * @param int    $course id of the course
 405 * @param string $actionpage The page receiving the data from the popoup form
 406 * @param int    $userid   id of the currently selected user (or 'all' if they are all selected)
 407 * @param int    $groupid id of requested group, 0 means all
 408 * @param int    $includeall bool include all option
 409 * @param bool   $return If true, will return the HTML, otherwise, will print directly
 410 * @return null
 411 */
 412function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
 413    global $CFG, $USER, $OUTPUT;
 414    return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
 415}
 416
 417function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
 418    global $USER, $CFG;
 419
 420    if (is_null($userid)) {
 421        $userid = $USER->id;
 422    }
 423    $coursecontext = context_course::instance($course->id);
 424    $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
 425    $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
 426    $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
 427    $menu = array(); // Will be a list of userid => user name
 428    $menususpendedusers = array(); // Suspended users go to a separate optgroup.
 429    $gui = new graded_users_iterator($course, null, $groupid);
 430    $gui->require_active_enrolment($showonlyactiveenrol);
 431    $gui->init();
 432    $label = get_string('selectauser', 'grades');
 433    if ($includeall) {
 434        $menu[0] = get_string('allusers', 'grades');
 435        $label = get_string('selectalloroneuser', 'grades');
 436    }
 437    while ($userdata = $gui->next_user()) {
 438        $user = $userdata->user;
 439        $userfullname = fullname($user);
 440        if ($user->suspendedenrolment) {
 441            $menususpendedusers[$user->id] = $userfullname;
 442        } else {
 443            $menu[$user->id] = $userfullname;
 444        }
 445    }
 446    $gui->close();
 447
 448    if ($includeall) {
 449        $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
 450    }
 451
 452    if (!empty($menususpendedusers)) {
 453        $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
 454    }
 455    $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
 456    $select->label = $label;
 457    $select->formid = 'choosegradeuser';
 458    return $select;
 459}
 460
 461/**
 462 * Print grading plugin selection popup form.
 463 *
 464 * @param array   $plugin_info An array of plugins containing information for the selector
 465 * @param boolean $return return as string
 466 *
 467 * @return nothing or string if $return true
 468 */
 469function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
 470    global $CFG, $OUTPUT, $PAGE;
 471
 472    $menu = array();
 473    $count = 0;
 474    $active = '';
 475
 476    foreach ($plugin_info as $plugin_type => $plugins) {
 477        if ($plugin_type == 'strings') {
 478            continue;
 479        }
 480
 481        $first_plugin = reset($plugins);
 482
 483        $sectionname = $plugin_info['strings'][$plugin_type];
 484        $section = array();
 485
 486        foreach ($plugins as $plugin) {
 487            $link = $plugin->link->out(false);
 488            $section[$link] = $plugin->string;
 489            $count++;
 490            if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
 491                $active = $link;
 492            }
 493        }
 494
 495        if ($section) {
 496            $menu[] = array($sectionname=>$section);
 497        }
 498    }
 499
 500    // finally print/return the popup form
 501    if ($count > 1) {
 502        $select = new url_select($menu, $active, null, 'choosepluginreport');
 503        $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
 504        if ($return) {
 505            return $OUTPUT->render($select);
 506        } else {
 507            echo $OUTPUT->render($select);
 508        }
 509    } else {
 510        // only one option - no plugin selector needed
 511        return '';
 512    }
 513}
 514
 515/**
 516 * Print grading plugin selection tab-based navigation.
 517 *
 518 * @param string  $active_type type of plugin on current page - import, export, report or edit
 519 * @param string  $active_plugin active plugin type - grader, user, cvs, ...
 520 * @param array   $plugin_info Array of plugins
 521 * @param boolean $return return as string
 522 *
 523 * @return nothing or string if $return true
 524 */
 525function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
 526    global $CFG, $COURSE;
 527
 528    if (!isset($currenttab)) { //TODO: this is weird
 529        $currenttab = '';
 530    }
 531
 532    $tabs = array();
 533    $top_row  = array();
 534    $bottom_row = array();
 535    $inactive = array($active_plugin);
 536    $activated = array();
 537
 538    $count = 0;
 539    $active = '';
 540
 541    foreach ($plugin_info as $plugin_type => $plugins) {
 542        if ($plugin_type == 'strings') {
 543            continue;
 544        }
 545
 546        // If $plugins is actually the definition of a child-less parent link:
 547        if (!empty($plugins->id)) {
 548            $string = $plugins->string;
 549            if (!empty($plugin_info[$active_type]->parent)) {
 550                $string = $plugin_info[$active_type]->parent->string;
 551            }
 552
 553            $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
 554            continue;
 555        }
 556
 557        $first_plugin = reset($plugins);
 558        $url = $first_plugin->link;
 559
 560        if ($plugin_type == 'report') {
 561            $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
 562        }
 563
 564        $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
 565
 566        if ($active_type == $plugin_type) {
 567            foreach ($plugins as $plugin) {
 568                $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
 569                if ($plugin->id == $active_plugin) {
 570                    $inactive = array($plugin->id);
 571                }
 572            }
 573        }
 574    }
 575
 576    $tabs[] = $top_row;
 577    $tabs[] = $bottom_row;
 578
 579    if ($return) {
 580        return print_tabs($tabs, $active_type, $inactive, $activated, true);
 581    } else {
 582        print_tabs($tabs, $active_type, $inactive, $activated);
 583    }
 584}
 585
 586/**
 587 * grade_get_plugin_info
 588 *
 589 * @param int    $courseid The course id
 590 * @param string $active_type type of plugin on current page - import, export, report or edit
 591 * @param string $active_plugin active plugin type - grader, user, cvs, ...
 592 *
 593 * @return array
 594 */
 595function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
 596    global $CFG, $SITE;
 597
 598    $context = context_course::instance($courseid);
 599
 600    $plugin_info = array();
 601    $count = 0;
 602    $active = '';
 603    $url_prefix = $CFG->wwwroot . '/grade/';
 604
 605    // Language strings
 606    $plugin_info['strings'] = grade_helper::get_plugin_strings();
 607
 608    if ($reports = grade_helper::get_plugins_reports($courseid)) {
 609        $plugin_info['report'] = $reports;
 610    }
 611
 612    //showing grade categories and items make no sense if we're not within a course
 613    if ($courseid!=$SITE->id) {
 614        if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
 615            $plugin_info['edittree'] = $edittree;
 616        }
 617    }
 618
 619    if ($scale = grade_helper::get_info_scales($courseid)) {
 620        $plugin_info['scale'] = array('view'=>$scale);
 621    }
 622
 623    if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
 624        $plugin_info['outcome'] = $outcomes;
 625    }
 626
 627    if ($letters = grade_helper::get_info_letters($courseid)) {
 628        $plugin_info['letter'] = $letters;
 629    }
 630
 631    if ($imports = grade_helper::get_plugins_import($courseid)) {
 632        $plugin_info['import'] = $imports;
 633    }
 634
 635    if ($exports = grade_helper::get_plugins_export($courseid)) {
 636        $plugin_info['export'] = $exports;
 637    }
 638
 639    foreach ($plugin_info as $plugin_type => $plugins) {
 640        if (!empty($plugins->id) && $active_plugin == $plugins->id) {
 641            $plugin_info['strings']['active_plugin_str'] = $plugins->string;
 642            break;
 643        }
 644        foreach ($plugins as $plugin) {
 645            if (is_a($plugin, 'grade_plugin_info')) {
 646                if ($active_plugin == $plugin->id) {
 647                    $plugin_info['strings']['active_plugin_str'] = $plugin->string;
 648                }
 649            }
 650        }
 651    }
 652
 653    //hide course settings if we're not in a course
 654    if ($courseid!=$SITE->id) {
 655        if ($setting = grade_helper::get_info_manage_settings($courseid)) {
 656            $plugin_info['settings'] = array('course'=>$setting);
 657        }
 658    }
 659
 660    // Put preferences last
 661    if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
 662        $plugin_info['preferences'] = $preferences;
 663    }
 664
 665    foreach ($plugin_info as $plugin_type => $plugins) {
 666        if (!empty($plugins->id) && $active_plugin == $plugins->id) {
 667            $plugin_info['strings']['active_plugin_str'] = $plugins->string;
 668            break;
 669        }
 670        foreach ($plugins as $plugin) {
 671            if (is_a($plugin, 'grade_plugin_info')) {
 672                if ($active_plugin == $plugin->id) {
 673                    $plugin_info['strings']['active_plugin_str'] = $plugin->string;
 674                }
 675            }
 676        }
 677    }
 678
 679    return $plugin_info;
 680}
 681
 682/**
 683 * A simple class containing info about grade plugins.
 684 * Can be subclassed for special rules
 685 *
 686 * @package core_grades
 687 * @copyright 2009 Nicolas Connault
 688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 689 */
 690class grade_plugin_info {
 691    /**
 692     * A unique id for this plugin
 693     *
 694     * @var mixed
 695     */
 696    public $id;
 697    /**
 698     * A URL to access this plugin
 699     *
 700     * @var mixed
 701     */
 702    public $link;
 703    /**
 704     * The name of this plugin
 705     *
 706     * @var mixed
 707     */
 708    public $string;
 709    /**
 710     * Another grade_plugin_info object, parent of the current one
 711     *
 712     * @var mixed
 713     */
 714    public $parent;
 715
 716    /**
 717     * Constructor
 718     *
 719     * @param int $id A unique id for this plugin
 720     * @param string $link A URL to access this plugin
 721     * @param string $string The name of this plugin
 722     * @param object $parent Another grade_plugin_info object, parent of the current one
 723     *
 724     * @return void
 725     */
 726    public function __construct($id, $link, $string, $parent=null) {
 727        $this->id = $id;
 728        $this->link = $link;
 729        $this->string = $string;
 730        $this->parent = $parent;
 731    }
 732}
 733
 734/**
 735 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
 736 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
 737 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
 738 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
 739 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
 740 *
 741 * @param int     $courseid Course id
 742 * @param string  $active_type The type of the current page (report, settings,
 743 *                             import, export, scales, outcomes, letters)
 744 * @param string  $active_plugin The plugin of the current page (grader, fullview etc...)
 745 * @param string  $heading The heading of the page. Tries to guess if none is given
 746 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
 747 * @param string  $bodytags Additional attributes that will be added to the <body> tag
 748 * @param string  $buttons Additional buttons to display on the page
 749 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
 750 *
 751 * @return string HTML code or nothing if $return == false
 752 */
 753function print_grade_page_head($courseid, $active_type, $active_plugin=null,
 754                               $heading = false, $return=false,
 755                               $buttons=false, $shownavigation=true) {
 756    global $CFG, $OUTPUT, $PAGE;
 757
 758    $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
 759
 760    // Determine the string of the active plugin
 761    $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
 762    $stractive_type = $plugin_info['strings'][$active_type];
 763
 764    if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
 765        $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
 766    } else {
 767        $title = $PAGE->course->fullname.': ' . $stractive_plugin;
 768    }
 769
 770    if ($active_type == 'report') {
 771        $PAGE->set_pagelayout('report');
 772    } else {
 773        $PAGE->set_pagelayout('admin');
 774    }
 775    $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
 776    $PAGE->set_heading($title);
 777    if ($buttons instanceof single_button) {
 778        $buttons = $OUTPUT->render($buttons);
 779    }
 780    $PAGE->set_button($buttons);
 781    grade_extend_settings($plugin_info, $courseid);
 782
 783    $returnval = $OUTPUT->header();
 784    if (!$return) {
 785        echo $returnval;
 786    }
 787
 788    // Guess heading if not given explicitly
 789    if (!$heading) {
 790        $heading = $stractive_plugin;
 791    }
 792
 793    if ($shownavigation) {
 794        if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
 795            $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
 796        }
 797
 798        if ($return) {
 799            $returnval .= $OUTPUT->heading($heading);
 800        } else {
 801            echo $OUTPUT->heading($heading);
 802        }
 803
 804        if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
 805            $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
 806        }
 807    }
 808
 809    if ($return) {
 810        return $returnval;
 811    }
 812}
 813
 814/**
 815 * Utility class used for return tracking when using edit and other forms in grade plugins
 816 *
 817 * @package core_grades
 818 * @copyright 2009 Nicolas Connault
 819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 820 */
 821class grade_plugin_return {
 822    public $type;
 823    public $plugin;
 824    public $courseid;
 825    public $userid;
 826    public $page;
 827
 828    /**
 829     * Constructor
 830     *
 831     * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
 832     */
 833    public function grade_plugin_return($params = null) {
 834        if (empty($params)) {
 835            $this->type     = optional_param('gpr_type', null, PARAM_SAFEDIR);
 836            $this->plugin   = optional_param('gpr_plugin', null, PARAM_PLUGIN);
 837            $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
 838            $this->userid   = optional_param('gpr_userid', null, PARAM_INT);
 839            $this->page     = optional_param('gpr_page', null, PARAM_INT);
 840
 841        } else {
 842            foreach ($params as $key=>$value) {
 843                if (property_exists($this, $key)) {
 844                    $this->$key = $value;
 845                }
 846            }
 847        }
 848    }
 849
 850    /**
 851     * Returns return parameters as options array suitable for buttons.
 852     * @return array options
 853     */
 854    public function get_options() {
 855        if (empty($this->type)) {
 856            return array();
 857        }
 858
 859        $params = array();
 860
 861        if (!empty($this->plugin)) {
 862            $params['plugin'] = $this->plugin;
 863        }
 864
 865        if (!empty($this->courseid)) {
 866            $params['id'] = $this->courseid;
 867        }
 868
 869        if (!empty($this->userid)) {
 870            $params['userid'] = $this->userid;
 871        }
 872
 873        if (!empty($this->page)) {
 874            $params['page'] = $this->page;
 875        }
 876
 877        return $params;
 878    }
 879
 880    /**
 881     * Returns return url
 882     *
 883     * @param string $default default url when params not set
 884     * @param array  $extras Extra URL parameters
 885     *
 886     * @return string url
 887     */
 888    public function get_return_url($default, $extras=null) {
 889        global $CFG;
 890
 891        if (empty($this->type) or empty($this->plugin)) {
 892            return $default;
 893        }
 894
 895        $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
 896        $glue = '?';
 897
 898        if (!empty($this->courseid)) {
 899            $url .= $glue.'id='.$this->courseid;
 900            $glue = '&amp;';
 901        }
 902
 903        if (!empty($this->userid)) {
 904            $url .= $glue.'userid='.$this->userid;
 905            $glue = '&amp;';
 906        }
 907
 908        if (!empty($this->page)) {
 909            $url .= $glue.'page='.$this->page;
 910            $glue = '&amp;';
 911        }
 912
 913        if (!empty($extras)) {
 914            foreach ($extras as $key=>$value) {
 915                $url .= $glue.$key.'='.$value;
 916                $glue = '&amp;';
 917            }
 918        }
 919
 920        return $url;
 921    }
 922
 923    /**
 924     * Returns string with hidden return tracking form elements.
 925     * @return string
 926     */
 927    public function get_form_fields() {
 928        if (empty($this->type)) {
 929            return '';
 930        }
 931
 932        $result  = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
 933
 934        if (!empty($this->plugin)) {
 935            $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
 936        }
 937
 938        if (!empty($this->courseid)) {
 939            $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
 940        }
 941
 942        if (!empty($this->userid)) {
 943            $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
 944        }
 945
 946        if (!empty($this->page)) {
 947            $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
 948        }
 949    }
 950
 951    /**
 952     * Add hidden elements into mform
 953     *
 954     * @param object &$mform moodle form object
 955     *
 956     * @return void
 957     */
 958    public function add_mform_elements(&$mform) {
 959        if (empty($this->type)) {
 960            return;
 961        }
 962
 963        $mform->addElement('hidden', 'gpr_type', $this->type);
 964        $mform->setType('gpr_type', PARAM_SAFEDIR);
 965
 966        if (!empty($this->plugin)) {
 967            $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
 968            $mform->setType('gpr_plugin', PARAM_PLUGIN);
 969        }
 970
 971        if (!empty($this->courseid)) {
 972            $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
 973            $mform->setType('gpr_courseid', PARAM_INT);
 974        }
 975
 976        if (!empty($this->userid)) {
 977            $mform->addElement('hidden', 'gpr_userid', $this->userid);
 978            $mform->setType('gpr_userid', PARAM_INT);
 979        }
 980
 981        if (!empty($this->page)) {
 982            $mform->addElement('hidden', 'gpr_page', $this->page);
 983            $mform->setType('gpr_page', PARAM_INT);
 984        }
 985    }
 986
 987    /**
 988     * Add return tracking params into url
 989     *
 990     * @param moodle_url $url A URL
 991     *
 992     * @return string $url with return tracking params
 993     */
 994    public function add_url_params(moodle_url $url) {
 995        if (empty($this->type)) {
 996            return $url;
 997        }
 998
 999        $url->param('gpr_type', $this->type);
1000
1001        if (!empty($this->plugin)) {
1002            $url->param('gpr_plugin', $this->plugin);
1003        }
1004
1005        if (!empty($this->courseid)) {
1006            $url->param('gpr_courseid' ,$this->courseid);
1007        }
1008
1009        if (!empty($this->userid)) {
1010            $url->param('gpr_userid', $this->userid);
1011        }
1012
1013        if (!empty($this->page)) {
1014            $url->param('gpr_page', $this->page);
1015        }
1016
1017        return $url;
1018    }
1019}
1020
1021/**
1022 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1023 *
1024 * @param string $path The path of the calling script (using __FILE__?)
1025 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1026 * @param mixed  $id Either a plain integer (assuming the key is 'id') or
1027 *                   an array of keys and values (e.g courseid => $courseid, itemid...)
1028 *
1029 * @return string
1030 */
1031function grade_build_nav($path, $pagename=null, $id=null) {
1032    global $CFG, $COURSE, $PAGE;
1033
1034    $strgrades = get_string('grades', 'grades');
1035
1036    // Parse the path and build navlinks from its elements
1037    $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1038    $path = substr($path, $dirroot_length);
1039    $path = str_replace('\\', '/', $path);
1040
1041    $path_elements = explode('/', $path);
1042
1043    $path_elements_count = count($path_elements);
1044
1045    // First link is always 'grade'
1046    $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1047
1048    $link = null;
1049    $numberofelements = 3;
1050
1051    // Prepare URL params string
1052    $linkparams = array();
1053    if (!is_null($id)) {
1054        if (is_array($id)) {
1055            foreach ($id as $idkey => $idvalue) {
1056                $linkparams[$idkey] = $idvalue;
1057            }
1058        } else {
1059            $linkparams['id'] = $id;
1060        }
1061    }
1062
1063    $navlink4 = null;
1064
1065    // Remove file extensions from filenames
1066    foreach ($path_elements as $key => $filename) {
1067        $path_elements[$key] = str_replace('.php', '', $filename);
1068    }
1069
1070    // Second level links
1071    switch ($path_elements[1]) {
1072        case 'edit': // No link
1073            if ($path_elements[3] != 'index.php') {
1074                $numberofelements = 4;
1075            }
1076            break;
1077        case 'import': // No link
1078            break;
1079        case 'export': // No link
1080            break;
1081        case 'report':
1082            // $id is required for this link. Do not print it if $id isn't given
1083            if (!is_null($id)) {
1084                $link = new moodle_url('/grade/report/index.php', $linkparams);
1085            }
1086
1087            if ($path_elements[2] == 'grader') {
1088                $numberofelements = 4;
1089            }
1090            break;
1091
1092        default:
1093            // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1094            debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1095                    " as the second path element after 'grade'.");
1096            return false;
1097    }
1098    $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1099
1100    // Third level links
1101    if (empty($pagename)) {
1102        $pagename = get_string($path_elements[2], 'grades');
1103    }
1104
1105    switch ($numberofelements) {
1106        case 3:
1107            $PAGE->navbar->add($pagename, $link);
1108            break;
1109        case 4:
1110            if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1111                $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1112            }
1113            $PAGE->navbar->add($pagename);
1114            break;
1115    }
1116
1117    return '';
1118}
1119
1120/**
1121 * General structure representing grade items in course
1122 *
1123 * @package core_grades
1124 * @copyright 2009 Nicolas Connault
1125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1126 */
1127class grade_structure {
1128    public $context;
1129
1130    public $courseid;
1131
1132    /**
1133    * Reference to modinfo for current course (for performance, to save
1134    * retrieving it from courseid every time). Not actually set except for
1135    * the grade_tree type.
1136    * @var course_modinfo
1137    */
1138    public $modinfo;
1139
1140    /**
1141     * 1D array of grade items only
1142     */
1143    public $items;
1144
1145    /**
1146     * Returns icon of element
1147     *
1148     * @param array &$element An array representing an element in the grade_tree
1149     * @param bool  $spacerifnone return spacer if no icon found
1150     *
1151     * @return string icon or spacer
1152     */
1153    public function get_element_icon(&$element, $spacerifnone=false) {
1154        global $CFG, $OUTPUT;
1155        require_once $CFG->libdir.'/filelib.php';
1156
1157        switch ($element['type']) {
1158            case 'item':
1159            case 'courseitem':
1160            case 'categoryitem':
1161                $is_course   = $element['object']->is_course_item();
1162                $is_category = $element['object']->is_category_item();
1163                $is_scale    = $element['object']->gradetype == GRADE_TYPE_SCALE;
1164                $is_value    = $element['object']->gradetype == GRADE_TYPE_VALUE;
1165                $is_outcome  = !empty($element['object']->outcomeid);
1166
1167                if ($element['object']->is_calculated()) {
1168                    $strcalc = get_string('calculatedgrade', 'grades');
1169                    return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1170                            s($strcalc).'" alt="'.s($strcalc).'"/>';
1171
1172                } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1173                    if ($category = $element['object']->get_item_category()) {
1174                        switch ($category->aggregation) {
1175                            case GRADE_AGGREGATE_MEAN:
1176                            case GRADE_AGGREGATE_MEDIAN:
1177                            case GRADE_AGGREGATE_WEIGHTED_MEAN:
1178                            case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1179                            case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1180                                $stragg = get_string('aggregation', 'grades');
1181                                return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1182                                        'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1183                            case GRADE_AGGREGATE_SUM:
1184                                $stragg = get_string('aggregation', 'grades');
1185                                return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1186                                        'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1187                        }
1188                    }
1189
1190                } else if ($element['object']->itemtype == 'mod') {
1191                    //prevent outcomes being displaying the same icon as the activity they are attached to
1192                    if ($is_outcome) {
1193                        $stroutcome = s(get_string('outcome', 'grades'));
1194                        return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1195                            'class="icon itemicon" title="'.$stroutcome.
1196                            '" alt="'.$stroutcome.'"/>';
1197                    } else {
1198                        $strmodname = get_string('modulename', $element['object']->itemmodule);
1199                        return '<img src="'.$OUTPUT->pix_url('icon',
1200                            $element['object']->itemmodule) . '" ' .
1201                            'class="icon itemicon" title="' .s($strmodname).
1202                            '" alt="' .s($strmodname).'"/>';
1203                    }
1204                } else if ($element['object']->itemtype == 'manual') {
1205                    if ($element['object']->is_outcome_item()) {
1206                        $stroutcome = get_string('outcome', 'grades');
1207                        return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1208                                'class="icon itemicon" title="'.s($stroutcome).
1209                                '" alt="'.s($stroutcome).'"/>';
1210                    } else {
1211                        $strmanual = get_string('manualitem', 'grades');
1212                        return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
1213                                'class="icon itemicon" title="'.s($strmanual).
1214                                '" alt="'.s($strmanual).'"/>';
1215                    }
1216                }
1217                break;
1218
1219            case 'category':
1220                $strcat = get_string('category', 'grades');
1221                return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
1222                        'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1223        }
1224
1225        if ($spacerifnone) {
1226            return $OUTPUT->spacer().' ';
1227        } else {
1228            return '';
1229        }
1230    }
1231
1232    /**
1233     * Returns name of element optionally with icon and link
1234     *
1235     * @param array &$element An array representing an element in the grade_tree
1236     * @param bool  $withlink Whether or not this header has a link
1237     * @param bool  $icon Whether or not to display an icon with this header
1238     * @param bool  $spacerifnone return spacer if no icon found
1239     *
1240     * @return string header
1241     */
1242    public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
1243        $header = '';
1244
1245        if ($icon) {
1246            $header .= $this->get_element_icon($element, $spacerifnone);
1247        }
1248
1249        $header .= $element['object']->get_name();
1250
1251        if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1252            $element['type'] != 'courseitem') {
1253            return $header;
1254        }
1255
1256        if ($withlink) {
1257            $url = $this->get_activity_link($element);
1258            if ($url) {
1259                $a = new stdClass();
1260                $a->name = get_string('modulename', $element['object']->itemmodule);
1261                $title = get_string('linktoactivity', 'grades', $a);
1262
1263                $header = html_writer::link($url, $header, array('title' => $title));
1264            }
1265        }
1266
1267        return $header;
1268    }
1269
1270    private function get_activity_link($element) {
1271        global $CFG;
1272        /** @var array static cache of the grade.php file existence flags */
1273        static $hasgradephp = array();
1274
1275        $itemtype = $element['object']->itemtype;
1276        $itemmodule = $element['object']->itemmodule;
1277        $iteminstance = $element['object']->iteminstance;
1278        $itemnumber = $element['object']->itemnumber;
1279
1280        // Links only for module items that have valid instance, module and are
1281        // called from grade_tree with valid modinfo
1282        if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1283            return null;
1284        }
1285
1286        // Get $cm efficiently and with visibility information using modinfo
1287        $instances = $this->modinfo->get_instances();
1288        if (empty($instances[$itemmodule][$iteminstance])) {
1289            return null;
1290        }
1291        $cm = $instances[$itemmodule][$iteminstance];
1292
1293        // Do not add link if activity is not visible to the current user
1294        if (!$cm->uservisible) {
1295            return null;
1296        }
1297
1298        if (!array_key_exists($itemmodule, $hasgradephp)) {
1299            if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1300                $hasgradephp[$itemmodule] = true;
1301            } else {
1302                $hasgradephp[$itemmodule] = false;
1303            }
1304        }
1305
1306        // If module has grade.php, link to that, otherwise view.php
1307        if ($hasgradephp[$itemmodule]) {
1308            $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1309            if (isset($element['userid'])) {
1310                $args['userid'] = $element['userid'];
1311            }
1312            return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1313        } else {
1314            return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1315        }
1316    }
1317
1318    /**
1319     * Returns URL of a page that is supposed to contain detailed grade analysis
1320     *
1321     * At the moment, only activity modules are supported. The method generates link
1322     * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1323     * gradeid and userid. If the grade.php does not exist, null is returned.
1324     *
1325     * @return moodle_url|null URL or null if unable to construct it
1326     */
1327    public function get_grade_analysis_url(grade_grade $grade) {
1328        global $CFG;
1329        /** @var array static cache of the grade.php file existence flags */
1330        static $hasgradephp = array();
1331
1332        if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1333            throw new coding_exception('Passed grade without the associated grade item');
1334        }
1335        $item = $grade->grade_item;
1336
1337        if (!$item->is_external_item()) {
1338            // at the moment, only activity modules are supported
1339            return null;
1340        }
1341        if ($item->itemtype !== 'mod') {
1342            throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1343        }
1344        if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1345            return null;
1346        }
1347
1348        if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1349            if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1350                $hasgradephp[$item->itemmodule] = true;
1351            } else {
1352                $hasgradephp[$item->itemmodule] = false;
1353            }
1354        }
1355
1356        if (!$hasgradephp[$item->itemmodule]) {
1357            return null;
1358        }
1359
1360        $instances = $this->modinfo->get_instances();
1361        if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1362            return null;
1363        }
1364        $cm = $instances[$item->itemmodule][$item->iteminstance];
1365        if (!$cm->uservisible) {
1366            return null;
1367        }
1368
1369        $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1370            'id'         => $cm->id,
1371            'itemid'     => $item->id,
1372            'itemnumber' => $item->itemnumber,
1373            'gradeid'    => $grade->id,
1374            'userid'     => $grade->userid,
1375        ));
1376
1377        return $url;
1378    }
1379
1380    /**
1381     * Returns an action icon leading to the grade analysis page
1382     *
1383     * @param grade_grade $grade
1384     * @return string
1385     */
1386    public function get_grade_analysis_icon(grade_grade $grade) {
1387        global $OUTPUT;
1388
1389        $url = $this->get_grade_analysis_url($grade);
1390        if (is_null($url)) {
1391            return '';
1392        }
1393
1394        return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1395            get_string('gradeanalysis', 'core_grades')));
1396    }
1397
1398    /**
1399     * Returns the grade eid - the grade may not exist yet.
1400     *
1401     * @param grade_grade $grade_grade A grade_grade object
1402     *
1403     * @return string eid
1404     */
1405    public function get_grade_eid($grade_grade) {
1406        if (empty($grade_grade->id)) {
1407            return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1408        } else {
1409            return 'g'.$grade_grade->id;
1410        }
1411    }
1412
1413    /**
1414     * Returns the grade_item eid
1415     * @param grade_item $grade_item A grade_item object
1416     * @return string eid
1417     */
1418    public function get_item_eid($grade_item) {
1419        return 'i'.$grade_item->id;
1420    }
1421
1422    /**
1423     * Given a grade_tree element, returns an array of parameters
1424     * used to build an icon for that element.
1425     *
1426     * @param array $element An array representing an element in the grade_tree
1427     *
1428     * @return array
1429     */
1430    public function get_params_for_iconstr($element) {
1431        $strparams = new stdClass();
1432        $strparams->category = '';
1433        $strparams->itemname = '';
1434        $strparams->itemmodule = '';
1435
1436        if (!method_exists($element['object'], 'get_name')) {
1437            return $strparams;
1438        }
1439
1440        $strparams->itemname = html_to_text($element['object']->get_name());
1441
1442        // If element name is categorytotal, get the name of the parent category
1443        if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1444            $parent = $element['object']->get_parent_category();
1445            $strparams->category = $parent->get_name() . ' ';
1446        } else {
1447            $strparams->category = '';
1448        }
1449
1450        $strparams->itemmodule = null;
1451        if (isset($element['object']->itemmodule)) {
1452            $strparams->itemmodule = $element['object']->itemmodule;
1453        }
1454        return $strparams;
1455    }
1456
1457    /**
1458     * Return edit icon for give element
1459     *
1460     * @param array  $element An array represen…

Large files files are truncated, but you can click here to view the full file