2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Functions used by gradebook plugins and reports.
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
25 require_once($CFG->libdir
. '/gradelib.php');
26 require_once($CFG->dirroot
. '/grade/export/lib.php');
29 * This class iterates over all users that are graded in a course.
30 * Returns detailed info about users and their grades.
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class graded_users_iterator
{
38 * The couse whose users we are interested in
43 * An array of grade items or null if only user data was requested
45 protected $grade_items;
48 * The group ID we are interested in. 0 means all groups.
53 * A recordset of graded users
58 * A recordset of user grades (grade_grade instances)
63 * Array used when moving to next user while iterating through the grades recordset
65 protected $gradestack;
68 * The first field of the users table by which the array of users will be sorted
70 protected $sortfield1;
73 * Should sortfield1 be ASC or DESC
75 protected $sortorder1;
78 * The second field of the users table by which the array of users will be sorted
80 protected $sortfield2;
83 * Should sortfield2 be ASC or DESC
85 protected $sortorder2;
88 * Should users whose enrolment has been suspended be ignored?
90 protected $onlyactive = false;
93 * Enable user custom fields
95 protected $allowusercustomfields = false;
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
101 protected $suspendedusers = array();
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)
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;
125 $this->gradestack
= array();
129 * Initialise the iterator
131 * @return boolean success
133 public function init() {
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.
145 $coursecontext = context_course
::instance($this->course
->id
);
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
);
151 $params = array_merge($params, $enrolledparams, $relatedctxparams);
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
;
163 if (empty($this->sortfield1
)) {
164 // We must do some sorting even if not specified.
165 $ofields = ", u.id AS usrt";
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";
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";
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++
;
201 $users_sql = "SELECT $userfields $ofields
203 JOIN ($enrolledsql) je ON je.id = u.id
204 $groupsql $customfieldssql
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
214 $this->users_rs
= $DB->get_recordset_sql($users_sql, $params);
216 if (!$this->onlyactive
) {
217 $context = context_course
::instance($this->course
->id
);
218 $this->suspendedusers
= get_suspended_userids($context);
220 $this->suspendedusers
= array();
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);
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
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
240 AND g.itemid $itemidsql
242 ORDER BY $order, g.itemid ASC";
243 $this->grades_rs
= $DB->get_recordset_sql($grades_sql, $params);
245 $this->grades_rs
= false;
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
255 public function next_user() {
256 if (!$this->users_rs
) {
257 return false; // no users present
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 :-(
265 return false; // no more users
267 $user = $this->users_rs
->current();
268 $this->users_rs
->next();
271 // find grades of this user
272 $grade_records = array();
274 if (!$current = $this->_pop()) {
275 break; // no more grades
278 if (empty($current->userid
)) {
282 if ($current->userid
!= $user->id
) {
283 // grade of the next user, we have all for this user
284 $this->_push($current);
288 $grade_records[$current->itemid
] = $current;
292 $feedbacks = array();
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();
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);
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);
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;
324 * Close the iterator, do not forget to call this function
326 public function close() {
327 if ($this->users_rs
) {
328 $this->users_rs
->close();
329 $this->users_rs
= null;
331 if ($this->grades_rs
) {
332 $this->grades_rs
->close();
333 $this->grades_rs
= null;
335 $this->gradestack
= array();
339 * Should all enrolled users be exported or just those with an active enrolment?
341 * @param bool $onlyactive True to limit the export to users with an active enrolment
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
);
347 $this->onlyactive
= $onlyactive;
351 * Allow custom fields to be included
353 * @param bool $allow Whether to allow custom fields or not
356 public function allow_user_custom_fields($allow = true) {
358 $this->allowusercustomfields
= true;
360 $this->allowusercustomfields
= false;
365 * Add a grade_grade instance to the grade stack
367 * @param grade_grade $grade Grade object
371 private function _push($grade) {
372 array_push($this->gradestack
, $grade);
377 * Remove a grade_grade instance from the grade stack
379 * @return grade_grade current grade object
381 private function _pop() {
383 if (empty($this->gradestack
)) {
384 if (empty($this->grades_rs
) ||
!$this->grades_rs
->valid()) {
385 return null; // no grades present
388 $current = $this->grades_rs
->current();
390 $this->grades_rs
->next();
394 return array_pop($this->gradestack
);
400 * Print a selection popup form of the graded users in a course.
402 * @deprecated since 2.0
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
412 function 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));
417 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
420 if (is_null($userid)) {
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);
432 $label = get_string('selectauser', 'grades');
434 $menu[0] = get_string('allusers', 'grades');
435 $label = get_string('selectalloroneuser', 'grades');
437 while ($userdata = $gui->next_user()) {
438 $user = $userdata->user
;
439 $userfullname = fullname($user);
440 if ($user->suspendedenrolment
) {
441 $menususpendedusers[$user->id
] = $userfullname;
443 $menu[$user->id
] = $userfullname;
449 $menu[0] .= " (" . (count($menu) +
count($menususpendedusers) - 1) . ")";
452 if (!empty($menususpendedusers)) {
453 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
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';
462 * Hide warning about changed grades during upgrade to 2.8.
464 * @param int $courseid The current course id.
466 function hide_natural_aggregation_upgrade_notice($courseid) {
467 unset_config('show_sumofgrades_upgrade_' . $courseid);
471 * Hide warning about changed grades during upgrade to 2.8.
473 * @param int $courseid The current course id.
475 function hide_aggregatesubcats_upgrade_notice($courseid) {
476 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
480 * Print warning about changed grades during upgrade to 2.8.
482 * @param int $courseid The current course id.
483 * @param context $context The course context.
484 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
485 * @param boolean $return return as string
487 * @return nothing or string if $return true
489 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
493 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL
) && confirm_sesskey();
494 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
495 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL
) && confirm_sesskey();
496 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
498 // Do not do anything if they are not a teacher.
499 if ($hidesubcatswarning ||
$showsubcatswarning ||
$hidenaturalwarning ||
$shownaturalwarning) {
500 if (!has_capability('moodle/grade:manage', $context)) {
505 // Hide the warning if the user told it to go away.
506 if ($hidenaturalwarning) {
507 hide_natural_aggregation_upgrade_notice($courseid);
509 // Hide the warning if the user told it to go away.
510 if ($hidesubcatswarning) {
511 hide_aggregatesubcats_upgrade_notice($courseid);
514 if (!$hidenaturalwarning && $shownaturalwarning) {
515 $message = get_string('sumofgradesupgradedgrades', 'grades');
516 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
517 $urlparams = array( 'id' => $courseid,
518 'seensumofgradesupgradedgrades' => true,
519 'sesskey' => sesskey());
520 $goawayurl = new moodle_url($thispage, $urlparams);
521 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
522 $html .= $OUTPUT->notification($message, 'notifysuccess');
523 $html .= $goawaybutton;
526 if (!$hidesubcatswarning && $showsubcatswarning) {
527 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
528 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
529 $urlparams = array( 'id' => $courseid,
530 'seenaggregatesubcatsupgradedgrades' => true,
531 'sesskey' => sesskey());
532 $goawayurl = new moodle_url($thispage, $urlparams);
533 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
534 $html .= $OUTPUT->notification($message, 'notifysuccess');
535 $html .= $goawaybutton;
546 * Print grading plugin selection popup form.
548 * @param array $plugin_info An array of plugins containing information for the selector
549 * @param boolean $return return as string
551 * @return nothing or string if $return true
553 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
554 global $CFG, $OUTPUT, $PAGE;
560 foreach ($plugin_info as $plugin_type => $plugins) {
561 if ($plugin_type == 'strings') {
565 $first_plugin = reset($plugins);
567 $sectionname = $plugin_info['strings'][$plugin_type];
570 foreach ($plugins as $plugin) {
571 $link = $plugin->link
->out(false);
572 $section[$link] = $plugin->string;
574 if ($plugin_type === $active_type and $plugin->id
=== $active_plugin) {
580 $menu[] = array($sectionname=>$section);
584 // finally print/return the popup form
586 $select = new url_select($menu, $active, null, 'choosepluginreport');
587 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
589 return $OUTPUT->render($select);
591 echo $OUTPUT->render($select);
594 // only one option - no plugin selector needed
600 * Print grading plugin selection tab-based navigation.
602 * @param string $active_type type of plugin on current page - import, export, report or edit
603 * @param string $active_plugin active plugin type - grader, user, cvs, ...
604 * @param array $plugin_info Array of plugins
605 * @param boolean $return return as string
607 * @return nothing or string if $return true
609 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
610 global $CFG, $COURSE;
612 if (!isset($currenttab)) { //TODO: this is weird
618 $bottom_row = array();
619 $inactive = array($active_plugin);
620 $activated = array();
625 foreach ($plugin_info as $plugin_type => $plugins) {
626 if ($plugin_type == 'strings') {
630 // If $plugins is actually the definition of a child-less parent link:
631 if (!empty($plugins->id
)) {
632 $string = $plugins->string;
633 if (!empty($plugin_info[$active_type]->parent
)) {
634 $string = $plugin_info[$active_type]->parent
->string;
637 $top_row[] = new tabobject($plugin_type, $plugins->link
, $string);
641 $first_plugin = reset($plugins);
642 $url = $first_plugin->link
;
644 if ($plugin_type == 'report') {
645 $url = $CFG->wwwroot
.'/grade/report/index.php?id='.$COURSE->id
;
648 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
650 if ($active_type == $plugin_type) {
651 foreach ($plugins as $plugin) {
652 $bottom_row[] = new tabobject($plugin->id
, $plugin->link
, $plugin->string);
653 if ($plugin->id
== $active_plugin) {
654 $inactive = array($plugin->id
);
661 $tabs[] = $bottom_row;
664 return print_tabs($tabs, $active_type, $inactive, $activated, true);
666 print_tabs($tabs, $active_type, $inactive, $activated);
671 * grade_get_plugin_info
673 * @param int $courseid The course id
674 * @param string $active_type type of plugin on current page - import, export, report or edit
675 * @param string $active_plugin active plugin type - grader, user, cvs, ...
679 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
682 $context = context_course
::instance($courseid);
684 $plugin_info = array();
687 $url_prefix = $CFG->wwwroot
. '/grade/';
690 $plugin_info['strings'] = grade_helper
::get_plugin_strings();
692 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
693 $plugin_info['report'] = $reports;
696 if ($settings = grade_helper
::get_info_manage_settings($courseid)) {
697 $plugin_info['settings'] = $settings;
700 if ($scale = grade_helper
::get_info_scales($courseid)) {
701 $plugin_info['scale'] = array('view'=>$scale);
704 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
705 $plugin_info['outcome'] = $outcomes;
708 if ($letters = grade_helper
::get_info_letters($courseid)) {
709 $plugin_info['letter'] = $letters;
712 if ($imports = grade_helper
::get_plugins_import($courseid)) {
713 $plugin_info['import'] = $imports;
716 if ($exports = grade_helper
::get_plugins_export($courseid)) {
717 $plugin_info['export'] = $exports;
720 foreach ($plugin_info as $plugin_type => $plugins) {
721 if (!empty($plugins->id
) && $active_plugin == $plugins->id
) {
722 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
725 foreach ($plugins as $plugin) {
726 if (is_a($plugin, 'grade_plugin_info')) {
727 if ($active_plugin == $plugin->id
) {
728 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
734 foreach ($plugin_info as $plugin_type => $plugins) {
735 if (!empty($plugins->id
) && $active_plugin == $plugins->id
) {
736 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
739 foreach ($plugins as $plugin) {
740 if (is_a($plugin, 'grade_plugin_info')) {
741 if ($active_plugin == $plugin->id
) {
742 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
752 * A simple class containing info about grade plugins.
753 * Can be subclassed for special rules
755 * @package core_grades
756 * @copyright 2009 Nicolas Connault
757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
759 class grade_plugin_info
{
761 * A unique id for this plugin
767 * A URL to access this plugin
773 * The name of this plugin
779 * Another grade_plugin_info object, parent of the current one
788 * @param int $id A unique id for this plugin
789 * @param string $link A URL to access this plugin
790 * @param string $string The name of this plugin
791 * @param object $parent Another grade_plugin_info object, parent of the current one
795 public function __construct($id, $link, $string, $parent=null) {
798 $this->string = $string;
799 $this->parent
= $parent;
804 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
805 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
806 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
807 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
808 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
810 * @param int $courseid Course id
811 * @param string $active_type The type of the current page (report, settings,
812 * import, export, scales, outcomes, letters)
813 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
814 * @param string $heading The heading of the page. Tries to guess if none is given
815 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
816 * @param string $bodytags Additional attributes that will be added to the <body> tag
817 * @param string $buttons Additional buttons to display on the page
818 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
819 * @param string $headerhelpidentifier The help string identifier if required.
820 * @param string $headerhelpcomponent The component for the help string.
822 * @return string HTML code or nothing if $return == false
824 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
825 $heading = false, $return=false,
826 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null) {
827 global $CFG, $OUTPUT, $PAGE;
829 if ($active_type === 'preferences') {
830 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
831 $active_type = 'settings';
834 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
836 // Determine the string of the active plugin
837 $stractive_plugin = ($active_plugin) ?
$plugin_info['strings']['active_plugin_str'] : $heading;
838 $stractive_type = $plugin_info['strings'][$active_type];
840 if (empty($plugin_info[$active_type]->id
) ||
!empty($plugin_info[$active_type]->parent
)) {
841 $title = $PAGE->course
->fullname
.': ' . $stractive_type . ': ' . $stractive_plugin;
843 $title = $PAGE->course
->fullname
.': ' . $stractive_plugin;
846 if ($active_type == 'report') {
847 $PAGE->set_pagelayout('report');
849 $PAGE->set_pagelayout('admin');
851 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
852 $PAGE->set_heading($title);
853 if ($buttons instanceof single_button
) {
854 $buttons = $OUTPUT->render($buttons);
856 $PAGE->set_button($buttons);
857 if ($courseid != SITEID
) {
858 grade_extend_settings($plugin_info, $courseid);
861 $returnval = $OUTPUT->header();
867 // Guess heading if not given explicitly
869 $heading = $stractive_plugin;
872 if ($shownavigation) {
873 if ($courseid != SITEID
&&
874 ($CFG->grade_navmethod
== GRADE_NAVMETHOD_COMBO ||
$CFG->grade_navmethod
== GRADE_NAVMETHOD_DROPDOWN
)) {
875 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
879 // Add a help dialogue box if provided.
880 if (isset($headerhelpidentifier)) {
881 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
883 $output = $OUTPUT->heading($heading);
887 $returnval .= $output;
892 if ($courseid != SITEID
&&
893 ($CFG->grade_navmethod
== GRADE_NAVMETHOD_COMBO ||
$CFG->grade_navmethod
== GRADE_NAVMETHOD_TABS
)) {
894 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
898 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
899 context_course
::instance($courseid),
909 * Utility class used for return tracking when using edit and other forms in grade plugins
911 * @package core_grades
912 * @copyright 2009 Nicolas Connault
913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
915 class grade_plugin_return
{
925 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
927 public function grade_plugin_return($params = null) {
928 if (empty($params)) {
929 $this->type
= optional_param('gpr_type', null, PARAM_SAFEDIR
);
930 $this->plugin
= optional_param('gpr_plugin', null, PARAM_PLUGIN
);
931 $this->courseid
= optional_param('gpr_courseid', null, PARAM_INT
);
932 $this->userid
= optional_param('gpr_userid', null, PARAM_INT
);
933 $this->page
= optional_param('gpr_page', null, PARAM_INT
);
936 foreach ($params as $key=>$value) {
937 if (property_exists($this, $key)) {
938 $this->$key = $value;
945 * Returns return parameters as options array suitable for buttons.
946 * @return array options
948 public function get_options() {
949 if (empty($this->type
)) {
955 if (!empty($this->plugin
)) {
956 $params['plugin'] = $this->plugin
;
959 if (!empty($this->courseid
)) {
960 $params['id'] = $this->courseid
;
963 if (!empty($this->userid
)) {
964 $params['userid'] = $this->userid
;
967 if (!empty($this->page
)) {
968 $params['page'] = $this->page
;
977 * @param string $default default url when params not set
978 * @param array $extras Extra URL parameters
982 public function get_return_url($default, $extras=null) {
985 if (empty($this->type
) or empty($this->plugin
)) {
989 $url = $CFG->wwwroot
.'/grade/'.$this->type
.'/'.$this->plugin
.'/index.php';
992 if (!empty($this->courseid
)) {
993 $url .= $glue.'id='.$this->courseid
;
997 if (!empty($this->userid
)) {
998 $url .= $glue.'userid='.$this->userid
;
1002 if (!empty($this->page
)) {
1003 $url .= $glue.'page='.$this->page
;
1007 if (!empty($extras)) {
1008 foreach ($extras as $key=>$value) {
1009 $url .= $glue.$key.'='.$value;
1018 * Returns string with hidden return tracking form elements.
1021 public function get_form_fields() {
1022 if (empty($this->type
)) {
1026 $result = '<input type="hidden" name="gpr_type" value="'.$this->type
.'" />';
1028 if (!empty($this->plugin
)) {
1029 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin
.'" />';
1032 if (!empty($this->courseid
)) {
1033 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid
.'" />';
1036 if (!empty($this->userid
)) {
1037 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid
.'" />';
1040 if (!empty($this->page
)) {
1041 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page
.'" />';
1046 * Add hidden elements into mform
1048 * @param object &$mform moodle form object
1052 public function add_mform_elements(&$mform) {
1053 if (empty($this->type
)) {
1057 $mform->addElement('hidden', 'gpr_type', $this->type
);
1058 $mform->setType('gpr_type', PARAM_SAFEDIR
);
1060 if (!empty($this->plugin
)) {
1061 $mform->addElement('hidden', 'gpr_plugin', $this->plugin
);
1062 $mform->setType('gpr_plugin', PARAM_PLUGIN
);
1065 if (!empty($this->courseid
)) {
1066 $mform->addElement('hidden', 'gpr_courseid', $this->courseid
);
1067 $mform->setType('gpr_courseid', PARAM_INT
);
1070 if (!empty($this->userid
)) {
1071 $mform->addElement('hidden', 'gpr_userid', $this->userid
);
1072 $mform->setType('gpr_userid', PARAM_INT
);
1075 if (!empty($this->page
)) {
1076 $mform->addElement('hidden', 'gpr_page', $this->page
);
1077 $mform->setType('gpr_page', PARAM_INT
);
1082 * Add return tracking params into url
1084 * @param moodle_url $url A URL
1086 * @return string $url with return tracking params
1088 public function add_url_params(moodle_url
$url) {
1089 if (empty($this->type
)) {
1093 $url->param('gpr_type', $this->type
);
1095 if (!empty($this->plugin
)) {
1096 $url->param('gpr_plugin', $this->plugin
);
1099 if (!empty($this->courseid
)) {
1100 $url->param('gpr_courseid' ,$this->courseid
);
1103 if (!empty($this->userid
)) {
1104 $url->param('gpr_userid', $this->userid
);
1107 if (!empty($this->page
)) {
1108 $url->param('gpr_page', $this->page
);
1116 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1118 * @param string $path The path of the calling script (using __FILE__?)
1119 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1120 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1121 * an array of keys and values (e.g courseid => $courseid, itemid...)
1125 function grade_build_nav($path, $pagename=null, $id=null) {
1126 global $CFG, $COURSE, $PAGE;
1128 $strgrades = get_string('grades', 'grades');
1130 // Parse the path and build navlinks from its elements
1131 $dirroot_length = strlen($CFG->dirroot
) +
1; // Add 1 for the first slash
1132 $path = substr($path, $dirroot_length);
1133 $path = str_replace('\\', '/', $path);
1135 $path_elements = explode('/', $path);
1137 $path_elements_count = count($path_elements);
1139 // First link is always 'grade'
1140 $PAGE->navbar
->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id
)));
1143 $numberofelements = 3;
1145 // Prepare URL params string
1146 $linkparams = array();
1147 if (!is_null($id)) {
1148 if (is_array($id)) {
1149 foreach ($id as $idkey => $idvalue) {
1150 $linkparams[$idkey] = $idvalue;
1153 $linkparams['id'] = $id;
1159 // Remove file extensions from filenames
1160 foreach ($path_elements as $key => $filename) {
1161 $path_elements[$key] = str_replace('.php', '', $filename);
1164 // Second level links
1165 switch ($path_elements[1]) {
1166 case 'edit': // No link
1167 if ($path_elements[3] != 'index.php') {
1168 $numberofelements = 4;
1171 case 'import': // No link
1173 case 'export': // No link
1176 // $id is required for this link. Do not print it if $id isn't given
1177 if (!is_null($id)) {
1178 $link = new moodle_url('/grade/report/index.php', $linkparams);
1181 if ($path_elements[2] == 'grader') {
1182 $numberofelements = 4;
1187 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1188 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1189 " as the second path element after 'grade'.");
1192 $PAGE->navbar
->add(get_string($path_elements[1], 'grades'), $link);
1194 // Third level links
1195 if (empty($pagename)) {
1196 $pagename = get_string($path_elements[2], 'grades');
1199 switch ($numberofelements) {
1201 $PAGE->navbar
->add($pagename, $link);
1204 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1205 $PAGE->navbar
->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1207 $PAGE->navbar
->add($pagename);
1215 * General structure representing grade items in course
1217 * @package core_grades
1218 * @copyright 2009 Nicolas Connault
1219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1221 class grade_structure
{
1227 * Reference to modinfo for current course (for performance, to save
1228 * retrieving it from courseid every time). Not actually set except for
1229 * the grade_tree type.
1230 * @var course_modinfo
1235 * 1D array of grade items only
1240 * Returns icon of element
1242 * @param array &$element An array representing an element in the grade_tree
1243 * @param bool $spacerifnone return spacer if no icon found
1245 * @return string icon or spacer
1247 public function get_element_icon(&$element, $spacerifnone=false) {
1248 global $CFG, $OUTPUT;
1249 require_once $CFG->libdir
.'/filelib.php';
1251 switch ($element['type']) {
1254 case 'categoryitem':
1255 $is_course = $element['object']->is_course_item();
1256 $is_category = $element['object']->is_category_item();
1257 $is_scale = $element['object']->gradetype
== GRADE_TYPE_SCALE
;
1258 $is_value = $element['object']->gradetype
== GRADE_TYPE_VALUE
;
1259 $is_outcome = !empty($element['object']->outcomeid
);
1261 if ($element['object']->is_calculated()) {
1262 $strcalc = get_string('calculatedgrade', 'grades');
1263 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1264 s($strcalc).'" alt="'.s($strcalc).'"/>';
1266 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1267 if ($category = $element['object']->get_item_category()) {
1268 $aggrstrings = grade_helper
::get_aggregation_strings();
1269 $stragg = $aggrstrings[$category->aggregation
];
1270 switch ($category->aggregation
) {
1271 case GRADE_AGGREGATE_MEAN
:
1272 case GRADE_AGGREGATE_MEDIAN
:
1273 case GRADE_AGGREGATE_WEIGHTED_MEAN
:
1274 case GRADE_AGGREGATE_WEIGHTED_MEAN2
:
1275 case GRADE_AGGREGATE_EXTRACREDIT_MEAN
:
1276 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1277 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1278 case GRADE_AGGREGATE_SUM
:
1279 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1280 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1282 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" ' .
1283 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1287 } else if ($element['object']->itemtype
== 'mod') {
1288 //prevent outcomes being displaying the same icon as the activity they are attached to
1290 $stroutcome = s(get_string('outcome', 'grades'));
1291 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1292 'class="icon itemicon" title="'.$stroutcome.
1293 '" alt="'.$stroutcome.'"/>';
1295 $strmodname = get_string('modulename', $element['object']->itemmodule
);
1296 return '<img src="'.$OUTPUT->pix_url('icon',
1297 $element['object']->itemmodule
) . '" ' .
1298 'class="icon itemicon" title="' .s($strmodname).
1299 '" alt="' .s($strmodname).'"/>';
1301 } else if ($element['object']->itemtype
== 'manual') {
1302 if ($element['object']->is_outcome_item()) {
1303 $stroutcome = get_string('outcome', 'grades');
1304 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1305 'class="icon itemicon" title="'.s($stroutcome).
1306 '" alt="'.s($stroutcome).'"/>';
1308 $strmanual = get_string('manualitem', 'grades');
1309 return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
1310 'class="icon itemicon" title="'.s($strmanual).
1311 '" alt="'.s($strmanual).'"/>';
1317 $strcat = get_string('category', 'grades');
1318 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
1319 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1322 if ($spacerifnone) {
1323 return $OUTPUT->spacer().' ';
1330 * Returns name of element optionally with icon and link
1332 * @param array &$element An array representing an element in the grade_tree
1333 * @param bool $withlink Whether or not this header has a link
1334 * @param bool $icon Whether or not to display an icon with this header
1335 * @param bool $spacerifnone return spacer if no icon found
1336 * @param bool $withdescription Show description if defined by this item.
1338 * @return string header
1340 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false, $withdescription=false) {
1344 $header .= $this->get_element_icon($element, $spacerifnone);
1347 $header .= $element['object']->get_name();
1349 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1350 $element['type'] != 'courseitem') {
1355 $url = $this->get_activity_link($element);
1357 $a = new stdClass();
1358 $a->name
= get_string('modulename', $element['object']->itemmodule
);
1359 $title = get_string('linktoactivity', 'grades', $a);
1361 $header = html_writer
::link($url, $header, array('title' => $title));
1365 if ($withdescription) {
1366 $desc = $element['object']->get_description();
1367 if (!empty($desc)) {
1368 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1375 private function get_activity_link($element) {
1377 /** @var array static cache of the grade.php file existence flags */
1378 static $hasgradephp = array();
1380 $itemtype = $element['object']->itemtype
;
1381 $itemmodule = $element['object']->itemmodule
;
1382 $iteminstance = $element['object']->iteminstance
;
1383 $itemnumber = $element['object']->itemnumber
;
1385 // Links only for module items that have valid instance, module and are
1386 // called from grade_tree with valid modinfo
1387 if ($itemtype != 'mod' ||
!$iteminstance ||
!$itemmodule ||
!$this->modinfo
) {
1391 // Get $cm efficiently and with visibility information using modinfo
1392 $instances = $this->modinfo
->get_instances();
1393 if (empty($instances[$itemmodule][$iteminstance])) {
1396 $cm = $instances[$itemmodule][$iteminstance];
1398 // Do not add link if activity is not visible to the current user
1399 if (!$cm->uservisible
) {
1403 if (!array_key_exists($itemmodule, $hasgradephp)) {
1404 if (file_exists($CFG->dirroot
. '/mod/' . $itemmodule . '/grade.php')) {
1405 $hasgradephp[$itemmodule] = true;
1407 $hasgradephp[$itemmodule] = false;
1411 // If module has grade.php, link to that, otherwise view.php
1412 if ($hasgradephp[$itemmodule]) {
1413 $args = array('id' => $cm->id
, 'itemnumber' => $itemnumber);
1414 if (isset($element['userid'])) {
1415 $args['userid'] = $element['userid'];
1417 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1419 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id
));
1424 * Returns URL of a page that is supposed to contain detailed grade analysis
1426 * At the moment, only activity modules are supported. The method generates link
1427 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1428 * gradeid and userid. If the grade.php does not exist, null is returned.
1430 * @return moodle_url|null URL or null if unable to construct it
1432 public function get_grade_analysis_url(grade_grade
$grade) {
1434 /** @var array static cache of the grade.php file existence flags */
1435 static $hasgradephp = array();
1437 if (empty($grade->grade_item
) or !($grade->grade_item
instanceof grade_item
)) {
1438 throw new coding_exception('Passed grade without the associated grade item');
1440 $item = $grade->grade_item
;
1442 if (!$item->is_external_item()) {
1443 // at the moment, only activity modules are supported
1446 if ($item->itemtype
!== 'mod') {
1447 throw new coding_exception('Unknown external itemtype: '.$item->itemtype
);
1449 if (empty($item->iteminstance
) or empty($item->itemmodule
) or empty($this->modinfo
)) {
1453 if (!array_key_exists($item->itemmodule
, $hasgradephp)) {
1454 if (file_exists($CFG->dirroot
. '/mod/' . $item->itemmodule
. '/grade.php')) {
1455 $hasgradephp[$item->itemmodule
] = true;
1457 $hasgradephp[$item->itemmodule
] = false;
1461 if (!$hasgradephp[$item->itemmodule
]) {
1465 $instances = $this->modinfo
->get_instances();
1466 if (empty($instances[$item->itemmodule
][$item->iteminstance
])) {
1469 $cm = $instances[$item->itemmodule
][$item->iteminstance
];
1470 if (!$cm->uservisible
) {
1474 $url = new moodle_url('/mod/'.$item->itemmodule
.'/grade.php', array(
1476 'itemid' => $item->id
,
1477 'itemnumber' => $item->itemnumber
,
1478 'gradeid' => $grade->id
,
1479 'userid' => $grade->userid
,
1486 * Returns an action icon leading to the grade analysis page
1488 * @param grade_grade $grade
1491 public function get_grade_analysis_icon(grade_grade
$grade) {
1494 $url = $this->get_grade_analysis_url($grade);
1495 if (is_null($url)) {
1499 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1500 get_string('gradeanalysis', 'core_grades')));
1504 * Returns the grade eid - the grade may not exist yet.
1506 * @param grade_grade $grade_grade A grade_grade object
1508 * @return string eid
1510 public function get_grade_eid($grade_grade) {
1511 if (empty($grade_grade->id
)) {
1512 return 'n'.$grade_grade->itemid
.'u'.$grade_grade->userid
;
1514 return 'g'.$grade_grade->id
;
1519 * Returns the grade_item eid
1520 * @param grade_item $grade_item A grade_item object
1521 * @return string eid
1523 public function get_item_eid($grade_item) {
1524 return 'ig'.$grade_item->id
;
1528 * Given a grade_tree element, returns an array of parameters
1529 * used to build an icon for that element.
1531 * @param array $element An array representing an element in the grade_tree
1535 public function get_params_for_iconstr($element) {
1536 $strparams = new stdClass();
1537 $strparams->category
= '';
1538 $strparams->itemname
= '';
1539 $strparams->itemmodule
= '';
1541 if (!method_exists($element['object'], 'get_name')) {
1545 $strparams->itemname
= html_to_text($element['object']->get_name());
1547 // If element name is categorytotal, get the name of the parent category
1548 if ($strparams->itemname
== get_string('categorytotal', 'grades')) {
1549 $parent = $element['object']->get_parent_category();
1550 $strparams->category
= $parent->get_name() . ' ';
1552 $strparams->category
= '';
1555 $strparams->itemmodule
= null;
1556 if (isset($element['object']->itemmodule
)) {
1557 $strparams->itemmodule
= $element['object']->itemmodule
;
1563 * Return a reset icon for the given element.
1565 * @param array $element An array representing an element in the grade_tree
1566 * @param object $gpr A grade_plugin_return object
1567 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1568 * @return string|action_menu_link
1570 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1571 global $CFG, $OUTPUT;
1573 // Limit to category items set to use the natural weights aggregation method, and users
1574 // with the capability to manage grades.
1575 if ($element['type'] != 'category' ||
$element['object']->aggregation
!= GRADE_AGGREGATE_SUM ||
1576 !has_capability('moodle/grade:manage', $this->context
)) {
1577 return $returnactionmenulink ?
null : '';
1580 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1581 $url = new moodle_url('/grade/edit/tree/action.php', array(
1582 'id' => $this->courseid
,
1583 'action' => 'resetweights',
1584 'eid' => $element['eid'],
1585 'sesskey' => sesskey(),
1588 if ($returnactionmenulink) {
1589 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1590 get_string('resetweightsshort', 'grades'));
1592 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1597 * Return edit icon for give element
1599 * @param array $element An array representing an element in the grade_tree
1600 * @param object $gpr A grade_plugin_return object
1601 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1602 * @return string|action_menu_link
1604 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1605 global $CFG, $OUTPUT;
1607 if (!has_capability('moodle/grade:manage', $this->context
)) {
1608 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context
)) {
1609 // oki - let them override grade
1611 return $returnactionmenulink ?
null : '';
1615 static $strfeedback = null;
1616 static $streditgrade = null;
1617 if (is_null($streditgrade)) {
1618 $streditgrade = get_string('editgrade', 'grades');
1619 $strfeedback = get_string('feedback');
1622 $strparams = $this->get_params_for_iconstr($element);
1624 $object = $element['object'];
1626 switch ($element['type']) {
1628 case 'categoryitem':
1630 $stredit = get_string('editverbose', 'grades', $strparams);
1631 if (empty($object->outcomeid
) ||
empty($CFG->enableoutcomes
)) {
1632 $url = new moodle_url('/grade/edit/tree/item.php',
1633 array('courseid' => $this->courseid
, 'id' => $object->id
));
1635 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1636 array('courseid' => $this->courseid
, 'id' => $object->id
));
1641 $stredit = get_string('editverbose', 'grades', $strparams);
1642 $url = new moodle_url('/grade/edit/tree/category.php',
1643 array('courseid' => $this->courseid
, 'id' => $object->id
));
1647 $stredit = $streditgrade;
1648 if (empty($object->id
)) {
1649 $url = new moodle_url('/grade/edit/tree/grade.php',
1650 array('courseid' => $this->courseid
, 'itemid' => $object->itemid
, 'userid' => $object->userid
));
1652 $url = new moodle_url('/grade/edit/tree/grade.php',
1653 array('courseid' => $this->courseid
, 'id' => $object->id
));
1655 if (!empty($object->feedback
)) {
1656 $feedback = addslashes_js(trim(format_string($object->feedback
, $object->feedbackformat
)));
1665 if ($returnactionmenulink) {
1666 return new action_menu_link_secondary($gpr->add_url_params($url),
1667 new pix_icon('t/edit', $stredit),
1668 get_string('editsettings'));
1670 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1674 return $returnactionmenulink ?
null : '';
1679 * Return hiding icon for give element
1681 * @param array $element An array representing an element in the grade_tree
1682 * @param object $gpr A grade_plugin_return object
1683 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1684 * @return string|action_menu_link
1686 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1687 global $CFG, $OUTPUT;
1689 if (!$element['object']->can_control_visibility()) {
1690 return $returnactionmenulink ?
null : '';
1693 if (!has_capability('moodle/grade:manage', $this->context
) and
1694 !has_capability('moodle/grade:hide', $this->context
)) {
1695 return $returnactionmenulink ?
null : '';
1698 $strparams = $this->get_params_for_iconstr($element);
1699 $strshow = get_string('showverbose', 'grades', $strparams);
1700 $strhide = get_string('hideverbose', 'grades', $strparams);
1702 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1703 $url = $gpr->add_url_params($url);
1705 if ($element['object']->is_hidden()) {
1707 $tooltip = $strshow;
1709 // Change the icon and add a tooltip showing the date
1710 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1711 $type = 'hiddenuntil';
1712 $tooltip = get_string('hiddenuntildate', 'grades',
1713 userdate($element['object']->get_hidden()));
1716 $url->param('action', 'show');
1718 if ($returnactionmenulink) {
1719 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1721 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1725 $url->param('action', 'hide');
1726 if ($returnactionmenulink) {
1727 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1729 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1737 * Return locking icon for given element
1739 * @param array $element An array representing an element in the grade_tree
1740 * @param object $gpr A grade_plugin_return object
1744 public function get_locking_icon($element, $gpr) {
1745 global $CFG, $OUTPUT;
1747 $strparams = $this->get_params_for_iconstr($element);
1748 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1749 $strlock = get_string('lockverbose', 'grades', $strparams);
1751 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1752 $url = $gpr->add_url_params($url);
1754 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1755 if ($element['type'] == 'grade' && $element['object']->grade_item
->is_locked()) {
1756 $strparamobj = new stdClass();
1757 $strparamobj->itemname
= $element['object']->grade_item
->itemname
;
1758 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1760 $action = html_writer
::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1761 array('class' => 'action-icon'));
1763 } else if ($element['object']->is_locked()) {
1765 $tooltip = $strunlock;
1767 // Change the icon and add a tooltip showing the date
1768 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1770 $tooltip = get_string('locktimedate', 'grades',
1771 userdate($element['object']->get_locktime()));
1774 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:unlock', $this->context
)) {
1777 $url->param('action', 'unlock');
1778 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1782 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:lock', $this->context
)) {
1785 $url->param('action', 'lock');
1786 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1794 * Return calculation icon for given element
1796 * @param array $element An array representing an element in the grade_tree
1797 * @param object $gpr A grade_plugin_return object
1798 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1799 * @return string|action_menu_link
1801 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1802 global $CFG, $OUTPUT;
1803 if (!has_capability('moodle/grade:manage', $this->context
)) {
1804 return $returnactionmenulink ?
null : '';
1807 $type = $element['type'];
1808 $object = $element['object'];
1810 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1811 $strparams = $this->get_params_for_iconstr($element);
1812 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1814 $is_scale = $object->gradetype
== GRADE_TYPE_SCALE
;
1815 $is_value = $object->gradetype
== GRADE_TYPE_VALUE
;
1817 // show calculation icon only when calculation possible
1818 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1819 if ($object->is_calculated()) {
1822 $icon = 't/calc_off';
1825 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid
, 'id' => $object->id
));
1826 $url = $gpr->add_url_params($url);
1827 if ($returnactionmenulink) {
1828 return new action_menu_link_secondary($url,
1829 new pix_icon($icon, $streditcalculation),
1830 get_string('editcalculation', 'grades'));
1832 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
1837 return $returnactionmenulink ?
null : '';
1842 * Flat structure similar to grade tree.
1844 * @uses grade_structure
1845 * @package core_grades
1846 * @copyright 2009 Nicolas Connault
1847 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1849 class grade_seq
extends grade_structure
{
1852 * 1D array of elements
1857 * Constructor, retrieves and stores array of all grade_category and grade_item
1858 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1860 * @param int $courseid The course id
1861 * @param bool $category_grade_last category grade item is the last child
1862 * @param bool $nooutcomes Whether or not outcomes should be included
1864 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
1867 $this->courseid
= $courseid;
1868 $this->context
= context_course
::instance($courseid);
1870 // get course grade tree
1871 $top_element = grade_category
::fetch_course_tree($courseid, true);
1873 $this->elements
= grade_seq
::flatten($top_element, $category_grade_last, $nooutcomes);
1875 foreach ($this->elements
as $key=>$unused) {
1876 $this->items
[$this->elements
[$key]['object']->id
] =& $this->elements
[$key]['object'];
1881 * Static recursive helper - makes the grade_item for category the last children
1883 * @param array &$element The seed of the recursion
1884 * @param bool $category_grade_last category grade item is the last child
1885 * @param bool $nooutcomes Whether or not outcomes should be included
1889 public function flatten(&$element, $category_grade_last, $nooutcomes) {
1890 if (empty($element['children'])) {
1893 $children = array();
1895 foreach ($element['children'] as $sortorder=>$unused) {
1896 if ($nooutcomes and $element['type'] != 'category' and
1897 $element['children'][$sortorder]['object']->is_outcome_item()) {
1900 $children[] = $element['children'][$sortorder];
1902 unset($element['children']);
1904 if ($category_grade_last and count($children) > 1) {
1905 $cat_item = array_shift($children);
1906 array_push($children, $cat_item);
1910 foreach ($children as $child) {
1911 if ($child['type'] == 'category') {
1912 $result = $result + grade_seq
::flatten($child, $category_grade_last, $nooutcomes);
1914 $child['eid'] = 'i'.$child['object']->id
;
1915 $result[$child['object']->id
] = $child;
1923 * Parses the array in search of a given eid and returns a element object with
1924 * information about the element it has found.
1926 * @param int $eid Gradetree Element ID
1928 * @return object element
1930 public function locate_element($eid) {
1931 // it is a grade - construct a new object
1932 if (strpos($eid, 'n') === 0) {
1933 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1937 $itemid = $matches[1];
1938 $userid = $matches[2];
1940 //extra security check - the grade item must be in this tree
1941 if (!$item_el = $this->locate_element('ig'.$itemid)) {
1945 // $gradea->id may be null - means does not exist yet
1946 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1948 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
1949 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1951 } else if (strpos($eid, 'g') === 0) {
1952 $id = (int) substr($eid, 1);
1953 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
1956 //extra security check - the grade item must be in this tree
1957 if (!$item_el = $this->locate_element('ig'.$grade->itemid
)) {
1960 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
1961 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1964 // it is a category or item
1965 foreach ($this->elements
as $element) {
1966 if ($element['eid'] == $eid) {
1976 * This class represents a complete tree of categories, grade_items and final grades,
1977 * organises as an array primarily, but which can also be converted to other formats.
1978 * It has simple method calls with complex implementations, allowing for easy insertion,
1979 * deletion and moving of items and categories within the tree.
1981 * @uses grade_structure
1982 * @package core_grades
1983 * @copyright 2009 Nicolas Connault
1984 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1986 class grade_tree
extends grade_structure
{
1989 * The basic representation of the tree as a hierarchical, 3-tiered array.
1990 * @var object $top_element
1992 public $top_element;
1995 * 2D array of grade items and categories
1996 * @var array $levels
2007 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2008 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2010 * @param int $courseid The Course ID
2011 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2012 * @param bool $category_grade_last category grade item is the last child
2013 * @param array $collapsed array of collapsed categories
2014 * @param bool $nooutcomes Whether or not outcomes should be included
2016 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2017 $collapsed=null, $nooutcomes=false) {
2018 global $USER, $CFG, $COURSE, $DB;
2020 $this->courseid
= $courseid;
2021 $this->levels
= array();
2022 $this->context
= context_course
::instance($courseid);
2024 if (!empty($COURSE->id
) && $COURSE->id
== $this->courseid
) {
2027 $course = $DB->get_record('course', array('id' => $this->courseid
));
2029 $this->modinfo
= get_fast_modinfo($course);
2031 // get course grade tree
2032 $this->top_element
= grade_category
::fetch_course_tree($courseid, true);
2034 // collapse the categories if requested
2035 if (!empty($collapsed)) {
2036 grade_tree
::category_collapse($this->top_element
, $collapsed);
2039 // no otucomes if requested
2040 if (!empty($nooutcomes)) {
2041 grade_tree
::no_outcomes($this->top_element
);
2044 // move category item to last position in category
2045 if ($category_grade_last) {
2046 grade_tree
::category_grade_last($this->top_element
);
2050 // inject fake categories == fillers
2051 grade_tree
::inject_fillers($this->top_element
, 0);
2052 // add colspans to categories and fillers
2053 grade_tree
::inject_colspans($this->top_element
);
2056 grade_tree
::fill_levels($this->levels
, $this->top_element
, 0);
2061 * Static recursive helper - removes items from collapsed categories
2063 * @param array &$element The seed of the recursion
2064 * @param array $collapsed array of collapsed categories
2068 public function category_collapse(&$element, $collapsed) {
2069 if ($element['type'] != 'category') {
2072 if (empty($element['children']) or count($element['children']) < 2) {
2076 if (in_array($element['object']->id
, $collapsed['aggregatesonly'])) {
2077 $category_item = reset($element['children']); //keep only category item
2078 $element['children'] = array(key($element['children'])=>$category_item);
2081 if (in_array($element['object']->id
, $collapsed['gradesonly'])) { // Remove category item
2082 reset($element['children']);
2083 $first_key = key($element['children']);
2084 unset($element['children'][$first_key]);
2086 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2087 grade_tree
::category_collapse($element['children'][$sortorder], $collapsed);
2093 * Static recursive helper - removes all outcomes
2095 * @param array &$element The seed of the recursion
2099 public function no_outcomes(&$element) {
2100 if ($element['type'] != 'category') {
2103 foreach ($element['children'] as $sortorder=>$child) {
2104 if ($element['children'][$sortorder]['type'] == 'item'
2105 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2106 unset($element['children'][$sortorder]);
2108 } else if ($element['children'][$sortorder]['type'] == 'category') {
2109 grade_tree
::no_outcomes($element['children'][$sortorder]);
2115 * Static recursive helper - makes the grade_item for category the last children
2117 * @param array &$element The seed of the recursion
2121 public function category_grade_last(&$element) {
2122 if (empty($element['children'])) {
2125 if (count($element['children']) < 2) {
2128 $first_item = reset($element['children']);
2129 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2130 // the category item might have been already removed
2131 $order = key($element['children']);
2132 unset($element['children'][$order]);
2133 $element['children'][$order] =& $first_item;
2135 foreach ($element['children'] as $sortorder => $child) {
2136 grade_tree
::category_grade_last($element['children'][$sortorder]);
2141 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2143 * @param array &$levels The levels of the grade tree through which to recurse
2144 * @param array &$element The seed of the recursion
2145 * @param int $depth How deep are we?
2148 public function fill_levels(&$levels, &$element, $depth) {
2149 if (!array_key_exists($depth, $levels)) {
2150 $levels[$depth] = array();
2153 // prepare unique identifier
2154 if ($element['type'] == 'category') {
2155 $element['eid'] = 'cg'.$element['object']->id
;
2156 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2157 $element['eid'] = 'ig'.$element['object']->id
;
2158 $this->items
[$element['object']->id
] =& $element['object'];
2161 $levels[$depth][] =& $element;
2163 if (empty($element['children'])) {
2167 foreach ($element['children'] as $sortorder=>$child) {
2168 grade_tree
::fill_levels($levels, $element['children'][$sortorder], $depth);
2169 $element['children'][$sortorder]['prev'] = $prev;
2170 $element['children'][$sortorder]['next'] = 0;
2172 $element['children'][$prev]['next'] = $sortorder;
2179 * Static recursive helper - makes full tree (all leafes are at the same level)
2181 * @param array &$element The seed of the recursion
2182 * @param int $depth How deep are we?
2186 public function inject_fillers(&$element, $depth) {
2189 if (empty($element['children'])) {
2192 $chdepths = array();
2193 $chids = array_keys($element['children']);
2194 $last_child = end($chids);
2195 $first_child = reset($chids);
2197 foreach ($chids as $chid) {
2198 $chdepths[$chid] = grade_tree
::inject_fillers($element['children'][$chid], $depth);
2202 $maxdepth = reset($chdepths);
2203 foreach ($chdepths as $chid=>$chd) {
2204 if ($chd == $maxdepth) {
2207 for ($i=0; $i < $maxdepth-$chd; $i++
) {
2208 if ($chid == $first_child) {
2209 $type = 'fillerfirst';
2210 } else if ($chid == $last_child) {
2211 $type = 'fillerlast';
2215 $oldchild =& $element['children'][$chid];
2216 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2217 'eid'=>'', 'depth'=>$element['object']->depth
,
2218 'children'=>array($oldchild));
2226 * Static recursive helper - add colspan information into categories
2228 * @param array &$element The seed of the recursion
2232 public function inject_colspans(&$element) {
2233 if (empty($element['children'])) {
2237 foreach ($element['children'] as $key=>$child) {
2238 $count +
= grade_tree
::inject_colspans($element['children'][$key]);
2240 $element['colspan'] = $count;
2245 * Parses the array in search of a given eid and returns a element object with
2246 * information about the element it has found.
2247 * @param int $eid Gradetree Element ID
2248 * @return object element
2250 public function locate_element($eid) {
2251 // it is a grade - construct a new object
2252 if (strpos($eid, 'n') === 0) {
2253 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2257 $itemid = $matches[1];
2258 $userid = $matches[2];
2260 //extra security check - the grade item must be in this tree
2261 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2265 // $gradea->id may be null - means does not exist yet
2266 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2268 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2269 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2271 } else if (strpos($eid, 'g') === 0) {
2272 $id = (int) substr($eid, 1);
2273 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
2276 //extra security check - the grade item must be in this tree
2277 if (!$item_el = $this->locate_element('ig'.$grade->itemid
)) {
2280 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2281 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2284 // it is a category or item
2285 foreach ($this->levels
as $row) {
2286 foreach ($row as $element) {
2287 if ($element['type'] == 'filler') {
2290 if ($element['eid'] == $eid) {
2300 * Returns a well-formed XML representation of the grade-tree using recursion.
2302 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2303 * @param string $tabs The control character to use for tabs
2305 * @return string $xml
2307 public function exporttoxml($root=null, $tabs="\t") {
2310 if (is_null($root)) {
2311 $root = $this->top_element
;
2312 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2313 $xml .= "<gradetree>\n";
2317 $type = 'undefined';
2318 if (strpos($root['object']->table
, 'grade_categories') !== false) {
2320 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
2322 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
2326 $xml .= "$tabs<element type=\"$type\">\n";
2327 foreach ($root['object'] as $var => $value) {
2328 if (!is_object($value) && !is_array($value) && !empty($value)) {
2329 $xml .= "$tabs\t<$var>$value</$var>\n";
2333 if (!empty($root['children'])) {
2334 $xml .= "$tabs\t<children>\n";
2335 foreach ($root['children'] as $sortorder => $child) {
2336 $xml .= $this->exportToXML($child, $tabs."\t\t");
2338 $xml .= "$tabs\t</children>\n";
2341 $xml .= "$tabs</element>\n";
2344 $xml .= "</gradetree>";
2351 * Returns a JSON representation of the grade-tree using recursion.
2353 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2354 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2358 public function exporttojson($root=null, $tabs="\t") {
2361 if (is_null($root)) {
2362 $root = $this->top_element
;
2369 if (strpos($root['object']->table
, 'grade_categories') !== false) {
2370 $name = $root['object']->fullname
;
2372 $name = $root['object']->get_name();
2374 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
2375 $name = $root['object']->itemname
;
2376 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
2377 $name = $root['object']->itemname
;
2380 $json .= "$tabs {\n";
2381 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2382 $json .= "$tabs\t \"name\": \"$name\",\n";
2384 foreach ($root['object'] as $var => $value) {
2385 if (!is_object($value) && !is_array($value) && !empty($value)) {
2386 $json .= "$tabs\t \"$var\": \"$value\",\n";
2390 $json = substr($json, 0, strrpos($json, ','));
2392 if (!empty($root['children'])) {
2393 $json .= ",\n$tabs\t\"children\": [\n";
2394 foreach ($root['children'] as $sortorder => $child) {
2395 $json .= $this->exportToJSON($child, $tabs."\t\t");
2397 $json = substr($json, 0, strrpos($json, ','));
2398 $json .= "\n$tabs\t]\n";
2404 $json .= "\n$tabs},\n";
2411 * Returns the array of levels
2415 public function get_levels() {
2416 return $this->levels
;
2420 * Returns the array of grade items
2424 public function get_items() {
2425 return $this->items
;
2429 * Returns a specific Grade Item
2431 * @param int $itemid The ID of the grade_item object
2433 * @return grade_item
2435 public function get_item($itemid) {
2436 if (array_key_exists($itemid, $this->items
)) {
2437 return $this->items
[$itemid];
2445 * Local shortcut function for creating an edit/delete button for a grade_* object.
2446 * @param string $type 'edit' or 'delete'
2447 * @param int $courseid The Course ID
2448 * @param grade_* $object The grade_* object
2449 * @return string html
2451 function grade_button($type, $courseid, $object) {
2452 global $CFG, $OUTPUT;
2453 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2454 $objectidstring = $matches[1] . 'id';
2456 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2459 $strdelete = get_string('delete');
2460 $stredit = get_string('edit');
2462 if ($type == 'delete') {
2463 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id
, 'action' => 'delete', 'sesskey' => sesskey()));
2464 } else if ($type == 'edit') {
2465 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id
));
2468 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $
{'str'.$type}, '', array('class' => 'iconsmall')));
2473 * This method adds settings to the settings block for the grade system and its
2476 * @global moodle_page $PAGE
2478 function grade_extend_settings($plugininfo, $courseid) {
2481 $gradenode = $PAGE->settingsnav
->prepend(get_string('gradeadministration', 'grades'), null, navigation_node
::TYPE_CONTAINER
);
2483 $strings = array_shift($plugininfo);
2485 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
2486 foreach ($reports as $report) {
2487 $gradenode->add($report->string, $report->link
, navigation_node
::TYPE_SETTING
, null, $report->id
, new pix_icon('i/report', ''));
2491 if ($settings = grade_helper
::get_info_manage_settings($courseid)) {
2492 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node
::TYPE_CONTAINER
);
2493 foreach ($settings as $setting) {
2494 $settingsnode->add($setting->string, $setting->link
, navigation_node
::TYPE_SETTING
, null, $setting->id
, new pix_icon('i/settings', ''));
2498 if ($imports = grade_helper
::get_plugins_import($courseid)) {
2499 $importnode = $gradenode->add($strings['import'], null, navigation_node
::TYPE_CONTAINER
);
2500 foreach ($imports as $import) {
2501 $importnode->add($import->string, $import->link
, navigation_node
::TYPE_SETTING
, null, $import->id
, new pix_icon('i/import', ''));
2505 if ($exports = grade_helper
::get_plugins_export($courseid)) {
2506 $exportnode = $gradenode->add($strings['export'], null, navigation_node
::TYPE_CONTAINER
);
2507 foreach ($exports as $export) {
2508 $exportnode->add($export->string, $export->link
, navigation_node
::TYPE_SETTING
, null, $export->id
, new pix_icon('i/export', ''));
2512 if ($letters = grade_helper
::get_info_letters($courseid)) {
2513 $letters = array_shift($letters);
2514 $gradenode->add($strings['letter'], $letters->link
, navigation_node
::TYPE_SETTING
, null, $letters->id
, new pix_icon('i/settings', ''));
2517 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
2518 $outcomes = array_shift($outcomes);
2519 $gradenode->add($strings['outcome'], $outcomes->link
, navigation_node
::TYPE_SETTING
, null, $outcomes->id
, new pix_icon('i/outcomes', ''));
2522 if ($scales = grade_helper
::get_info_scales($courseid)) {
2523 $gradenode->add($strings['scale'], $scales->link
, navigation_node
::TYPE_SETTING
, null, $scales->id
, new pix_icon('i/scales', ''));
2526 if ($gradenode->contains_active_node()) {
2527 // If the gradenode is active include the settings base node (gradeadministration) in
2528 // the navbar, typcially this is ignored.
2529 $PAGE->navbar
->includesettingsbase
= true;
2531 // If we can get the course admin node make sure it is closed by default
2532 // as in this case the gradenode will be opened
2533 if ($coursenode = $PAGE->settingsnav
->get('courseadmin', navigation_node
::TYPE_COURSE
)){
2534 $coursenode->make_inactive();
2535 $coursenode->forceopen
= false;
2541 * Grade helper class
2543 * This class provides several helpful functions that work irrespective of any
2546 * @copyright 2010 Sam Hemelryk
2547 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2549 abstract class grade_helper
{
2551 * Cached manage settings info {@see get_info_settings}
2552 * @var grade_plugin_info|false
2554 protected static $managesetting = null;
2556 * Cached grade report plugins {@see get_plugins_reports}
2559 protected static $gradereports = null;
2561 * Cached grade report plugins preferences {@see get_info_scales}
2564 protected static $gradereportpreferences = null;
2566 * Cached scale info {@see get_info_scales}
2567 * @var grade_plugin_info|false
2569 protected static $scaleinfo = null;
2571 * Cached outcome info {@see get_info_outcomes}
2572 * @var grade_plugin_info|false
2574 protected static $outcomeinfo = null;
2576 * Cached leftter info {@see get_info_letters}
2577 * @var grade_plugin_info|false
2579 protected static $letterinfo = null;
2581 * Cached grade import plugins {@see get_plugins_import}
2584 protected static $importplugins = null;
2586 * Cached grade export plugins {@see get_plugins_export}
2589 protected static $exportplugins = null;
2591 * Cached grade plugin strings
2594 protected static $pluginstrings = null;
2596 * Cached grade aggregation strings
2599 protected static $aggregationstrings = null;
2602 * Gets strings commonly used by the describe plugins
2604 * report => get_string('view'),
2605 * scale => get_string('scales'),
2606 * outcome => get_string('outcomes', 'grades'),
2607 * letter => get_string('letters', 'grades'),
2608 * export => get_string('export', 'grades'),
2609 * import => get_string('import'),
2610 * preferences => get_string('mypreferences', 'grades'),
2611 * settings => get_string('settings')
2615 public static function get_plugin_strings() {
2616 if (self
::$pluginstrings === null) {
2617 self
::$pluginstrings = array(
2618 'report' => get_string('view'),
2619 'scale' => get_string('scales'),
2620 'outcome' => get_string('outcomes', 'grades'),
2621 'letter' => get_string('letters', 'grades'),
2622 'export' => get_string('export', 'grades'),
2623 'import' => get_string('import'),
2624 'settings' => get_string('edittree', 'grades')
2627 return self
::$pluginstrings;
2631 * Gets strings describing the available aggregation methods.
2635 public static function get_aggregation_strings() {
2636 if (self
::$aggregationstrings === null) {
2637 self
::$aggregationstrings = array(
2638 GRADE_AGGREGATE_MEAN
=> get_string('aggregatemean', 'grades'),
2639 GRADE_AGGREGATE_WEIGHTED_MEAN
=> get_string('aggregateweightedmean', 'grades'),
2640 GRADE_AGGREGATE_WEIGHTED_MEAN2
=> get_string('aggregateweightedmean2', 'grades'),
2641 GRADE_AGGREGATE_EXTRACREDIT_MEAN
=> get_string('aggregateextracreditmean', 'grades'),
2642 GRADE_AGGREGATE_MEDIAN
=> get_string('aggregatemedian', 'grades'),
2643 GRADE_AGGREGATE_MIN
=> get_string('aggregatemin', 'grades'),
2644 GRADE_AGGREGATE_MAX
=> get_string('aggregatemax', 'grades'),
2645 GRADE_AGGREGATE_MODE
=> get_string('aggregatemode', 'grades'),
2646 GRADE_AGGREGATE_SUM
=> get_string('aggregatesum', 'grades')
2649 return self
::$aggregationstrings;
2653 * Get grade_plugin_info object for managing settings if the user can
2655 * @param int $courseid
2656 * @return grade_plugin_info[]
2658 public static function get_info_manage_settings($courseid) {
2659 if (self
::$managesetting !== null) {
2660 return self
::$managesetting;
2662 $context = context_course
::instance($courseid);
2663 self
::$managesetting = array();
2664 if ($courseid != SITEID
&& has_capability('moodle/grade:manage', $context)) {
2665 self
::$managesetting['categoriesanditems'] = new grade_plugin_info('setup',
2666 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2667 get_string('categoriesanditems', 'grades'));
2668 self
::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2669 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2670 get_string('coursegradesettings', 'grades'));
2672 if (self
::$gradereportpreferences === null) {
2673 self
::get_plugins_reports($courseid);
2675 if (self
::$gradereportpreferences) {
2676 self
::$managesetting = array_merge(self
::$managesetting, self
::$gradereportpreferences);
2678 return self
::$managesetting;
2681 * Returns an array of plugin reports as grade_plugin_info objects
2683 * @param int $courseid
2686 public static function get_plugins_reports($courseid) {
2689 if (self
::$gradereports !== null) {
2690 return self
::$gradereports;
2692 $context = context_course
::instance($courseid);
2693 $gradereports = array();
2694 $gradepreferences = array();
2695 foreach (core_component
::get_plugin_list('gradereport') as $plugin => $plugindir) {
2696 //some reports make no sense if we're not within a course
2697 if ($courseid==$SITE->id
&& ($plugin=='grader' ||
$plugin=='user')) {
2701 // Remove ones we can't see
2702 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2706 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2707 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2708 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2710 // Add link to preferences tab if such a page exists
2711 if (file_exists($plugindir.'/preferences.php')) {
2712 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2713 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2714 get_string('mypreferences', 'grades') . ': ' . $pluginstr);
2717 if (count($gradereports) == 0) {
2718 $gradereports = false;
2719 $gradepreferences = false;
2720 } else if (count($gradepreferences) == 0) {
2721 $gradepreferences = false;
2722 asort($gradereports);
2724 asort($gradereports);
2725 asort($gradepreferences);
2727 self
::$gradereports = $gradereports;
2728 self
::$gradereportpreferences = $gradepreferences;
2729 return self
::$gradereports;
2733 * Get information on scales
2734 * @param int $courseid
2735 * @return grade_plugin_info
2737 public static function get_info_scales($courseid) {
2738 if (self
::$scaleinfo !== null) {
2739 return self
::$scaleinfo;
2741 if (has_capability('moodle/course:managescales', context_course
::instance($courseid))) {
2742 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2743 self
::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2745 self
::$scaleinfo = false;
2747 return self
::$scaleinfo;
2750 * Get information on outcomes
2751 * @param int $courseid
2752 * @return grade_plugin_info
2754 public static function get_info_outcomes($courseid) {
2757 if (self
::$outcomeinfo !== null) {
2758 return self
::$outcomeinfo;
2760 $context = context_course
::instance($courseid);
2761 $canmanage = has_capability('moodle/grade:manage', $context);
2762 $canupdate = has_capability('moodle/course:update', $context);
2763 if (!empty($CFG->enableoutcomes
) && ($canmanage ||
$canupdate)) {
2764 $outcomes = array();
2766 if ($courseid!=$SITE->id
) {
2767 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2768 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2770 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2771 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2772 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2773 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2775 if ($courseid!=$SITE->id
) {
2776 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2777 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2780 self
::$outcomeinfo = $outcomes;
2782 self
::$outcomeinfo = false;
2784 return self
::$outcomeinfo;
2787 * Get information on letters
2788 * @param int $courseid
2791 public static function get_info_letters($courseid) {
2793 if (self
::$letterinfo !== null) {
2794 return self
::$letterinfo;
2796 $context = context_course
::instance($courseid);
2797 $canmanage = has_capability('moodle/grade:manage', $context);
2798 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2799 if ($canmanage ||
$canmanageletters) {
2800 // Redirect to system context when report is accessed from admin settings MDL-31633
2801 if ($context->instanceid
== $SITE->id
) {
2802 $param = array('edit' => 1);
2804 $param = array('edit' => 1,'id' => $context->id
);
2806 self
::$letterinfo = array(
2807 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id
)), get_string('view')),
2808 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
2811 self
::$letterinfo = false;
2813 return self
::$letterinfo;
2816 * Get information import plugins
2817 * @param int $courseid
2820 public static function get_plugins_import($courseid) {
2823 if (self
::$importplugins !== null) {
2824 return self
::$importplugins;
2826 $importplugins = array();
2827 $context = context_course
::instance($courseid);
2829 if (has_capability('moodle/grade:import', $context)) {
2830 foreach (core_component
::get_plugin_list('gradeimport') as $plugin => $plugindir) {
2831 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2834 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2835 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2836 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2840 if ($CFG->gradepublishing
) {
2841 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2842 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2846 if (count($importplugins) > 0) {
2847 asort($importplugins);
2848 self
::$importplugins = $importplugins;
2850 self
::$importplugins = false;
2852 return self
::$importplugins;
2855 * Get information export plugins
2856 * @param int $courseid
2859 public static function get_plugins_export($courseid) {
2862 if (self
::$exportplugins !== null) {
2863 return self
::$exportplugins;
2865 $context = context_course
::instance($courseid);
2866 $exportplugins = array();
2867 if (has_capability('moodle/grade:export', $context)) {
2868 foreach (core_component
::get_plugin_list('gradeexport') as $plugin => $plugindir) {
2869 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2872 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
2873 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2874 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2877 if ($CFG->gradepublishing
) {
2878 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2879 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2882 if (count($exportplugins) > 0) {
2883 asort($exportplugins);
2884 self
::$exportplugins = $exportplugins;
2886 self
::$exportplugins = false;
2888 return self
::$exportplugins;
2892 * Returns the value of a field from a user record
2894 * @param stdClass $user object
2895 * @param stdClass $field object
2896 * @return string value of the field
2898 public static function get_user_field_value($user, $field) {
2899 if (!empty($field->customid
)) {
2900 $fieldname = 'customfield_' . $field->shortname
;
2901 if (!empty($user->{$fieldname}) ||
is_numeric($user->{$fieldname})) {
2902 $fieldvalue = $user->{$fieldname};
2904 $fieldvalue = $field->default;
2907 $fieldvalue = $user->{$field->shortname
};
2913 * Returns an array of user profile fields to be included in export
2915 * @param int $courseid
2916 * @param bool $includecustomfields
2917 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
2919 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
2922 // Gets the fields that have to be hidden
2923 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields
));
2924 $context = context_course
::instance($courseid);
2925 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
2926 if ($canseehiddenfields) {
2927 $hiddenfields = array();
2931 require_once($CFG->dirroot
.'/user/lib.php'); // Loads user_get_default_fields()
2932 require_once($CFG->dirroot
.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
2933 $userdefaultfields = user_get_default_fields();
2935 // Sets the list of profile fields
2936 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields
));
2937 if (!empty($userprofilefields)) {
2938 foreach ($userprofilefields as $field) {
2939 $field = trim($field);
2940 if (in_array($field, $hiddenfields) ||
!in_array($field, $userdefaultfields)) {
2943 $obj = new stdClass();
2945 $obj->shortname
= $field;
2946 $obj->fullname
= get_string($field);
2951 // Sets the list of custom profile fields
2952 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields
));
2953 if ($includecustomfields && !empty($customprofilefields)) {
2954 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
2955 $customfields = $DB->get_records_sql("SELECT f.*
2956 FROM {user_info_field} f
2957 JOIN {user_info_category} c ON f.categoryid=c.id
2958 WHERE f.shortname $wherefields
2959 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
2960 if (!is_array($customfields)) {
2964 foreach ($customfields as $field) {
2965 // Make sure we can display this custom field
2966 if (!in_array($field->shortname
, $customprofilefields)) {
2968 } else if (in_array($field->shortname
, $hiddenfields)) {
2970 } else if ($field->visible
!= PROFILE_VISIBLE_ALL
&& !$canseehiddenfields) {
2974 $obj = new stdClass();
2975 $obj->customid
= $field->id
;
2976 $obj->shortname
= $field->shortname
;
2977 $obj->fullname
= format_string($field->name
);
2978 $obj->datatype
= $field->datatype
;
2979 $obj->default = $field->defaultdata
;
2988 * This helper method gets a snapshot of all the weights for a course.
2989 * It is used as a quick method to see if any wieghts have been automatically adjusted.
2990 * @param int $courseid
2991 * @return array of itemid -> aggregationcoef2
2993 public static function fetch_all_natural_weights_for_course($courseid) {
2997 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
2998 foreach ($records as $record) {
2999 $result[$record->id
] = $record->aggregationcoef2
;