Merge branch 'MDL-72779' of https://github.com/paulholden/moodle
[moodle.git] / grade / lib.php
blob491d92e2a5c1eba0b8179931f4c90497cc1fc2c2
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.
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/>.
17 /**
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');
28 /**
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 {
37 /**
38 * The couse whose users we are interested in
40 protected $course;
42 /**
43 * An array of grade items or null if only user data was requested
45 protected $grade_items;
47 /**
48 * The group ID we are interested in. 0 means all groups.
50 protected $groupid;
52 /**
53 * A recordset of graded users
55 protected $users_rs;
57 /**
58 * A recordset of user grades (grade_grade instances)
60 protected $grades_rs;
62 /**
63 * Array used when moving to next user while iterating through the grades recordset
65 protected $gradestack;
67 /**
68 * The first field of the users table by which the array of users will be sorted
70 protected $sortfield1;
72 /**
73 * Should sortfield1 be ASC or DESC
75 protected $sortorder1;
77 /**
78 * The second field of the users table by which the array of users will be sorted
80 protected $sortfield2;
82 /**
83 * Should sortfield2 be ASC or DESC
85 protected $sortorder2;
87 /**
88 * Should users whose enrolment has been suspended be ignored?
90 protected $onlyactive = false;
92 /**
93 * Enable user custom fields
95 protected $allowusercustomfields = false;
97 /**
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();
104 * Constructor
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() {
134 global $CFG, $DB;
136 $this->close();
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;
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;
158 } else {
159 $groupsql = "";
160 $groupwheresql = "";
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";
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";
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";
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->customid}";
195 $params['cf'.$customfieldscount] = $field->customid;
196 $customfieldscount++;
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);
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();
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
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;
248 return true;
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
266 } else {
267 $user = $this->users_rs->current();
268 $this->users_rs->next();
271 // find grades of this user
272 $grade_records = array();
273 while (true) {
274 if (!$current = $this->_pop()) {
275 break; // no more grades
278 if (empty($current->userid)) {
279 break;
282 if ($current->userid != $user->id) {
283 // grade of the next user, we have all for this user
284 $this->_push($current);
285 break;
288 $grade_records[$current->itemid] = $current;
291 $grades = array();
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);
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);
311 $grades[$grade_item->id]->grade_item = $grade_item;
315 // Set user suspended status.
316 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
317 $result = new stdClass();
318 $result->user = $user;
319 $result->grades = $grades;
320 $result->feedbacks = $feedbacks;
321 return $result;
325 * Close the iterator, do not forget to call this function
327 public function close() {
328 if ($this->users_rs) {
329 $this->users_rs->close();
330 $this->users_rs = null;
332 if ($this->grades_rs) {
333 $this->grades_rs->close();
334 $this->grades_rs = null;
336 $this->gradestack = array();
340 * Should all enrolled users be exported or just those with an active enrolment?
342 * @param bool $onlyactive True to limit the export to users with an active enrolment
344 public function require_active_enrolment($onlyactive = true) {
345 if (!empty($this->users_rs)) {
346 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
348 $this->onlyactive = $onlyactive;
352 * Allow custom fields to be included
354 * @param bool $allow Whether to allow custom fields or not
355 * @return void
357 public function allow_user_custom_fields($allow = true) {
358 if ($allow) {
359 $this->allowusercustomfields = true;
360 } else {
361 $this->allowusercustomfields = false;
366 * Add a grade_grade instance to the grade stack
368 * @param grade_grade $grade Grade object
370 * @return void
372 private function _push($grade) {
373 array_push($this->gradestack, $grade);
378 * Remove a grade_grade instance from the grade stack
380 * @return grade_grade current grade object
382 private function _pop() {
383 global $DB;
384 if (empty($this->gradestack)) {
385 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
386 return null; // no grades present
389 $current = $this->grades_rs->current();
391 $this->grades_rs->next();
393 return $current;
394 } else {
395 return array_pop($this->gradestack);
401 * Print a selection popup form of the graded users in a course.
403 * @deprecated since 2.0
405 * @param int $course id of the course
406 * @param string $actionpage The page receiving the data from the popoup form
407 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
408 * @param int $groupid id of requested group, 0 means all
409 * @param int $includeall bool include all option
410 * @param bool $return If true, will return the HTML, otherwise, will print directly
411 * @return null
413 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
414 global $CFG, $USER, $OUTPUT;
415 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
418 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
419 global $USER, $CFG;
421 if (is_null($userid)) {
422 $userid = $USER->id;
424 $coursecontext = context_course::instance($course->id);
425 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
426 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
427 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
428 $menu = array(); // Will be a list of userid => user name
429 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
430 $gui = new graded_users_iterator($course, null, $groupid);
431 $gui->require_active_enrolment($showonlyactiveenrol);
432 $gui->init();
433 $label = get_string('selectauser', 'grades');
434 if ($includeall) {
435 $menu[0] = get_string('allusers', 'grades');
436 $label = get_string('selectalloroneuser', 'grades');
438 while ($userdata = $gui->next_user()) {
439 $user = $userdata->user;
440 $userfullname = fullname($user);
441 if ($user->suspendedenrolment) {
442 $menususpendedusers[$user->id] = $userfullname;
443 } else {
444 $menu[$user->id] = $userfullname;
447 $gui->close();
449 if ($includeall) {
450 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
453 if (!empty($menususpendedusers)) {
454 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
456 $gpr = new grade_plugin_return(array('type' => 'report', 'course' => $course, 'groupid' => $groupid));
457 $select = new single_select(
458 new moodle_url('/grade/report/'.$report.'/index.php', $gpr->get_options()),
459 'userid', $menu, $userid
461 $select->label = $label;
462 $select->formid = 'choosegradeuser';
463 return $select;
467 * Hide warning about changed grades during upgrade to 2.8.
469 * @param int $courseid The current course id.
471 function hide_natural_aggregation_upgrade_notice($courseid) {
472 unset_config('show_sumofgrades_upgrade_' . $courseid);
476 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
478 * @param int $courseid The current course id.
480 function grade_hide_min_max_grade_upgrade_notice($courseid) {
481 unset_config('show_min_max_grades_changed_' . $courseid);
485 * Use the grade min and max from the grade_grade.
487 * This is reserved for core use after an upgrade.
489 * @param int $courseid The current course id.
491 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
492 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
494 grade_force_full_regrading($courseid);
495 // Do this now, because it probably happened to late in the page load to be happen automatically.
496 grade_regrade_final_grades($courseid);
500 * Use the grade min and max from the grade_item.
502 * This is reserved for core use after an upgrade.
504 * @param int $courseid The current course id.
506 function grade_upgrade_use_min_max_from_grade_item($courseid) {
507 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
509 grade_force_full_regrading($courseid);
510 // Do this now, because it probably happened to late in the page load to be happen automatically.
511 grade_regrade_final_grades($courseid);
515 * Hide warning about changed grades during upgrade to 2.8.
517 * @param int $courseid The current course id.
519 function hide_aggregatesubcats_upgrade_notice($courseid) {
520 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
524 * Hide warning about changed grades due to bug fixes
526 * @param int $courseid The current course id.
528 function hide_gradebook_calculations_freeze_notice($courseid) {
529 unset_config('gradebook_calculations_freeze_' . $courseid);
533 * Print warning about changed grades during upgrade to 2.8.
535 * @param int $courseid The current course id.
536 * @param context $context The course context.
537 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
538 * @param boolean $return return as string
540 * @return nothing or string if $return true
542 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
543 global $CFG, $OUTPUT;
544 $html = '';
546 // Do not do anything if they cannot manage the grades of this course.
547 if (!has_capability('moodle/grade:manage', $context)) {
548 return $html;
551 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
552 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
553 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
554 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
556 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
557 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
559 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
560 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
562 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
564 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
565 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
567 // Hide the warning if the user told it to go away.
568 if ($hidenaturalwarning) {
569 hide_natural_aggregation_upgrade_notice($courseid);
571 // Hide the warning if the user told it to go away.
572 if ($hidesubcatswarning) {
573 hide_aggregatesubcats_upgrade_notice($courseid);
576 // Hide the min/max warning if the user told it to go away.
577 if ($hideminmaxwarning) {
578 grade_hide_min_max_grade_upgrade_notice($courseid);
579 $showminmaxwarning = false;
582 if ($useminmaxfromgradegrade) {
583 // Revert to the new behaviour, we now use the grade_grade for min/max.
584 grade_upgrade_use_min_max_from_grade_grade($courseid);
585 grade_hide_min_max_grade_upgrade_notice($courseid);
586 $showminmaxwarning = false;
588 } else if ($useminmaxfromgradeitem) {
589 // Apply the new logic, we now use the grade_item for min/max.
590 grade_upgrade_use_min_max_from_grade_item($courseid);
591 grade_hide_min_max_grade_upgrade_notice($courseid);
592 $showminmaxwarning = false;
596 if (!$hidenaturalwarning && $shownaturalwarning) {
597 $message = get_string('sumofgradesupgradedgrades', 'grades');
598 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
599 $urlparams = array( 'id' => $courseid,
600 'seensumofgradesupgradedgrades' => true,
601 'sesskey' => sesskey());
602 $goawayurl = new moodle_url($thispage, $urlparams);
603 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
604 $html .= $OUTPUT->notification($message, 'notifysuccess');
605 $html .= $goawaybutton;
608 if (!$hidesubcatswarning && $showsubcatswarning) {
609 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
610 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
611 $urlparams = array( 'id' => $courseid,
612 'seenaggregatesubcatsupgradedgrades' => true,
613 'sesskey' => sesskey());
614 $goawayurl = new moodle_url($thispage, $urlparams);
615 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
616 $html .= $OUTPUT->notification($message, 'notifysuccess');
617 $html .= $goawaybutton;
620 if ($showminmaxwarning) {
621 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
622 $urlparams = array( 'id' => $courseid,
623 'seenminmaxupgradedgrades' => true,
624 'sesskey' => sesskey());
626 $goawayurl = new moodle_url($thispage, $urlparams);
627 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
628 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
629 array('target' => '_blank'));
631 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
632 // Show the message that there were min/max issues that have been resolved.
633 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
635 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
636 $urlparams = array('id' => $courseid,
637 'useminmaxfromgradegrade' => true,
638 'sesskey' => sesskey());
639 $reverturl = new moodle_url($thispage, $urlparams);
640 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
642 $html .= $OUTPUT->notification($message);
643 $html .= $revertbutton . $hideminmaxbutton;
645 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
646 // Show the warning that there are min/max issues that have not be resolved.
647 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
649 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
650 $urlparams = array('id' => $courseid,
651 'useminmaxfromgradeitem' => true,
652 'sesskey' => sesskey());
653 $fixurl = new moodle_url($thispage, $urlparams);
654 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
656 $html .= $OUTPUT->notification($message);
657 $html .= $fixbutton . $hideminmaxbutton;
661 if ($gradebookcalculationsfreeze) {
662 if ($acceptgradebookchanges) {
663 // Accept potential changes in grades caused by extra credit bug MDL-49257.
664 hide_gradebook_calculations_freeze_notice($courseid);
665 $courseitem = grade_item::fetch_course_item($courseid);
666 $courseitem->force_regrading();
667 grade_regrade_final_grades($courseid);
669 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
670 } else {
671 // Show the warning that there may be extra credit weights problems.
672 $a = new stdClass();
673 $a->gradebookversion = $gradebookcalculationsfreeze;
674 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
675 $a->currentversion = $matches[1];
676 } else {
677 $a->currentversion = $CFG->release;
679 $a->url = get_docs_url('Gradebook_calculation_changes');
680 $message = get_string('gradebookcalculationswarning', 'grades', $a);
682 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
683 $urlparams = array('id' => $courseid,
684 'acceptgradebookchanges' => true,
685 'sesskey' => sesskey());
686 $fixurl = new moodle_url($thispage, $urlparams);
687 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
689 $html .= $OUTPUT->notification($message);
690 $html .= $fixbutton;
694 if (!empty($html)) {
695 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
698 if ($return) {
699 return $html;
700 } else {
701 echo $html;
706 * Print grading plugin selection popup form.
708 * @param array $plugin_info An array of plugins containing information for the selector
709 * @param boolean $return return as string
711 * @return nothing or string if $return true
713 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
714 global $CFG, $OUTPUT, $PAGE;
716 $menu = array();
717 $count = 0;
718 $active = '';
720 foreach ($plugin_info as $plugin_type => $plugins) {
721 if ($plugin_type == 'strings') {
722 continue;
725 $first_plugin = reset($plugins);
727 $sectionname = $plugin_info['strings'][$plugin_type];
728 $section = array();
730 foreach ($plugins as $plugin) {
731 $link = $plugin->link->out(false);
732 $section[$link] = $plugin->string;
733 $count++;
734 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
735 $active = $link;
739 if ($section) {
740 $menu[] = array($sectionname=>$section);
744 // finally print/return the popup form
745 if ($count > 1) {
746 $select = new url_select($menu, $active, null, 'choosepluginreport');
747 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
748 if ($return) {
749 return $OUTPUT->render($select);
750 } else {
751 echo $OUTPUT->render($select);
753 } else {
754 // only one option - no plugin selector needed
755 return '';
760 * Print grading plugin selection tab-based navigation.
762 * @param string $active_type type of plugin on current page - import, export, report or edit
763 * @param string $active_plugin active plugin type - grader, user, cvs, ...
764 * @param array $plugin_info Array of plugins
765 * @param boolean $return return as string
767 * @return nothing or string if $return true
769 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
770 global $CFG, $COURSE;
772 if (!isset($currenttab)) { //TODO: this is weird
773 $currenttab = '';
776 $tabs = array();
777 $top_row = array();
778 $bottom_row = array();
779 $inactive = array($active_plugin);
780 $activated = array($active_type);
782 $count = 0;
783 $active = '';
785 foreach ($plugin_info as $plugin_type => $plugins) {
786 if ($plugin_type == 'strings') {
787 continue;
790 // If $plugins is actually the definition of a child-less parent link:
791 if (!empty($plugins->id)) {
792 $string = $plugins->string;
793 if (!empty($plugin_info[$active_type]->parent)) {
794 $string = $plugin_info[$active_type]->parent->string;
797 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
798 continue;
801 $first_plugin = reset($plugins);
802 $url = $first_plugin->link;
804 if ($plugin_type == 'report') {
805 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
808 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
810 if ($active_type == $plugin_type) {
811 foreach ($plugins as $plugin) {
812 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
813 if ($plugin->id == $active_plugin) {
814 $inactive = array($plugin->id);
820 // Do not display rows that contain only one item, they are not helpful.
821 if (count($top_row) > 1) {
822 $tabs[] = $top_row;
824 if (count($bottom_row) > 1) {
825 $tabs[] = $bottom_row;
827 if (empty($tabs)) {
828 return;
831 $rv = html_writer::div(print_tabs($tabs, $active_plugin, $inactive, $activated, true), 'grade-navigation');
833 if ($return) {
834 return $rv;
835 } else {
836 echo $rv;
841 * grade_get_plugin_info
843 * @param int $courseid The course id
844 * @param string $active_type type of plugin on current page - import, export, report or edit
845 * @param string $active_plugin active plugin type - grader, user, cvs, ...
847 * @return array
849 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
850 global $CFG, $SITE;
852 $context = context_course::instance($courseid);
854 $plugin_info = array();
855 $count = 0;
856 $active = '';
857 $url_prefix = $CFG->wwwroot . '/grade/';
859 // Language strings
860 $plugin_info['strings'] = grade_helper::get_plugin_strings();
862 if ($reports = grade_helper::get_plugins_reports($courseid)) {
863 $plugin_info['report'] = $reports;
866 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
867 $plugin_info['settings'] = $settings;
870 if ($scale = grade_helper::get_info_scales($courseid)) {
871 $plugin_info['scale'] = array('view'=>$scale);
874 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
875 $plugin_info['outcome'] = $outcomes;
878 if ($letters = grade_helper::get_info_letters($courseid)) {
879 $plugin_info['letter'] = $letters;
882 if ($imports = grade_helper::get_plugins_import($courseid)) {
883 $plugin_info['import'] = $imports;
886 if ($exports = grade_helper::get_plugins_export($courseid)) {
887 $plugin_info['export'] = $exports;
890 // Let other plugins add plugins here so that we get extra tabs
891 // in the gradebook.
892 $callbacks = get_plugins_with_function('extend_gradebook_plugininfo', 'lib.php');
893 foreach ($callbacks as $plugins) {
894 foreach ($plugins as $pluginfunction) {
895 $plugin_info = $pluginfunction($plugin_info, $courseid);
899 foreach ($plugin_info as $plugin_type => $plugins) {
900 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
901 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
902 break;
904 foreach ($plugins as $plugin) {
905 if (is_a($plugin, 'grade_plugin_info')) {
906 if ($active_plugin == $plugin->id) {
907 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
913 return $plugin_info;
917 * A simple class containing info about grade plugins.
918 * Can be subclassed for special rules
920 * @package core_grades
921 * @copyright 2009 Nicolas Connault
922 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
924 class grade_plugin_info {
926 * A unique id for this plugin
928 * @var mixed
930 public $id;
932 * A URL to access this plugin
934 * @var mixed
936 public $link;
938 * The name of this plugin
940 * @var mixed
942 public $string;
944 * Another grade_plugin_info object, parent of the current one
946 * @var mixed
948 public $parent;
951 * Constructor
953 * @param int $id A unique id for this plugin
954 * @param string $link A URL to access this plugin
955 * @param string $string The name of this plugin
956 * @param object $parent Another grade_plugin_info object, parent of the current one
958 * @return void
960 public function __construct($id, $link, $string, $parent=null) {
961 $this->id = $id;
962 $this->link = $link;
963 $this->string = $string;
964 $this->parent = $parent;
969 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
970 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
971 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
972 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
973 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
975 * @param int $courseid Course id
976 * @param string $active_type The type of the current page (report, settings,
977 * import, export, scales, outcomes, letters)
978 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
979 * @param string $heading The heading of the page. Tries to guess if none is given
980 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
981 * @param string $bodytags Additional attributes that will be added to the <body> tag
982 * @param string $buttons Additional buttons to display on the page
983 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
984 * @param string $headerhelpidentifier The help string identifier if required.
985 * @param string $headerhelpcomponent The component for the help string.
986 * @param stdClass $user The user object for use with the user context header.
988 * @return string HTML code or nothing if $return == false
990 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
991 $heading = false, $return=false,
992 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null,
993 $user = null) {
994 global $CFG, $OUTPUT, $PAGE;
996 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
997 require_once($CFG->dirroot . '/course/lib.php');
998 if (course_modules_pending_deletion($courseid, true)) {
999 \core\notification::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
1000 \core\output\notification::NOTIFY_WARNING);
1003 if ($active_type === 'preferences') {
1004 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
1005 $active_type = 'settings';
1008 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
1010 // Determine the string of the active plugin
1011 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
1012 $stractive_type = $plugin_info['strings'][$active_type];
1014 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
1015 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
1016 } else {
1017 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
1020 if ($active_type == 'report') {
1021 $PAGE->set_pagelayout('report');
1022 } else {
1023 $PAGE->set_pagelayout('admin');
1025 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
1026 $PAGE->set_heading($title);
1027 if ($buttons instanceof single_button) {
1028 $buttons = $OUTPUT->render($buttons);
1030 $PAGE->set_button($buttons);
1031 if ($courseid != SITEID) {
1032 grade_extend_settings($plugin_info, $courseid);
1035 // Set the current report as active in the breadcrumbs.
1036 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
1037 $reportnav->make_active();
1040 $returnval = $OUTPUT->header();
1042 if (!$return) {
1043 echo $returnval;
1046 // Guess heading if not given explicitly
1047 if (!$heading) {
1048 $heading = $stractive_plugin;
1051 if ($shownavigation) {
1052 $navselector = null;
1053 if ($courseid != SITEID &&
1054 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
1055 // It's absolutely essential that this grade plugin selector is shown after the user header. Just ask Fred.
1056 $navselector = print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, true);
1057 if ($return) {
1058 $returnval .= $navselector;
1059 } else if (!isset($user)) {
1060 echo $navselector;
1064 $output = '';
1065 // Add a help dialogue box if provided.
1066 if (isset($headerhelpidentifier)) {
1067 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
1068 } else {
1069 if (isset($user)) {
1070 $output = $OUTPUT->context_header(
1071 array(
1072 'heading' => html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id,
1073 'course' => $courseid)), fullname($user)),
1074 'user' => $user,
1075 'usercontext' => context_user::instance($user->id)
1076 ), 2
1077 ) . $navselector;
1078 } else {
1079 $output = $OUTPUT->heading($heading);
1083 if ($return) {
1084 $returnval .= $output;
1085 } else {
1086 echo $output;
1089 if ($courseid != SITEID &&
1090 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
1091 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
1095 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
1096 context_course::instance($courseid),
1097 $PAGE->url,
1098 $return);
1100 if ($return) {
1101 return $returnval;
1106 * Utility class used for return tracking when using edit and other forms in grade plugins
1108 * @package core_grades
1109 * @copyright 2009 Nicolas Connault
1110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1112 class grade_plugin_return {
1114 * Type of grade plugin (e.g. 'edit', 'report')
1116 * @var string
1118 public $type;
1120 * Name of grade plugin (e.g. 'grader', 'overview')
1122 * @var string
1124 public $plugin;
1126 * Course id being viewed
1128 * @var int
1130 public $courseid;
1132 * Id of user whose information is being viewed/edited
1134 * @var int
1136 public $userid;
1138 * Id of group for which information is being viewed/edited
1140 * @var int
1142 public $groupid;
1144 * Current page # within output
1146 * @var int
1148 public $page;
1151 * Constructor
1153 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1155 public function __construct($params = []) {
1156 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1157 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1158 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1159 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1160 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1161 $this->page = optional_param('gpr_page', null, PARAM_INT);
1163 foreach ($params as $key => $value) {
1164 if (property_exists($this, $key)) {
1165 $this->$key = $value;
1168 // Allow course object rather than id to be used to specify course
1169 // - avoid unnecessary use of get_course.
1170 if (array_key_exists('course', $params)) {
1171 $course = $params['course'];
1172 $this->courseid = $course->id;
1173 } else {
1174 $course = null;
1176 // If group has been explicitly set in constructor parameters,
1177 // we should respect that.
1178 if (!array_key_exists('groupid', $params)) {
1179 // Otherwise, 'group' in request parameters is a request for a change.
1180 // In that case, or if we have no group at all, we should get groupid from
1181 // groups_get_course_group, which will do some housekeeping as well as
1182 // give us the correct value.
1183 $changegroup = optional_param('group', -1, PARAM_INT);
1184 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1185 if ($course === null) {
1186 $course = get_course($this->courseid);
1188 $this->groupid = groups_get_course_group($course, true);
1194 * Old syntax of class constructor. Deprecated in PHP7.
1196 * @deprecated since Moodle 3.1
1198 public function grade_plugin_return($params = null) {
1199 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1200 self::__construct($params);
1204 * Returns return parameters as options array suitable for buttons.
1205 * @return array options
1207 public function get_options() {
1208 if (empty($this->type)) {
1209 return array();
1212 $params = array();
1214 if (!empty($this->plugin)) {
1215 $params['plugin'] = $this->plugin;
1218 if (!empty($this->courseid)) {
1219 $params['id'] = $this->courseid;
1222 if (!empty($this->userid)) {
1223 $params['userid'] = $this->userid;
1226 if (!empty($this->groupid)) {
1227 $params['group'] = $this->groupid;
1230 if (!empty($this->page)) {
1231 $params['page'] = $this->page;
1234 return $params;
1238 * Returns return url
1240 * @param string $default default url when params not set
1241 * @param array $extras Extra URL parameters
1243 * @return string url
1245 public function get_return_url($default, $extras=null) {
1246 global $CFG;
1248 if (empty($this->type) or empty($this->plugin)) {
1249 return $default;
1252 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1253 $glue = '?';
1255 if (!empty($this->courseid)) {
1256 $url .= $glue.'id='.$this->courseid;
1257 $glue = '&amp;';
1260 if (!empty($this->userid)) {
1261 $url .= $glue.'userid='.$this->userid;
1262 $glue = '&amp;';
1265 if (!empty($this->groupid)) {
1266 $url .= $glue.'group='.$this->groupid;
1267 $glue = '&amp;';
1270 if (!empty($this->page)) {
1271 $url .= $glue.'page='.$this->page;
1272 $glue = '&amp;';
1275 if (!empty($extras)) {
1276 foreach ($extras as $key=>$value) {
1277 $url .= $glue.$key.'='.$value;
1278 $glue = '&amp;';
1282 return $url;
1286 * Returns string with hidden return tracking form elements.
1287 * @return string
1289 public function get_form_fields() {
1290 if (empty($this->type)) {
1291 return '';
1294 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1296 if (!empty($this->plugin)) {
1297 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1300 if (!empty($this->courseid)) {
1301 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1304 if (!empty($this->userid)) {
1305 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1308 if (!empty($this->groupid)) {
1309 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1312 if (!empty($this->page)) {
1313 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1315 return $result;
1319 * Add hidden elements into mform
1321 * @param object &$mform moodle form object
1323 * @return void
1325 public function add_mform_elements(&$mform) {
1326 if (empty($this->type)) {
1327 return;
1330 $mform->addElement('hidden', 'gpr_type', $this->type);
1331 $mform->setType('gpr_type', PARAM_SAFEDIR);
1333 if (!empty($this->plugin)) {
1334 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1335 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1338 if (!empty($this->courseid)) {
1339 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1340 $mform->setType('gpr_courseid', PARAM_INT);
1343 if (!empty($this->userid)) {
1344 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1345 $mform->setType('gpr_userid', PARAM_INT);
1348 if (!empty($this->groupid)) {
1349 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1350 $mform->setType('gpr_groupid', PARAM_INT);
1353 if (!empty($this->page)) {
1354 $mform->addElement('hidden', 'gpr_page', $this->page);
1355 $mform->setType('gpr_page', PARAM_INT);
1360 * Add return tracking params into url
1362 * @param moodle_url $url A URL
1364 * @return string $url with return tracking params
1366 public function add_url_params(moodle_url $url) {
1367 if (empty($this->type)) {
1368 return $url;
1371 $url->param('gpr_type', $this->type);
1373 if (!empty($this->plugin)) {
1374 $url->param('gpr_plugin', $this->plugin);
1377 if (!empty($this->courseid)) {
1378 $url->param('gpr_courseid' ,$this->courseid);
1381 if (!empty($this->userid)) {
1382 $url->param('gpr_userid', $this->userid);
1385 if (!empty($this->groupid)) {
1386 $url->param('gpr_groupid', $this->groupid);
1389 if (!empty($this->page)) {
1390 $url->param('gpr_page', $this->page);
1393 return $url;
1398 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1400 * @param string $path The path of the calling script (using __FILE__?)
1401 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1402 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1403 * an array of keys and values (e.g courseid => $courseid, itemid...)
1405 * @return string
1407 function grade_build_nav($path, $pagename=null, $id=null) {
1408 global $CFG, $COURSE, $PAGE;
1410 $strgrades = get_string('grades', 'grades');
1412 // Parse the path and build navlinks from its elements
1413 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1414 $path = substr($path, $dirroot_length);
1415 $path = str_replace('\\', '/', $path);
1417 $path_elements = explode('/', $path);
1419 $path_elements_count = count($path_elements);
1421 // First link is always 'grade'
1422 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1424 $link = null;
1425 $numberofelements = 3;
1427 // Prepare URL params string
1428 $linkparams = array();
1429 if (!is_null($id)) {
1430 if (is_array($id)) {
1431 foreach ($id as $idkey => $idvalue) {
1432 $linkparams[$idkey] = $idvalue;
1434 } else {
1435 $linkparams['id'] = $id;
1439 $navlink4 = null;
1441 // Remove file extensions from filenames
1442 foreach ($path_elements as $key => $filename) {
1443 $path_elements[$key] = str_replace('.php', '', $filename);
1446 // Second level links
1447 switch ($path_elements[1]) {
1448 case 'edit': // No link
1449 if ($path_elements[3] != 'index.php') {
1450 $numberofelements = 4;
1452 break;
1453 case 'import': // No link
1454 break;
1455 case 'export': // No link
1456 break;
1457 case 'report':
1458 // $id is required for this link. Do not print it if $id isn't given
1459 if (!is_null($id)) {
1460 $link = new moodle_url('/grade/report/index.php', $linkparams);
1463 if ($path_elements[2] == 'grader') {
1464 $numberofelements = 4;
1466 break;
1468 default:
1469 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1470 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1471 " as the second path element after 'grade'.");
1472 return false;
1474 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1476 // Third level links
1477 if (empty($pagename)) {
1478 $pagename = get_string($path_elements[2], 'grades');
1481 switch ($numberofelements) {
1482 case 3:
1483 $PAGE->navbar->add($pagename, $link);
1484 break;
1485 case 4:
1486 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1487 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1489 $PAGE->navbar->add($pagename);
1490 break;
1493 return '';
1497 * General structure representing grade items in course
1499 * @package core_grades
1500 * @copyright 2009 Nicolas Connault
1501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1503 class grade_structure {
1504 public $context;
1506 public $courseid;
1509 * Reference to modinfo for current course (for performance, to save
1510 * retrieving it from courseid every time). Not actually set except for
1511 * the grade_tree type.
1512 * @var course_modinfo
1514 public $modinfo;
1517 * 1D array of grade items only
1519 public $items;
1522 * Returns icon of element
1524 * @param array &$element An array representing an element in the grade_tree
1525 * @param bool $spacerifnone return spacer if no icon found
1527 * @return string icon or spacer
1529 public function get_element_icon(&$element, $spacerifnone=false) {
1530 global $CFG, $OUTPUT;
1531 require_once $CFG->libdir.'/filelib.php';
1533 $outputstr = '';
1535 // Object holding pix_icon information before instantiation.
1536 $icon = new stdClass();
1537 $icon->attributes = array(
1538 'class' => 'icon itemicon'
1540 $icon->component = 'moodle';
1542 $none = true;
1543 switch ($element['type']) {
1544 case 'item':
1545 case 'courseitem':
1546 case 'categoryitem':
1547 $none = false;
1549 $is_course = $element['object']->is_course_item();
1550 $is_category = $element['object']->is_category_item();
1551 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1552 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1553 $is_outcome = !empty($element['object']->outcomeid);
1555 if ($element['object']->is_calculated()) {
1556 $icon->pix = 'i/calc';
1557 $icon->title = s(get_string('calculatedgrade', 'grades'));
1559 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1560 if ($category = $element['object']->get_item_category()) {
1561 $aggrstrings = grade_helper::get_aggregation_strings();
1562 $stragg = $aggrstrings[$category->aggregation];
1564 $icon->pix = 'i/calc';
1565 $icon->title = s($stragg);
1567 switch ($category->aggregation) {
1568 case GRADE_AGGREGATE_MEAN:
1569 case GRADE_AGGREGATE_MEDIAN:
1570 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1571 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1572 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1573 $icon->pix = 'i/agg_mean';
1574 break;
1575 case GRADE_AGGREGATE_SUM:
1576 $icon->pix = 'i/agg_sum';
1577 break;
1581 } else if ($element['object']->itemtype == 'mod') {
1582 // Prevent outcomes displaying the same icon as the activity they are attached to.
1583 if ($is_outcome) {
1584 $icon->pix = 'i/outcomes';
1585 $icon->title = s(get_string('outcome', 'grades'));
1586 } else {
1587 $modinfo = get_fast_modinfo($element['object']->courseid);
1588 $module = $element['object']->itemmodule;
1589 $instanceid = $element['object']->iteminstance;
1590 if (isset($modinfo->instances[$module][$instanceid])) {
1591 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
1592 } else {
1593 $icon->pix = 'icon';
1594 $icon->component = $element['object']->itemmodule;
1596 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1598 } else if ($element['object']->itemtype == 'manual') {
1599 if ($element['object']->is_outcome_item()) {
1600 $icon->pix = 'i/outcomes';
1601 $icon->title = s(get_string('outcome', 'grades'));
1602 } else {
1603 $icon->pix = 'i/manual_item';
1604 $icon->title = s(get_string('manualitem', 'grades'));
1607 break;
1609 case 'category':
1610 $none = false;
1611 $icon->pix = 'i/folder';
1612 $icon->title = s(get_string('category', 'grades'));
1613 break;
1616 if ($none) {
1617 if ($spacerifnone) {
1618 $outputstr = $OUTPUT->spacer() . ' ';
1620 } else if (isset($icon->url)) {
1621 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
1622 } else {
1623 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1626 return $outputstr;
1630 * Returns name of element optionally with icon and link
1632 * @param array &$element An array representing an element in the grade_tree
1633 * @param bool $withlink Whether or not this header has a link
1634 * @param bool $icon Whether or not to display an icon with this header
1635 * @param bool $spacerifnone return spacer if no icon found
1636 * @param bool $withdescription Show description if defined by this item.
1637 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1638 * instead of "Category total" or "Course total"
1640 * @return string header
1642 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1643 $withdescription = false, $fulltotal = false) {
1644 $header = '';
1646 if ($icon) {
1647 $header .= $this->get_element_icon($element, $spacerifnone);
1650 $title = $element['object']->get_name($fulltotal);
1651 $titleunescaped = $element['object']->get_name($fulltotal, false);
1652 $header .= $title;
1654 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1655 $element['type'] != 'courseitem') {
1656 return $header;
1659 if ($withlink && $url = $this->get_activity_link($element)) {
1660 $a = new stdClass();
1661 $a->name = get_string('modulename', $element['object']->itemmodule);
1662 $a->title = $titleunescaped;
1663 $title = get_string('linktoactivity', 'grades', $a);
1665 $header = html_writer::link($url, $header, array('title' => $title, 'class' => 'gradeitemheader'));
1666 } else {
1667 $header = html_writer::span($header, 'gradeitemheader', array('title' => $titleunescaped, 'tabindex' => '0'));
1670 if ($withdescription) {
1671 $desc = $element['object']->get_description();
1672 if (!empty($desc)) {
1673 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1677 return $header;
1680 private function get_activity_link($element) {
1681 global $CFG;
1682 /** @var array static cache of the grade.php file existence flags */
1683 static $hasgradephp = array();
1685 $itemtype = $element['object']->itemtype;
1686 $itemmodule = $element['object']->itemmodule;
1687 $iteminstance = $element['object']->iteminstance;
1688 $itemnumber = $element['object']->itemnumber;
1690 // Links only for module items that have valid instance, module and are
1691 // called from grade_tree with valid modinfo
1692 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1693 return null;
1696 // Get $cm efficiently and with visibility information using modinfo
1697 $instances = $this->modinfo->get_instances();
1698 if (empty($instances[$itemmodule][$iteminstance])) {
1699 return null;
1701 $cm = $instances[$itemmodule][$iteminstance];
1703 // Do not add link if activity is not visible to the current user
1704 if (!$cm->uservisible) {
1705 return null;
1708 if (!array_key_exists($itemmodule, $hasgradephp)) {
1709 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1710 $hasgradephp[$itemmodule] = true;
1711 } else {
1712 $hasgradephp[$itemmodule] = false;
1716 // If module has grade.php, link to that, otherwise view.php
1717 if ($hasgradephp[$itemmodule]) {
1718 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1719 if (isset($element['userid'])) {
1720 $args['userid'] = $element['userid'];
1722 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1723 } else {
1724 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1729 * Returns URL of a page that is supposed to contain detailed grade analysis
1731 * At the moment, only activity modules are supported. The method generates link
1732 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1733 * gradeid and userid. If the grade.php does not exist, null is returned.
1735 * @return moodle_url|null URL or null if unable to construct it
1737 public function get_grade_analysis_url(grade_grade $grade) {
1738 global $CFG;
1739 /** @var array static cache of the grade.php file existence flags */
1740 static $hasgradephp = array();
1742 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1743 throw new coding_exception('Passed grade without the associated grade item');
1745 $item = $grade->grade_item;
1747 if (!$item->is_external_item()) {
1748 // at the moment, only activity modules are supported
1749 return null;
1751 if ($item->itemtype !== 'mod') {
1752 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1754 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1755 return null;
1758 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1759 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1760 $hasgradephp[$item->itemmodule] = true;
1761 } else {
1762 $hasgradephp[$item->itemmodule] = false;
1766 if (!$hasgradephp[$item->itemmodule]) {
1767 return null;
1770 $instances = $this->modinfo->get_instances();
1771 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1772 return null;
1774 $cm = $instances[$item->itemmodule][$item->iteminstance];
1775 if (!$cm->uservisible) {
1776 return null;
1779 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1780 'id' => $cm->id,
1781 'itemid' => $item->id,
1782 'itemnumber' => $item->itemnumber,
1783 'gradeid' => $grade->id,
1784 'userid' => $grade->userid,
1787 return $url;
1791 * Returns an action icon leading to the grade analysis page
1793 * @param grade_grade $grade
1794 * @return string
1796 public function get_grade_analysis_icon(grade_grade $grade) {
1797 global $OUTPUT;
1799 $url = $this->get_grade_analysis_url($grade);
1800 if (is_null($url)) {
1801 return '';
1804 $title = get_string('gradeanalysis', 'core_grades');
1805 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1806 ['title' => $title, 'aria-label' => $title]);
1810 * Returns the grade eid - the grade may not exist yet.
1812 * @param grade_grade $grade_grade A grade_grade object
1814 * @return string eid
1816 public function get_grade_eid($grade_grade) {
1817 if (empty($grade_grade->id)) {
1818 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1819 } else {
1820 return 'g'.$grade_grade->id;
1825 * Returns the grade_item eid
1826 * @param grade_item $grade_item A grade_item object
1827 * @return string eid
1829 public function get_item_eid($grade_item) {
1830 return 'ig'.$grade_item->id;
1834 * Given a grade_tree element, returns an array of parameters
1835 * used to build an icon for that element.
1837 * @param array $element An array representing an element in the grade_tree
1839 * @return array
1841 public function get_params_for_iconstr($element) {
1842 $strparams = new stdClass();
1843 $strparams->category = '';
1844 $strparams->itemname = '';
1845 $strparams->itemmodule = '';
1847 if (!method_exists($element['object'], 'get_name')) {
1848 return $strparams;
1851 $strparams->itemname = html_to_text($element['object']->get_name());
1853 // If element name is categorytotal, get the name of the parent category
1854 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1855 $parent = $element['object']->get_parent_category();
1856 $strparams->category = $parent->get_name() . ' ';
1857 } else {
1858 $strparams->category = '';
1861 $strparams->itemmodule = null;
1862 if (isset($element['object']->itemmodule)) {
1863 $strparams->itemmodule = $element['object']->itemmodule;
1865 return $strparams;
1869 * Return a reset icon for the given element.
1871 * @param array $element An array representing an element in the grade_tree
1872 * @param object $gpr A grade_plugin_return object
1873 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1874 * @return string|action_menu_link
1876 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1877 global $CFG, $OUTPUT;
1879 // Limit to category items set to use the natural weights aggregation method, and users
1880 // with the capability to manage grades.
1881 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1882 !has_capability('moodle/grade:manage', $this->context)) {
1883 return $returnactionmenulink ? null : '';
1886 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1887 $url = new moodle_url('/grade/edit/tree/action.php', array(
1888 'id' => $this->courseid,
1889 'action' => 'resetweights',
1890 'eid' => $element['eid'],
1891 'sesskey' => sesskey(),
1894 if ($returnactionmenulink) {
1895 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1896 get_string('resetweightsshort', 'grades'));
1897 } else {
1898 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1903 * Return edit icon for give element
1905 * @param array $element An array representing an element in the grade_tree
1906 * @param object $gpr A grade_plugin_return object
1907 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1908 * @return string|action_menu_link
1910 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1911 global $CFG, $OUTPUT;
1913 if (!has_capability('moodle/grade:manage', $this->context)) {
1914 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1915 // oki - let them override grade
1916 } else {
1917 return $returnactionmenulink ? null : '';
1921 static $strfeedback = null;
1922 static $streditgrade = null;
1923 if (is_null($streditgrade)) {
1924 $streditgrade = get_string('editgrade', 'grades');
1925 $strfeedback = get_string('feedback');
1928 $strparams = $this->get_params_for_iconstr($element);
1930 $object = $element['object'];
1932 switch ($element['type']) {
1933 case 'item':
1934 case 'categoryitem':
1935 case 'courseitem':
1936 $stredit = get_string('editverbose', 'grades', $strparams);
1937 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1938 $url = new moodle_url('/grade/edit/tree/item.php',
1939 array('courseid' => $this->courseid, 'id' => $object->id));
1940 } else {
1941 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1942 array('courseid' => $this->courseid, 'id' => $object->id));
1944 break;
1946 case 'category':
1947 $stredit = get_string('editverbose', 'grades', $strparams);
1948 $url = new moodle_url('/grade/edit/tree/category.php',
1949 array('courseid' => $this->courseid, 'id' => $object->id));
1950 break;
1952 case 'grade':
1953 $stredit = $streditgrade;
1954 if (empty($object->id)) {
1955 $url = new moodle_url('/grade/edit/tree/grade.php',
1956 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1957 } else {
1958 $url = new moodle_url('/grade/edit/tree/grade.php',
1959 array('courseid' => $this->courseid, 'id' => $object->id));
1961 if (!empty($object->feedback)) {
1962 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1964 break;
1966 default:
1967 $url = null;
1970 if ($url) {
1971 if ($returnactionmenulink) {
1972 return new action_menu_link_secondary($gpr->add_url_params($url),
1973 new pix_icon('t/edit', $stredit),
1974 get_string('editsettings'));
1975 } else {
1976 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1979 } else {
1980 return $returnactionmenulink ? null : '';
1985 * Return hiding icon for give element
1987 * @param array $element An array representing an element in the grade_tree
1988 * @param object $gpr A grade_plugin_return object
1989 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1990 * @return string|action_menu_link
1992 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1993 global $CFG, $OUTPUT;
1995 if (!$element['object']->can_control_visibility()) {
1996 return $returnactionmenulink ? null : '';
1999 if (!has_capability('moodle/grade:manage', $this->context) and
2000 !has_capability('moodle/grade:hide', $this->context)) {
2001 return $returnactionmenulink ? null : '';
2004 $strparams = $this->get_params_for_iconstr($element);
2005 $strshow = get_string('showverbose', 'grades', $strparams);
2006 $strhide = get_string('hideverbose', 'grades', $strparams);
2008 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2009 $url = $gpr->add_url_params($url);
2011 if ($element['object']->is_hidden()) {
2012 $type = 'show';
2013 $tooltip = $strshow;
2015 // Change the icon and add a tooltip showing the date
2016 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
2017 $type = 'hiddenuntil';
2018 $tooltip = get_string('hiddenuntildate', 'grades',
2019 userdate($element['object']->get_hidden()));
2022 $url->param('action', 'show');
2024 if ($returnactionmenulink) {
2025 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2026 } else {
2027 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2030 } else {
2031 $url->param('action', 'hide');
2032 if ($returnactionmenulink) {
2033 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2034 } else {
2035 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2039 return $hideicon;
2043 * Return locking icon for given element
2045 * @param array $element An array representing an element in the grade_tree
2046 * @param object $gpr A grade_plugin_return object
2048 * @return string
2050 public function get_locking_icon($element, $gpr) {
2051 global $CFG, $OUTPUT;
2053 $strparams = $this->get_params_for_iconstr($element);
2054 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2055 $strlock = get_string('lockverbose', 'grades', $strparams);
2057 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2058 $url = $gpr->add_url_params($url);
2060 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2061 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
2062 $strparamobj = new stdClass();
2063 $strparamobj->itemname = $element['object']->grade_item->itemname;
2064 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2066 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2067 array('class' => 'action-icon'));
2069 } else if ($element['object']->is_locked()) {
2070 $type = 'unlock';
2071 $tooltip = $strunlock;
2073 // Change the icon and add a tooltip showing the date
2074 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
2075 $type = 'locktime';
2076 $tooltip = get_string('locktimedate', 'grades',
2077 userdate($element['object']->get_locktime()));
2080 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
2081 $action = '';
2082 } else {
2083 $url->param('action', 'unlock');
2084 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
2087 } else {
2088 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
2089 $action = '';
2090 } else {
2091 $url->param('action', 'lock');
2092 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
2096 return $action;
2100 * Return calculation icon for given element
2102 * @param array $element An array representing an element in the grade_tree
2103 * @param object $gpr A grade_plugin_return object
2104 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2105 * @return string|action_menu_link
2107 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
2108 global $CFG, $OUTPUT;
2109 if (!has_capability('moodle/grade:manage', $this->context)) {
2110 return $returnactionmenulink ? null : '';
2113 $type = $element['type'];
2114 $object = $element['object'];
2116 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
2117 $strparams = $this->get_params_for_iconstr($element);
2118 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2120 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2121 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2123 // show calculation icon only when calculation possible
2124 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2125 if ($object->is_calculated()) {
2126 $icon = 't/calc';
2127 } else {
2128 $icon = 't/calc_off';
2131 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2132 $url = $gpr->add_url_params($url);
2133 if ($returnactionmenulink) {
2134 return new action_menu_link_secondary($url,
2135 new pix_icon($icon, $streditcalculation),
2136 get_string('editcalculation', 'grades'));
2137 } else {
2138 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2143 return $returnactionmenulink ? null : '';
2148 * Flat structure similar to grade tree.
2150 * @uses grade_structure
2151 * @package core_grades
2152 * @copyright 2009 Nicolas Connault
2153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2155 class grade_seq extends grade_structure {
2158 * 1D array of elements
2160 public $elements;
2163 * Constructor, retrieves and stores array of all grade_category and grade_item
2164 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2166 * @param int $courseid The course id
2167 * @param bool $category_grade_last category grade item is the last child
2168 * @param bool $nooutcomes Whether or not outcomes should be included
2170 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2171 global $USER, $CFG;
2173 $this->courseid = $courseid;
2174 $this->context = context_course::instance($courseid);
2176 // get course grade tree
2177 $top_element = grade_category::fetch_course_tree($courseid, true);
2179 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2181 foreach ($this->elements as $key=>$unused) {
2182 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2187 * Old syntax of class constructor. Deprecated in PHP7.
2189 * @deprecated since Moodle 3.1
2191 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2192 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2193 self::__construct($courseid, $category_grade_last, $nooutcomes);
2197 * Static recursive helper - makes the grade_item for category the last children
2199 * @param array &$element The seed of the recursion
2200 * @param bool $category_grade_last category grade item is the last child
2201 * @param bool $nooutcomes Whether or not outcomes should be included
2203 * @return array
2205 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2206 if (empty($element['children'])) {
2207 return array();
2209 $children = array();
2211 foreach ($element['children'] as $sortorder=>$unused) {
2212 if ($nooutcomes and $element['type'] != 'category' and
2213 $element['children'][$sortorder]['object']->is_outcome_item()) {
2214 continue;
2216 $children[] = $element['children'][$sortorder];
2218 unset($element['children']);
2220 if ($category_grade_last and count($children) > 1 and
2222 $children[0]['type'] === 'courseitem' or
2223 $children[0]['type'] === 'categoryitem'
2226 $cat_item = array_shift($children);
2227 array_push($children, $cat_item);
2230 $result = array();
2231 foreach ($children as $child) {
2232 if ($child['type'] == 'category') {
2233 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2234 } else {
2235 $child['eid'] = 'i'.$child['object']->id;
2236 $result[$child['object']->id] = $child;
2240 return $result;
2244 * Parses the array in search of a given eid and returns a element object with
2245 * information about the element it has found.
2247 * @param int $eid Gradetree Element ID
2249 * @return object element
2251 public function locate_element($eid) {
2252 // it is a grade - construct a new object
2253 if (strpos($eid, 'n') === 0) {
2254 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2255 return null;
2258 $itemid = $matches[1];
2259 $userid = $matches[2];
2261 //extra security check - the grade item must be in this tree
2262 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2263 return null;
2266 // $gradea->id may be null - means does not exist yet
2267 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2269 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2270 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2272 } else if (strpos($eid, 'g') === 0) {
2273 $id = (int) substr($eid, 1);
2274 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2275 return null;
2277 //extra security check - the grade item must be in this tree
2278 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2279 return null;
2281 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2282 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2285 // it is a category or item
2286 foreach ($this->elements as $element) {
2287 if ($element['eid'] == $eid) {
2288 return $element;
2292 return null;
2297 * This class represents a complete tree of categories, grade_items and final grades,
2298 * organises as an array primarily, but which can also be converted to other formats.
2299 * It has simple method calls with complex implementations, allowing for easy insertion,
2300 * deletion and moving of items and categories within the tree.
2302 * @uses grade_structure
2303 * @package core_grades
2304 * @copyright 2009 Nicolas Connault
2305 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2307 class grade_tree extends grade_structure {
2310 * The basic representation of the tree as a hierarchical, 3-tiered array.
2311 * @var object $top_element
2313 public $top_element;
2316 * 2D array of grade items and categories
2317 * @var array $levels
2319 public $levels;
2322 * Grade items
2323 * @var array $items
2325 public $items;
2328 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2329 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2331 * @param int $courseid The Course ID
2332 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2333 * @param bool $category_grade_last category grade item is the last child
2334 * @param array $collapsed array of collapsed categories
2335 * @param bool $nooutcomes Whether or not outcomes should be included
2337 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2338 $collapsed=null, $nooutcomes=false) {
2339 global $USER, $CFG, $COURSE, $DB;
2341 $this->courseid = $courseid;
2342 $this->levels = array();
2343 $this->context = context_course::instance($courseid);
2345 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2346 $course = $COURSE;
2347 } else {
2348 $course = $DB->get_record('course', array('id' => $this->courseid));
2350 $this->modinfo = get_fast_modinfo($course);
2352 // get course grade tree
2353 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2355 // collapse the categories if requested
2356 if (!empty($collapsed)) {
2357 grade_tree::category_collapse($this->top_element, $collapsed);
2360 // no otucomes if requested
2361 if (!empty($nooutcomes)) {
2362 grade_tree::no_outcomes($this->top_element);
2365 // move category item to last position in category
2366 if ($category_grade_last) {
2367 grade_tree::category_grade_last($this->top_element);
2370 if ($fillers) {
2371 // inject fake categories == fillers
2372 grade_tree::inject_fillers($this->top_element, 0);
2373 // add colspans to categories and fillers
2374 grade_tree::inject_colspans($this->top_element);
2377 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2382 * Old syntax of class constructor. Deprecated in PHP7.
2384 * @deprecated since Moodle 3.1
2386 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2387 $collapsed=null, $nooutcomes=false) {
2388 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2389 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2393 * Static recursive helper - removes items from collapsed categories
2395 * @param array &$element The seed of the recursion
2396 * @param array $collapsed array of collapsed categories
2398 * @return void
2400 public function category_collapse(&$element, $collapsed) {
2401 if ($element['type'] != 'category') {
2402 return;
2404 if (empty($element['children']) or count($element['children']) < 2) {
2405 return;
2408 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2409 $category_item = reset($element['children']); //keep only category item
2410 $element['children'] = array(key($element['children'])=>$category_item);
2412 } else {
2413 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2414 reset($element['children']);
2415 $first_key = key($element['children']);
2416 unset($element['children'][$first_key]);
2418 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2419 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2425 * Static recursive helper - removes all outcomes
2427 * @param array &$element The seed of the recursion
2429 * @return void
2431 public function no_outcomes(&$element) {
2432 if ($element['type'] != 'category') {
2433 return;
2435 foreach ($element['children'] as $sortorder=>$child) {
2436 if ($element['children'][$sortorder]['type'] == 'item'
2437 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2438 unset($element['children'][$sortorder]);
2440 } else if ($element['children'][$sortorder]['type'] == 'category') {
2441 grade_tree::no_outcomes($element['children'][$sortorder]);
2447 * Static recursive helper - makes the grade_item for category the last children
2449 * @param array &$element The seed of the recursion
2451 * @return void
2453 public function category_grade_last(&$element) {
2454 if (empty($element['children'])) {
2455 return;
2457 if (count($element['children']) < 2) {
2458 return;
2460 $first_item = reset($element['children']);
2461 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2462 // the category item might have been already removed
2463 $order = key($element['children']);
2464 unset($element['children'][$order]);
2465 $element['children'][$order] =& $first_item;
2467 foreach ($element['children'] as $sortorder => $child) {
2468 grade_tree::category_grade_last($element['children'][$sortorder]);
2473 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2475 * @param array &$levels The levels of the grade tree through which to recurse
2476 * @param array &$element The seed of the recursion
2477 * @param int $depth How deep are we?
2478 * @return void
2480 public function fill_levels(&$levels, &$element, $depth) {
2481 if (!array_key_exists($depth, $levels)) {
2482 $levels[$depth] = array();
2485 // prepare unique identifier
2486 if ($element['type'] == 'category') {
2487 $element['eid'] = 'cg'.$element['object']->id;
2488 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2489 $element['eid'] = 'ig'.$element['object']->id;
2490 $this->items[$element['object']->id] =& $element['object'];
2493 $levels[$depth][] =& $element;
2494 $depth++;
2495 if (empty($element['children'])) {
2496 return;
2498 $prev = 0;
2499 foreach ($element['children'] as $sortorder=>$child) {
2500 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2501 $element['children'][$sortorder]['prev'] = $prev;
2502 $element['children'][$sortorder]['next'] = 0;
2503 if ($prev) {
2504 $element['children'][$prev]['next'] = $sortorder;
2506 $prev = $sortorder;
2511 * Determines whether the grade tree item can be displayed.
2512 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2513 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2514 * can be output.
2516 * @param array $element The grade category element.
2517 * @return bool True if the grade tree item can be displayed. False, otherwise.
2519 public static function can_output_item($element) {
2520 $canoutput = true;
2522 if ($element['type'] === 'category') {
2523 $object = $element['object'];
2524 $category = grade_category::fetch(array('id' => $object->id));
2525 // Category has total, we can output this.
2526 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2527 return true;
2530 // Category has no total and has no children, no need to output this.
2531 if (empty($element['children'])) {
2532 return false;
2535 $canoutput = false;
2536 // Loop over children and make sure at least one child can be output.
2537 foreach ($element['children'] as $child) {
2538 $canoutput = self::can_output_item($child);
2539 if ($canoutput) {
2540 break;
2545 return $canoutput;
2549 * Static recursive helper - makes full tree (all leafes are at the same level)
2551 * @param array &$element The seed of the recursion
2552 * @param int $depth How deep are we?
2554 * @return int
2556 public function inject_fillers(&$element, $depth) {
2557 $depth++;
2559 if (empty($element['children'])) {
2560 return $depth;
2562 $chdepths = array();
2563 $chids = array_keys($element['children']);
2564 $last_child = end($chids);
2565 $first_child = reset($chids);
2567 foreach ($chids as $chid) {
2568 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2570 arsort($chdepths);
2572 $maxdepth = reset($chdepths);
2573 foreach ($chdepths as $chid=>$chd) {
2574 if ($chd == $maxdepth) {
2575 continue;
2577 if (!self::can_output_item($element['children'][$chid])) {
2578 continue;
2580 for ($i=0; $i < $maxdepth-$chd; $i++) {
2581 if ($chid == $first_child) {
2582 $type = 'fillerfirst';
2583 } else if ($chid == $last_child) {
2584 $type = 'fillerlast';
2585 } else {
2586 $type = 'filler';
2588 $oldchild =& $element['children'][$chid];
2589 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2590 'eid'=>'', 'depth'=>$element['object']->depth,
2591 'children'=>array($oldchild));
2595 return $maxdepth;
2599 * Static recursive helper - add colspan information into categories
2601 * @param array &$element The seed of the recursion
2603 * @return int
2605 public function inject_colspans(&$element) {
2606 if (empty($element['children'])) {
2607 return 1;
2609 $count = 0;
2610 foreach ($element['children'] as $key=>$child) {
2611 if (!self::can_output_item($child)) {
2612 continue;
2614 $count += grade_tree::inject_colspans($element['children'][$key]);
2616 $element['colspan'] = $count;
2617 return $count;
2621 * Parses the array in search of a given eid and returns a element object with
2622 * information about the element it has found.
2623 * @param int $eid Gradetree Element ID
2624 * @return object element
2626 public function locate_element($eid) {
2627 // it is a grade - construct a new object
2628 if (strpos($eid, 'n') === 0) {
2629 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2630 return null;
2633 $itemid = $matches[1];
2634 $userid = $matches[2];
2636 //extra security check - the grade item must be in this tree
2637 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2638 return null;
2641 // $gradea->id may be null - means does not exist yet
2642 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2644 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2645 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2647 } else if (strpos($eid, 'g') === 0) {
2648 $id = (int) substr($eid, 1);
2649 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2650 return null;
2652 //extra security check - the grade item must be in this tree
2653 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2654 return null;
2656 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2657 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2660 // it is a category or item
2661 foreach ($this->levels as $row) {
2662 foreach ($row as $element) {
2663 if ($element['type'] == 'filler') {
2664 continue;
2666 if ($element['eid'] == $eid) {
2667 return $element;
2672 return null;
2676 * Returns a well-formed XML representation of the grade-tree using recursion.
2678 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2679 * @param string $tabs The control character to use for tabs
2681 * @return string $xml
2683 public function exporttoxml($root=null, $tabs="\t") {
2684 $xml = null;
2685 $first = false;
2686 if (is_null($root)) {
2687 $root = $this->top_element;
2688 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2689 $xml .= "<gradetree>\n";
2690 $first = true;
2693 $type = 'undefined';
2694 if (strpos($root['object']->table, 'grade_categories') !== false) {
2695 $type = 'category';
2696 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2697 $type = 'item';
2698 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2699 $type = 'outcome';
2702 $xml .= "$tabs<element type=\"$type\">\n";
2703 foreach ($root['object'] as $var => $value) {
2704 if (!is_object($value) && !is_array($value) && !empty($value)) {
2705 $xml .= "$tabs\t<$var>$value</$var>\n";
2709 if (!empty($root['children'])) {
2710 $xml .= "$tabs\t<children>\n";
2711 foreach ($root['children'] as $sortorder => $child) {
2712 $xml .= $this->exportToXML($child, $tabs."\t\t");
2714 $xml .= "$tabs\t</children>\n";
2717 $xml .= "$tabs</element>\n";
2719 if ($first) {
2720 $xml .= "</gradetree>";
2723 return $xml;
2727 * Returns a JSON representation of the grade-tree using recursion.
2729 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2730 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2732 * @return string
2734 public function exporttojson($root=null, $tabs="\t") {
2735 $json = null;
2736 $first = false;
2737 if (is_null($root)) {
2738 $root = $this->top_element;
2739 $first = true;
2742 $name = '';
2745 if (strpos($root['object']->table, 'grade_categories') !== false) {
2746 $name = $root['object']->fullname;
2747 if ($name == '?') {
2748 $name = $root['object']->get_name();
2750 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2751 $name = $root['object']->itemname;
2752 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2753 $name = $root['object']->itemname;
2756 $json .= "$tabs {\n";
2757 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2758 $json .= "$tabs\t \"name\": \"$name\",\n";
2760 foreach ($root['object'] as $var => $value) {
2761 if (!is_object($value) && !is_array($value) && !empty($value)) {
2762 $json .= "$tabs\t \"$var\": \"$value\",\n";
2766 $json = substr($json, 0, strrpos($json, ','));
2768 if (!empty($root['children'])) {
2769 $json .= ",\n$tabs\t\"children\": [\n";
2770 foreach ($root['children'] as $sortorder => $child) {
2771 $json .= $this->exportToJSON($child, $tabs."\t\t");
2773 $json = substr($json, 0, strrpos($json, ','));
2774 $json .= "\n$tabs\t]\n";
2777 if ($first) {
2778 $json .= "\n}";
2779 } else {
2780 $json .= "\n$tabs},\n";
2783 return $json;
2787 * Returns the array of levels
2789 * @return array
2791 public function get_levels() {
2792 return $this->levels;
2796 * Returns the array of grade items
2798 * @return array
2800 public function get_items() {
2801 return $this->items;
2805 * Returns a specific Grade Item
2807 * @param int $itemid The ID of the grade_item object
2809 * @return grade_item
2811 public function get_item($itemid) {
2812 if (array_key_exists($itemid, $this->items)) {
2813 return $this->items[$itemid];
2814 } else {
2815 return false;
2821 * Local shortcut function for creating an edit/delete button for a grade_* object.
2822 * @param string $type 'edit' or 'delete'
2823 * @param int $courseid The Course ID
2824 * @param grade_* $object The grade_* object
2825 * @return string html
2827 function grade_button($type, $courseid, $object) {
2828 global $CFG, $OUTPUT;
2829 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2830 $objectidstring = $matches[1] . 'id';
2831 } else {
2832 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2835 $strdelete = get_string('delete');
2836 $stredit = get_string('edit');
2838 if ($type == 'delete') {
2839 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2840 } else if ($type == 'edit') {
2841 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2844 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2849 * This method adds settings to the settings block for the grade system and its
2850 * plugins
2852 * @global moodle_page $PAGE
2854 function grade_extend_settings($plugininfo, $courseid) {
2855 global $PAGE;
2857 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2859 $strings = array_shift($plugininfo);
2861 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2862 foreach ($reports as $report) {
2863 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2867 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2868 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2869 foreach ($settings as $setting) {
2870 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2874 if ($imports = grade_helper::get_plugins_import($courseid)) {
2875 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2876 foreach ($imports as $import) {
2877 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2881 if ($exports = grade_helper::get_plugins_export($courseid)) {
2882 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2883 foreach ($exports as $export) {
2884 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2888 if ($letters = grade_helper::get_info_letters($courseid)) {
2889 $letters = array_shift($letters);
2890 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2893 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2894 $outcomes = array_shift($outcomes);
2895 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2898 if ($scales = grade_helper::get_info_scales($courseid)) {
2899 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2902 if ($gradenode->contains_active_node()) {
2903 // If the gradenode is active include the settings base node (gradeadministration) in
2904 // the navbar, typcially this is ignored.
2905 $PAGE->navbar->includesettingsbase = true;
2907 // If we can get the course admin node make sure it is closed by default
2908 // as in this case the gradenode will be opened
2909 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2910 $coursenode->make_inactive();
2911 $coursenode->forceopen = false;
2917 * Grade helper class
2919 * This class provides several helpful functions that work irrespective of any
2920 * current state.
2922 * @copyright 2010 Sam Hemelryk
2923 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2925 abstract class grade_helper {
2927 * Cached manage settings info {@see get_info_settings}
2928 * @var grade_plugin_info|false
2930 protected static $managesetting = null;
2932 * Cached grade report plugins {@see get_plugins_reports}
2933 * @var array|false
2935 protected static $gradereports = null;
2937 * Cached grade report plugins preferences {@see get_info_scales}
2938 * @var array|false
2940 protected static $gradereportpreferences = null;
2942 * Cached scale info {@see get_info_scales}
2943 * @var grade_plugin_info|false
2945 protected static $scaleinfo = null;
2947 * Cached outcome info {@see get_info_outcomes}
2948 * @var grade_plugin_info|false
2950 protected static $outcomeinfo = null;
2952 * Cached leftter info {@see get_info_letters}
2953 * @var grade_plugin_info|false
2955 protected static $letterinfo = null;
2957 * Cached grade import plugins {@see get_plugins_import}
2958 * @var array|false
2960 protected static $importplugins = null;
2962 * Cached grade export plugins {@see get_plugins_export}
2963 * @var array|false
2965 protected static $exportplugins = null;
2967 * Cached grade plugin strings
2968 * @var array
2970 protected static $pluginstrings = null;
2972 * Cached grade aggregation strings
2973 * @var array
2975 protected static $aggregationstrings = null;
2978 * Gets strings commonly used by the describe plugins
2980 * report => get_string('view'),
2981 * scale => get_string('scales'),
2982 * outcome => get_string('outcomes', 'grades'),
2983 * letter => get_string('letters', 'grades'),
2984 * export => get_string('export', 'grades'),
2985 * import => get_string('import'),
2986 * settings => get_string('settings')
2988 * @return array
2990 public static function get_plugin_strings() {
2991 if (self::$pluginstrings === null) {
2992 self::$pluginstrings = array(
2993 'report' => get_string('view'),
2994 'scale' => get_string('scales'),
2995 'outcome' => get_string('outcomes', 'grades'),
2996 'letter' => get_string('letters', 'grades'),
2997 'export' => get_string('export', 'grades'),
2998 'import' => get_string('import'),
2999 'settings' => get_string('edittree', 'grades')
3002 return self::$pluginstrings;
3006 * Gets strings describing the available aggregation methods.
3008 * @return array
3010 public static function get_aggregation_strings() {
3011 if (self::$aggregationstrings === null) {
3012 self::$aggregationstrings = array(
3013 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
3014 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
3015 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
3016 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
3017 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
3018 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
3019 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
3020 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
3021 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
3024 return self::$aggregationstrings;
3028 * Get grade_plugin_info object for managing settings if the user can
3030 * @param int $courseid
3031 * @return grade_plugin_info[]
3033 public static function get_info_manage_settings($courseid) {
3034 if (self::$managesetting !== null) {
3035 return self::$managesetting;
3037 $context = context_course::instance($courseid);
3038 self::$managesetting = array();
3039 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
3040 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
3041 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
3042 get_string('gradebooksetup', 'grades'));
3043 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3044 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3045 get_string('coursegradesettings', 'grades'));
3047 if (self::$gradereportpreferences === null) {
3048 self::get_plugins_reports($courseid);
3050 if (self::$gradereportpreferences) {
3051 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
3053 return self::$managesetting;
3056 * Returns an array of plugin reports as grade_plugin_info objects
3058 * @param int $courseid
3059 * @return array
3061 public static function get_plugins_reports($courseid) {
3062 global $SITE;
3064 if (self::$gradereports !== null) {
3065 return self::$gradereports;
3067 $context = context_course::instance($courseid);
3068 $gradereports = array();
3069 $gradepreferences = array();
3070 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
3071 //some reports make no sense if we're not within a course
3072 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
3073 continue;
3076 // Remove ones we can't see
3077 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3078 continue;
3081 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3082 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3083 'moodle/grade:edit'), $context)) {
3084 continue;
3087 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
3088 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3089 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3091 // Add link to preferences tab if such a page exists
3092 if (file_exists($plugindir.'/preferences.php')) {
3093 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
3094 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
3095 get_string('preferences', 'grades') . ': ' . $pluginstr);
3098 if (count($gradereports) == 0) {
3099 $gradereports = false;
3100 $gradepreferences = false;
3101 } else if (count($gradepreferences) == 0) {
3102 $gradepreferences = false;
3103 asort($gradereports);
3104 } else {
3105 asort($gradereports);
3106 asort($gradepreferences);
3108 self::$gradereports = $gradereports;
3109 self::$gradereportpreferences = $gradepreferences;
3110 return self::$gradereports;
3114 * Get information on scales
3115 * @param int $courseid
3116 * @return grade_plugin_info
3118 public static function get_info_scales($courseid) {
3119 if (self::$scaleinfo !== null) {
3120 return self::$scaleinfo;
3122 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
3123 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3124 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3125 } else {
3126 self::$scaleinfo = false;
3128 return self::$scaleinfo;
3131 * Get information on outcomes
3132 * @param int $courseid
3133 * @return grade_plugin_info
3135 public static function get_info_outcomes($courseid) {
3136 global $CFG, $SITE;
3138 if (self::$outcomeinfo !== null) {
3139 return self::$outcomeinfo;
3141 $context = context_course::instance($courseid);
3142 $canmanage = has_capability('moodle/grade:manage', $context);
3143 $canupdate = has_capability('moodle/course:update', $context);
3144 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3145 $outcomes = array();
3146 if ($canupdate) {
3147 if ($courseid!=$SITE->id) {
3148 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3149 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3151 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3152 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3153 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3154 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3155 } else {
3156 if ($courseid!=$SITE->id) {
3157 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3158 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3161 self::$outcomeinfo = $outcomes;
3162 } else {
3163 self::$outcomeinfo = false;
3165 return self::$outcomeinfo;
3168 * Get information on letters
3169 * @param int $courseid
3170 * @return array
3172 public static function get_info_letters($courseid) {
3173 global $SITE;
3174 if (self::$letterinfo !== null) {
3175 return self::$letterinfo;
3177 $context = context_course::instance($courseid);
3178 $canmanage = has_capability('moodle/grade:manage', $context);
3179 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3180 if ($canmanage || $canmanageletters) {
3181 // Redirect to system context when report is accessed from admin settings MDL-31633
3182 if ($context->instanceid == $SITE->id) {
3183 $param = array('edit' => 1);
3184 } else {
3185 $param = array('edit' => 1,'id' => $context->id);
3187 self::$letterinfo = array(
3188 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3189 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3191 } else {
3192 self::$letterinfo = false;
3194 return self::$letterinfo;
3197 * Get information import plugins
3198 * @param int $courseid
3199 * @return array
3201 public static function get_plugins_import($courseid) {
3202 global $CFG;
3204 if (self::$importplugins !== null) {
3205 return self::$importplugins;
3207 $importplugins = array();
3208 $context = context_course::instance($courseid);
3210 if (has_capability('moodle/grade:import', $context)) {
3211 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3212 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3213 continue;
3215 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3216 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3217 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3220 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3221 // XML is the only grade import plugin that has publishing feature.
3222 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3223 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3224 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3228 if (count($importplugins) > 0) {
3229 asort($importplugins);
3230 self::$importplugins = $importplugins;
3231 } else {
3232 self::$importplugins = false;
3234 return self::$importplugins;
3237 * Get information export plugins
3238 * @param int $courseid
3239 * @return array
3241 public static function get_plugins_export($courseid) {
3242 global $CFG;
3244 if (self::$exportplugins !== null) {
3245 return self::$exportplugins;
3247 $context = context_course::instance($courseid);
3248 $exportplugins = array();
3249 $canpublishgrades = 0;
3250 if (has_capability('moodle/grade:export', $context)) {
3251 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3252 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3253 continue;
3255 // All the grade export plugins has grade publishing capabilities.
3256 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3257 $canpublishgrades++;
3260 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3261 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3262 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3265 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3266 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3267 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3268 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3271 if (count($exportplugins) > 0) {
3272 asort($exportplugins);
3273 self::$exportplugins = $exportplugins;
3274 } else {
3275 self::$exportplugins = false;
3277 return self::$exportplugins;
3281 * Returns the value of a field from a user record
3283 * @param stdClass $user object
3284 * @param stdClass $field object
3285 * @return string value of the field
3287 public static function get_user_field_value($user, $field) {
3288 if (!empty($field->customid)) {
3289 $fieldname = 'customfield_' . $field->customid;
3290 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3291 $fieldvalue = $user->{$fieldname};
3292 } else {
3293 $fieldvalue = $field->default;
3295 } else {
3296 $fieldvalue = $user->{$field->shortname};
3298 return $fieldvalue;
3302 * Returns an array of user profile fields to be included in export
3304 * @param int $courseid
3305 * @param bool $includecustomfields
3306 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3308 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3309 global $CFG, $DB;
3311 // Gets the fields that have to be hidden
3312 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3313 $context = context_course::instance($courseid);
3314 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3315 if ($canseehiddenfields) {
3316 $hiddenfields = array();
3319 $fields = array();
3320 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3321 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3322 $userdefaultfields = user_get_default_fields();
3324 // Sets the list of profile fields
3325 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3326 if (!empty($userprofilefields)) {
3327 foreach ($userprofilefields as $field) {
3328 $field = trim($field);
3329 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3330 continue;
3332 $obj = new stdClass();
3333 $obj->customid = 0;
3334 $obj->shortname = $field;
3335 $obj->fullname = get_string($field);
3336 $fields[] = $obj;
3340 // Sets the list of custom profile fields
3341 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3342 if ($includecustomfields && !empty($customprofilefields)) {
3343 $customfields = profile_get_user_fields_with_data(0);
3345 foreach ($customfields as $fieldobj) {
3346 $field = (object)$fieldobj->get_field_config_for_external();
3347 // Make sure we can display this custom field
3348 if (!in_array($field->shortname, $customprofilefields)) {
3349 continue;
3350 } else if (in_array($field->shortname, $hiddenfields)) {
3351 continue;
3352 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3353 continue;
3356 $obj = new stdClass();
3357 $obj->customid = $field->id;
3358 $obj->shortname = $field->shortname;
3359 $obj->fullname = format_string($field->name);
3360 $obj->datatype = $field->datatype;
3361 $obj->default = $field->defaultdata;
3362 $fields[] = $obj;
3366 return $fields;
3370 * This helper method gets a snapshot of all the weights for a course.
3371 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3372 * @param int $courseid
3373 * @return array of itemid -> aggregationcoef2
3375 public static function fetch_all_natural_weights_for_course($courseid) {
3376 global $DB;
3377 $result = array();
3379 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3380 foreach ($records as $record) {
3381 $result[$record->id] = $record->aggregationcoef2;
3383 return $result;