2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir
. '/gradelib.php');
26 require_once($CFG->dirroot
. '/grade/export/lib.php');
28 use \core_grades\output\action_bar
;
29 use \core_grades\output\general_action_bar
;
32 * This class iterates over all users that are graded in a course.
33 * Returns detailed info about users and their grades.
35 * @author Petr Skoda <skodak@moodle.org>
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38 class graded_users_iterator
{
41 * The couse whose users we are interested in
46 * An array of grade items or null if only user data was requested
48 protected $grade_items;
51 * The group ID we are interested in. 0 means all groups.
56 * A recordset of graded users
61 * A recordset of user grades (grade_grade instances)
66 * Array used when moving to next user while iterating through the grades recordset
68 protected $gradestack;
71 * The first field of the users table by which the array of users will be sorted
73 protected $sortfield1;
76 * Should sortfield1 be ASC or DESC
78 protected $sortorder1;
81 * The second field of the users table by which the array of users will be sorted
83 protected $sortfield2;
86 * Should sortfield2 be ASC or DESC
88 protected $sortorder2;
91 * Should users whose enrolment has been suspended be ignored?
93 protected $onlyactive = false;
96 * Enable user custom fields
98 protected $allowusercustomfields = false;
101 * List of suspended users in course. This includes users whose enrolment status is suspended
102 * or enrolment has expired or not started.
104 protected $suspendedusers = array();
109 * @param object $course A course object
110 * @param array $grade_items array of grade items, if not specified only user info returned
111 * @param int $groupid iterate only group users if present
112 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
113 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
114 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
115 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
117 public function __construct($course, $grade_items=null, $groupid=0,
118 $sortfield1='lastname', $sortorder1='ASC',
119 $sortfield2='firstname', $sortorder2='ASC') {
120 $this->course
= $course;
121 $this->grade_items
= $grade_items;
122 $this->groupid
= $groupid;
123 $this->sortfield1
= $sortfield1;
124 $this->sortorder1
= $sortorder1;
125 $this->sortfield2
= $sortfield2;
126 $this->sortorder2
= $sortorder2;
128 $this->gradestack
= array();
132 * Initialise the iterator
134 * @return boolean success
136 public function init() {
141 export_verify_grades($this->course
->id
);
142 $course_item = grade_item
::fetch_course_item($this->course
->id
);
143 if ($course_item->needsupdate
) {
144 // Can not calculate all final grades - sorry.
148 $coursecontext = context_course
::instance($this->course
->id
);
150 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'relatedctx');
151 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles
), SQL_PARAMS_NAMED
, 'grbr');
152 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive
);
154 $params = array_merge($params, $enrolledparams, $relatedctxparams);
156 if ($this->groupid
) {
157 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
158 $groupwheresql = "AND gm.groupid = :groupid";
159 // $params contents: gradebookroles
160 $params['groupid'] = $this->groupid
;
166 if (empty($this->sortfield1
)) {
167 // We must do some sorting even if not specified.
168 $ofields = ", u.id AS usrt";
172 $ofields = ", u.$this->sortfield1 AS usrt1";
173 $order = "usrt1 $this->sortorder1";
174 if (!empty($this->sortfield2
)) {
175 $ofields .= ", u.$this->sortfield2 AS usrt2";
176 $order .= ", usrt2 $this->sortorder2";
178 if ($this->sortfield1
!= 'id' and $this->sortfield2
!= 'id') {
179 // User order MUST be the same in both queries,
180 // must include the only unique user->id if not already present.
181 $ofields .= ", u.id AS usrt";
182 $order .= ", usrt ASC";
187 $customfieldssql = '';
188 if ($this->allowusercustomfields
&& !empty($CFG->grade_export_customprofilefields
)) {
189 $customfieldscount = 0;
190 $customfieldsarray = grade_helper
::get_user_profile_fields($this->course
->id
, $this->allowusercustomfields
);
191 foreach ($customfieldsarray as $field) {
192 if (!empty($field->customid
)) {
193 $customfieldssql .= "
194 LEFT JOIN (SELECT * FROM {user_info_data}
195 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
196 ON u.id = cf$customfieldscount.userid";
197 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->customid}";
198 $params['cf'.$customfieldscount] = $field->customid
;
199 $customfieldscount++
;
204 $users_sql = "SELECT $userfields $ofields
206 JOIN ($enrolledsql) je ON je.id = u.id
207 $groupsql $customfieldssql
209 SELECT DISTINCT ra.userid
210 FROM {role_assignments} ra
211 WHERE ra.roleid $gradebookroles_sql
212 AND ra.contextid $relatedctxsql
213 ) rainner ON rainner.userid = u.id
217 $this->users_rs
= $DB->get_recordset_sql($users_sql, $params);
219 if (!$this->onlyactive
) {
220 $context = context_course
::instance($this->course
->id
);
221 $this->suspendedusers
= get_suspended_userids($context);
223 $this->suspendedusers
= array();
226 if (!empty($this->grade_items
)) {
227 $itemids = array_keys($this->grade_items
);
228 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED
, 'items');
229 $params = array_merge($params, $grades_params);
231 $grades_sql = "SELECT g.* $ofields
232 FROM {grade_grades} g
233 JOIN {user} u ON g.userid = u.id
234 JOIN ($enrolledsql) je ON je.id = u.id
237 SELECT DISTINCT ra.userid
238 FROM {role_assignments} ra
239 WHERE ra.roleid $gradebookroles_sql
240 AND ra.contextid $relatedctxsql
241 ) rainner ON rainner.userid = u.id
243 AND g.itemid $itemidsql
245 ORDER BY $order, g.itemid ASC";
246 $this->grades_rs
= $DB->get_recordset_sql($grades_sql, $params);
248 $this->grades_rs
= false;
255 * Returns information about the next user
256 * @return mixed array of user info, all grades and feedback or null when no more users found
258 public function next_user() {
259 if (!$this->users_rs
) {
260 return false; // no users present
263 if (!$this->users_rs
->valid()) {
264 if ($current = $this->_pop()) {
265 // this is not good - user or grades updated between the two reads above :-(
268 return false; // no more users
270 $user = $this->users_rs
->current();
271 $this->users_rs
->next();
274 // find grades of this user
275 $grade_records = array();
277 if (!$current = $this->_pop()) {
278 break; // no more grades
281 if (empty($current->userid
)) {
285 if ($current->userid
!= $user->id
) {
286 // grade of the next user, we have all for this user
287 $this->_push($current);
291 $grade_records[$current->itemid
] = $current;
295 $feedbacks = array();
297 if (!empty($this->grade_items
)) {
298 foreach ($this->grade_items
as $grade_item) {
299 if (!isset($feedbacks[$grade_item->id
])) {
300 $feedbacks[$grade_item->id
] = new stdClass();
302 if (array_key_exists($grade_item->id
, $grade_records)) {
303 $feedbacks[$grade_item->id
]->feedback
= $grade_records[$grade_item->id
]->feedback
;
304 $feedbacks[$grade_item->id
]->feedbackformat
= $grade_records[$grade_item->id
]->feedbackformat
;
305 unset($grade_records[$grade_item->id
]->feedback
);
306 unset($grade_records[$grade_item->id
]->feedbackformat
);
307 $grades[$grade_item->id
] = new grade_grade($grade_records[$grade_item->id
], false);
309 $feedbacks[$grade_item->id
]->feedback
= '';
310 $feedbacks[$grade_item->id
]->feedbackformat
= FORMAT_MOODLE
;
311 $grades[$grade_item->id
] =
312 new grade_grade(array('userid'=>$user->id
, 'itemid'=>$grade_item->id
), false);
314 $grades[$grade_item->id
]->grade_item
= $grade_item;
318 // Set user suspended status.
319 $user->suspendedenrolment
= isset($this->suspendedusers
[$user->id
]);
320 $result = new stdClass();
321 $result->user
= $user;
322 $result->grades
= $grades;
323 $result->feedbacks
= $feedbacks;
328 * Close the iterator, do not forget to call this function
330 public function close() {
331 if ($this->users_rs
) {
332 $this->users_rs
->close();
333 $this->users_rs
= null;
335 if ($this->grades_rs
) {
336 $this->grades_rs
->close();
337 $this->grades_rs
= null;
339 $this->gradestack
= array();
343 * Should all enrolled users be exported or just those with an active enrolment?
345 * @param bool $onlyactive True to limit the export to users with an active enrolment
347 public function require_active_enrolment($onlyactive = true) {
348 if (!empty($this->users_rs
)) {
349 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER
);
351 $this->onlyactive
= $onlyactive;
355 * Allow custom fields to be included
357 * @param bool $allow Whether to allow custom fields or not
360 public function allow_user_custom_fields($allow = true) {
362 $this->allowusercustomfields
= true;
364 $this->allowusercustomfields
= false;
369 * Add a grade_grade instance to the grade stack
371 * @param grade_grade $grade Grade object
375 private function _push($grade) {
376 array_push($this->gradestack
, $grade);
381 * Remove a grade_grade instance from the grade stack
383 * @return grade_grade current grade object
385 private function _pop() {
387 if (empty($this->gradestack
)) {
388 if (empty($this->grades_rs
) ||
!$this->grades_rs
->valid()) {
389 return null; // no grades present
392 $current = $this->grades_rs
->current();
394 $this->grades_rs
->next();
398 return array_pop($this->gradestack
);
404 * Print a selection popup form of the graded users in a course.
406 * @deprecated since 2.0
408 * @param int $course id of the course
409 * @param string $actionpage The page receiving the data from the popoup form
410 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
411 * @param int $groupid id of requested group, 0 means all
412 * @param int $includeall bool include all option
413 * @param bool $return If true, will return the HTML, otherwise, will print directly
416 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
417 global $CFG, $USER, $OUTPUT;
418 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
421 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
424 if (is_null($userid)) {
427 $coursecontext = context_course
::instance($course->id
);
428 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol
);
429 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
430 $showonlyactiveenrol = $showonlyactiveenrol ||
!has_capability('moodle/course:viewsuspendedusers', $coursecontext);
431 $menu = array(); // Will be a list of userid => user name
432 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
433 $gui = new graded_users_iterator($course, null, $groupid);
434 $gui->require_active_enrolment($showonlyactiveenrol);
436 $label = get_string('selectauser', 'grades');
438 $menu[0] = get_string('allusers', 'grades');
439 $label = get_string('selectalloroneuser', 'grades');
441 while ($userdata = $gui->next_user()) {
442 $user = $userdata->user
;
443 $userfullname = fullname($user);
444 if ($user->suspendedenrolment
) {
445 $menususpendedusers[$user->id
] = $userfullname;
447 $menu[$user->id
] = $userfullname;
453 $menu[0] .= " (" . (count($menu) +
count($menususpendedusers) - 1) . ")";
456 if (!empty($menususpendedusers)) {
457 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
459 $gpr = new grade_plugin_return(array('type' => 'report', 'course' => $course, 'groupid' => $groupid));
460 $select = new single_select(
461 new moodle_url('/grade/report/'.$report.'/index.php', $gpr->get_options()),
462 'userid', $menu, $userid
464 $select->label
= $label;
465 $select->formid
= 'choosegradeuser';
470 * Hide warning about changed grades during upgrade to 2.8.
472 * @param int $courseid The current course id.
474 function hide_natural_aggregation_upgrade_notice($courseid) {
475 unset_config('show_sumofgrades_upgrade_' . $courseid);
479 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
481 * @param int $courseid The current course id.
483 function grade_hide_min_max_grade_upgrade_notice($courseid) {
484 unset_config('show_min_max_grades_changed_' . $courseid);
488 * Use the grade min and max from the grade_grade.
490 * This is reserved for core use after an upgrade.
492 * @param int $courseid The current course id.
494 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
495 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE
);
497 grade_force_full_regrading($courseid);
498 // Do this now, because it probably happened to late in the page load to be happen automatically.
499 grade_regrade_final_grades($courseid);
503 * Use the grade min and max from the grade_item.
505 * This is reserved for core use after an upgrade.
507 * @param int $courseid The current course id.
509 function grade_upgrade_use_min_max_from_grade_item($courseid) {
510 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM
);
512 grade_force_full_regrading($courseid);
513 // Do this now, because it probably happened to late in the page load to be happen automatically.
514 grade_regrade_final_grades($courseid);
518 * Hide warning about changed grades during upgrade to 2.8.
520 * @param int $courseid The current course id.
522 function hide_aggregatesubcats_upgrade_notice($courseid) {
523 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
527 * Hide warning about changed grades due to bug fixes
529 * @param int $courseid The current course id.
531 function hide_gradebook_calculations_freeze_notice($courseid) {
532 unset_config('gradebook_calculations_freeze_' . $courseid);
536 * Print warning about changed grades during upgrade to 2.8.
538 * @param int $courseid The current course id.
539 * @param context $context The course context.
540 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
541 * @param boolean $return return as string
543 * @return nothing or string if $return true
545 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
546 global $CFG, $OUTPUT;
549 // Do not do anything if they cannot manage the grades of this course.
550 if (!has_capability('moodle/grade:manage', $context)) {
554 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL
) && confirm_sesskey();
555 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
556 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL
) && confirm_sesskey();
557 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
559 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL
) && confirm_sesskey();
560 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
562 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL
) && confirm_sesskey();
563 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL
) && confirm_sesskey();
565 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse
);
567 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
568 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL
) && confirm_sesskey();
570 // Hide the warning if the user told it to go away.
571 if ($hidenaturalwarning) {
572 hide_natural_aggregation_upgrade_notice($courseid);
574 // Hide the warning if the user told it to go away.
575 if ($hidesubcatswarning) {
576 hide_aggregatesubcats_upgrade_notice($courseid);
579 // Hide the min/max warning if the user told it to go away.
580 if ($hideminmaxwarning) {
581 grade_hide_min_max_grade_upgrade_notice($courseid);
582 $showminmaxwarning = false;
585 if ($useminmaxfromgradegrade) {
586 // Revert to the new behaviour, we now use the grade_grade for min/max.
587 grade_upgrade_use_min_max_from_grade_grade($courseid);
588 grade_hide_min_max_grade_upgrade_notice($courseid);
589 $showminmaxwarning = false;
591 } else if ($useminmaxfromgradeitem) {
592 // Apply the new logic, we now use the grade_item for min/max.
593 grade_upgrade_use_min_max_from_grade_item($courseid);
594 grade_hide_min_max_grade_upgrade_notice($courseid);
595 $showminmaxwarning = false;
599 if (!$hidenaturalwarning && $shownaturalwarning) {
600 $message = get_string('sumofgradesupgradedgrades', 'grades');
601 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
602 $urlparams = array( 'id' => $courseid,
603 'seensumofgradesupgradedgrades' => true,
604 'sesskey' => sesskey());
605 $goawayurl = new moodle_url($thispage, $urlparams);
606 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
607 $html .= $OUTPUT->notification($message, 'notifysuccess');
608 $html .= $goawaybutton;
611 if (!$hidesubcatswarning && $showsubcatswarning) {
612 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
613 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
614 $urlparams = array( 'id' => $courseid,
615 'seenaggregatesubcatsupgradedgrades' => true,
616 'sesskey' => sesskey());
617 $goawayurl = new moodle_url($thispage, $urlparams);
618 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
619 $html .= $OUTPUT->notification($message, 'notifysuccess');
620 $html .= $goawaybutton;
623 if ($showminmaxwarning) {
624 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
625 $urlparams = array( 'id' => $courseid,
626 'seenminmaxupgradedgrades' => true,
627 'sesskey' => sesskey());
629 $goawayurl = new moodle_url($thispage, $urlparams);
630 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
631 $moreinfo = html_writer
::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
632 array('target' => '_blank'));
634 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM
) {
635 // Show the message that there were min/max issues that have been resolved.
636 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
638 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
639 $urlparams = array('id' => $courseid,
640 'useminmaxfromgradegrade' => true,
641 'sesskey' => sesskey());
642 $reverturl = new moodle_url($thispage, $urlparams);
643 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
645 $html .= $OUTPUT->notification($message);
646 $html .= $revertbutton . $hideminmaxbutton;
648 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE
) {
649 // Show the warning that there are min/max issues that have not be resolved.
650 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
652 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
653 $urlparams = array('id' => $courseid,
654 'useminmaxfromgradeitem' => true,
655 'sesskey' => sesskey());
656 $fixurl = new moodle_url($thispage, $urlparams);
657 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
659 $html .= $OUTPUT->notification($message);
660 $html .= $fixbutton . $hideminmaxbutton;
664 if ($gradebookcalculationsfreeze) {
665 if ($acceptgradebookchanges) {
666 // Accept potential changes in grades caused by extra credit bug MDL-49257.
667 hide_gradebook_calculations_freeze_notice($courseid);
668 $courseitem = grade_item
::fetch_course_item($courseid);
669 $courseitem->force_regrading();
670 grade_regrade_final_grades($courseid);
672 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
674 // Show the warning that there may be extra credit weights problems.
676 $a->gradebookversion
= $gradebookcalculationsfreeze;
677 if (preg_match('/(\d{8,})/', $CFG->release
, $matches)) {
678 $a->currentversion
= $matches[1];
680 $a->currentversion
= $CFG->release
;
682 $a->url
= get_docs_url('Gradebook_calculation_changes');
683 $message = get_string('gradebookcalculationswarning', 'grades', $a);
685 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
686 $urlparams = array('id' => $courseid,
687 'acceptgradebookchanges' => true,
688 'sesskey' => sesskey());
689 $fixurl = new moodle_url($thispage, $urlparams);
690 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
692 $html .= $OUTPUT->notification($message);
698 $html = html_writer
::tag('div', $html, array('class' => 'core_grades_notices'));
709 * grade_get_plugin_info
711 * @param int $courseid The course id
712 * @param string $active_type type of plugin on current page - import, export, report or edit
713 * @param string $active_plugin active plugin type - grader, user, cvs, ...
717 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
720 $context = context_course
::instance($courseid);
722 $plugin_info = array();
725 $url_prefix = $CFG->wwwroot
. '/grade/';
728 $plugin_info['strings'] = grade_helper
::get_plugin_strings();
730 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
731 $plugin_info['report'] = $reports;
734 if ($settings = grade_helper
::get_info_manage_settings($courseid)) {
735 $plugin_info['settings'] = $settings;
738 if ($scale = grade_helper
::get_info_scales($courseid)) {
739 $plugin_info['scale'] = array('view'=>$scale);
742 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
743 $plugin_info['outcome'] = $outcomes;
746 if ($letters = grade_helper
::get_info_letters($courseid)) {
747 $plugin_info['letter'] = $letters;
750 if ($imports = grade_helper
::get_plugins_import($courseid)) {
751 $plugin_info['import'] = $imports;
754 if ($exports = grade_helper
::get_plugins_export($courseid)) {
755 $plugin_info['export'] = $exports;
758 // Let other plugins add plugins here so that we get extra tabs
760 $callbacks = get_plugins_with_function('extend_gradebook_plugininfo', 'lib.php');
761 foreach ($callbacks as $plugins) {
762 foreach ($plugins as $pluginfunction) {
763 $plugin_info = $pluginfunction($plugin_info, $courseid);
767 foreach ($plugin_info as $plugin_type => $plugins) {
768 if (!empty($plugins->id
) && $active_plugin == $plugins->id
) {
769 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
772 foreach ($plugins as $plugin) {
773 if (is_a($plugin, grade_plugin_info
::class)) {
774 if ($plugin_type === $active_type && $active_plugin == $plugin->id
) {
775 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
785 * Load a valid list of gradable users in a course.
787 * @param int $courseid The course ID.
788 * @param int|null $groupid The group ID (optional).
789 * @param bool $onlyactiveenrol Include only active enrolments.
790 * @return array $users A list of enrolled gradable users.
792 function get_gradable_users(int $courseid, ?
int $groupid = null, bool $onlyactiveenrol = false): array {
793 $course = get_course($courseid);
794 // Create a graded_users_iterator because it will properly check the groups etc.
795 $gui = new graded_users_iterator($course, null, $groupid);
796 $gui->require_active_enrolment($onlyactiveenrol);
799 // Flatten the users.
801 while ($user = $gui->next_user()) {
802 $users[$user->user
->id
] = $user->user
;
810 * A simple class containing info about grade plugins.
811 * Can be subclassed for special rules
813 * @package core_grades
814 * @copyright 2009 Nicolas Connault
815 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
817 class grade_plugin_info
{
819 * A unique id for this plugin
825 * A URL to access this plugin
831 * The name of this plugin
837 * Another grade_plugin_info object, parent of the current one
846 * @param int $id A unique id for this plugin
847 * @param string $link A URL to access this plugin
848 * @param string $string The name of this plugin
849 * @param object $parent Another grade_plugin_info object, parent of the current one
853 public function __construct($id, $link, $string, $parent=null) {
856 $this->string = $string;
857 $this->parent
= $parent;
862 * Prints the page headers, breadcrumb trail, page heading, (optional) navigation and for any gradebook page.
863 * All gradebook pages MUST use these functions in favour of the usual print_header(), print_header_simple(),
864 * print_heading() etc.
866 * @param int $courseid Course id
867 * @param string $active_type The type of the current page (report, settings,
868 * import, export, scales, outcomes, letters)
869 * @param string|null $active_plugin The plugin of the current page (grader, fullview etc...)
870 * @param string|bool $heading The heading of the page.
871 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
872 * @param string|bool $buttons Additional buttons to display on the page
873 * @param boolean $shownavigation should the gradebook navigation be shown?
874 * @param string|null $headerhelpidentifier The help string identifier if required.
875 * @param string|null $headerhelpcomponent The component for the help string.
876 * @param stdClass|null $user The user object for use with the user context header.
877 * @param action_bar|null $actionbar The actions bar which will be displayed on the page if $shownavigation is set
878 * to true. If $actionbar is not explicitly defined, the general action bar
879 * (\core_grades\output\general_action_bar) will be used by default.
880 * @param null $unused This parameter has been deprecated since 4.3 and should not be used anymore.
881 * @return string HTML code or nothing if $return == false
883 function print_grade_page_head(int $courseid, string $active_type, ?
string $active_plugin = null, string|
bool $heading = false,
884 bool $return = false, $buttons = false, bool $shownavigation = true, ?
string $headerhelpidentifier = null,
885 ?
string $headerhelpcomponent = null, ?stdClass
$user = null, ?action_bar
$actionbar = null, $unused = null) {
886 global $CFG, $OUTPUT, $PAGE, $USER;
888 if ($heading !== false) {
889 // Make sure to trim heading, including the non-breaking space character.
890 $heading = str_replace(" ", " ", $heading);
891 $heading = trim($heading);
894 if ($unused !== null) {
895 debugging('Deprecated argument passed to ' . __FUNCTION__
, DEBUG_DEVELOPER
);
898 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
899 require_once($CFG->dirroot
. '/course/lib.php');
900 if (course_modules_pending_deletion($courseid, true)) {
901 \core\notification
::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
902 \core\output\notification
::NOTIFY_WARNING
);
905 if ($active_type === 'preferences') {
906 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
907 $active_type = 'settings';
910 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
912 // Determine the string of the active plugin.
913 $stractive_type = $plugin_info['strings'][$active_type];
914 $stractiveplugin = ($active_plugin) ?
$plugin_info['strings']['active_plugin_str'] : $heading;
916 if ($active_type == 'report') {
917 $PAGE->set_pagelayout('report');
919 $PAGE->set_pagelayout('admin');
921 $coursecontext = context_course
::instance($courseid);
922 // Title will be constituted by information starting from the unique identifying information for the page.
924 // If heading is supplied, use this for the page title.
925 $uniquetitle = $heading;
926 } else if (in_array($active_type, ['report', 'settings'])) {
927 // For grade reports or settings pages of grade plugins, use the plugin name for the unique title.
928 $uniquetitle = $stractiveplugin;
929 // But if editing mode is turned on, check if the report plugin has an editing mode title string and use it if present.
930 if ($PAGE->user_is_editing() && $active_type === 'report') {
931 $strcomponent = "gradereport_{$active_plugin}";
932 if (get_string_manager()->string_exists('editingmode_title', $strcomponent)) {
933 $uniquetitle = get_string('editingmode_title', $strcomponent);
937 $uniquetitle = $stractive_type . ': ' . $stractiveplugin;
941 $coursecontext->get_context_name(false),
943 $PAGE->set_title(implode(moodle_page
::TITLE_SEPARATOR
, $titlecomponents));
944 $PAGE->set_heading($PAGE->course
->fullname
);
945 $PAGE->set_secondary_active_tab('grades');
947 if ($buttons instanceof single_button
) {
948 $buttons = $OUTPUT->render($buttons);
950 $PAGE->set_button($buttons);
951 if ($courseid != SITEID
) {
952 grade_extend_settings($plugin_info, $courseid);
955 // Set the current report as active in the breadcrumbs.
956 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav
->find($active_plugin, navigation_node
::TYPE_SETTING
)) {
957 $reportnav->make_active();
960 $returnval = $OUTPUT->header();
966 if ($shownavigation) {
967 $renderer = $PAGE->get_renderer('core_grades');
968 // If the navigation action bar is not explicitly defined, use the general (default) action bar.
970 $actionbar = new general_action_bar($PAGE->context
, $PAGE->url
, $active_type, $active_plugin);
974 $returnval .= $renderer->render_action_bar($actionbar);
976 echo $renderer->render_action_bar($actionbar);
981 // Add a help dialogue box if provided.
982 if (isset($headerhelpidentifier) && !empty($heading)) {
983 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
984 } else if (isset($user)) {
985 $renderer = $PAGE->get_renderer('core_grades');
986 // If the user is viewing their own grade report, no need to show the "Message"
987 // and "Add to contact" buttons in the user heading.
988 $showuserbuttons = $user->id
!= $USER->id
;
989 $output = $renderer->user_heading($user, $courseid, $showuserbuttons);
990 } else if (!empty($heading)) {
991 $output = $OUTPUT->heading($heading);
995 $returnval .= $output;
1000 $returnval .= print_natural_aggregation_upgrade_notice($courseid, $coursecontext, $PAGE->url
, $return);
1008 * Utility class used for return tracking when using edit and other forms in grade plugins
1010 * @package core_grades
1011 * @copyright 2009 Nicolas Connault
1012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1014 class grade_plugin_return
{
1016 * Type of grade plugin (e.g. 'edit', 'report')
1022 * Name of grade plugin (e.g. 'grader', 'overview')
1028 * Course id being viewed
1034 * Id of user whose information is being viewed/edited
1040 * Id of group for which information is being viewed/edited
1046 * Current page # within output
1061 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1063 public function __construct($params = []) {
1064 $this->type
= optional_param('gpr_type', null, PARAM_SAFEDIR
);
1065 $this->plugin
= optional_param('gpr_plugin', null, PARAM_PLUGIN
);
1066 $this->courseid
= optional_param('gpr_courseid', null, PARAM_INT
);
1067 $this->userid
= optional_param('gpr_userid', null, PARAM_INT
);
1068 $this->groupid
= optional_param('gpr_groupid', null, PARAM_INT
);
1069 $this->page
= optional_param('gpr_page', null, PARAM_INT
);
1070 $this->search
= optional_param('gpr_search', '', PARAM_NOTAGS
);
1072 foreach ($params as $key => $value) {
1073 if (property_exists($this, $key)) {
1074 $this->$key = $value;
1077 // Allow course object rather than id to be used to specify course
1078 // - avoid unnecessary use of get_course.
1079 if (array_key_exists('course', $params)) {
1080 $course = $params['course'];
1081 $this->courseid
= $course->id
;
1085 // If group has been explicitly set in constructor parameters,
1086 // we should respect that.
1087 if (!array_key_exists('groupid', $params)) {
1088 // Otherwise, 'group' in request parameters is a request for a change.
1089 // In that case, or if we have no group at all, we should get groupid from
1090 // groups_get_course_group, which will do some housekeeping as well as
1091 // give us the correct value.
1092 $changegroup = optional_param('group', -1, PARAM_INT
);
1093 if ($changegroup !== -1 or (empty($this->groupid
) and !empty($this->courseid
))) {
1094 if ($course === null) {
1095 $course = get_course($this->courseid
);
1097 $this->groupid
= groups_get_course_group($course, true);
1103 * Old syntax of class constructor. Deprecated in PHP7.
1105 * @deprecated since Moodle 3.1
1107 public function grade_plugin_return($params = null) {
1108 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
1109 self
::__construct($params);
1113 * Returns return parameters as options array suitable for buttons.
1114 * @return array options
1116 public function get_options() {
1117 if (empty($this->type
)) {
1123 if (!empty($this->plugin
)) {
1124 $params['plugin'] = $this->plugin
;
1127 if (!empty($this->courseid
)) {
1128 $params['id'] = $this->courseid
;
1131 if (!empty($this->userid
)) {
1132 $params['userid'] = $this->userid
;
1135 if (!empty($this->groupid
)) {
1136 $params['group'] = $this->groupid
;
1139 if (!empty($this->page
)) {
1140 $params['page'] = $this->page
;
1147 * Returns return url
1149 * @param string $default default url when params not set
1150 * @param array $extras Extra URL parameters
1152 * @return string url
1154 public function get_return_url($default, $extras=null) {
1157 if (empty($this->type
) or empty($this->plugin
)) {
1161 $url = $CFG->wwwroot
.'/grade/'.$this->type
.'/'.$this->plugin
.'/index.php';
1164 if (!empty($this->courseid
)) {
1165 $url .= $glue.'id='.$this->courseid
;
1169 if (!empty($this->userid
)) {
1170 $url .= $glue.'userid='.$this->userid
;
1174 if (!empty($this->groupid
)) {
1175 $url .= $glue.'group='.$this->groupid
;
1179 if (!empty($this->page
)) {
1180 $url .= $glue.'page='.$this->page
;
1184 if (!empty($extras)) {
1185 foreach ($extras as $key=>$value) {
1186 $url .= $glue.$key.'='.$value;
1195 * Returns string with hidden return tracking form elements.
1198 public function get_form_fields() {
1199 if (empty($this->type
)) {
1203 $result = '<input type="hidden" name="gpr_type" value="'.$this->type
.'" />';
1205 if (!empty($this->plugin
)) {
1206 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin
.'" />';
1209 if (!empty($this->courseid
)) {
1210 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid
.'" />';
1213 if (!empty($this->userid
)) {
1214 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid
.'" />';
1217 if (!empty($this->groupid
)) {
1218 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid
.'" />';
1221 if (!empty($this->page
)) {
1222 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page
.'" />';
1225 if (!empty($this->search
)) {
1226 $result .= html_writer
::empty_tag('input',
1227 ['type' => 'hidden', 'name' => 'gpr_search', 'value' => $this->search
]);
1234 * Add hidden elements into mform
1236 * @param object &$mform moodle form object
1240 public function add_mform_elements(&$mform) {
1241 if (empty($this->type
)) {
1245 $mform->addElement('hidden', 'gpr_type', $this->type
);
1246 $mform->setType('gpr_type', PARAM_SAFEDIR
);
1248 if (!empty($this->plugin
)) {
1249 $mform->addElement('hidden', 'gpr_plugin', $this->plugin
);
1250 $mform->setType('gpr_plugin', PARAM_PLUGIN
);
1253 if (!empty($this->courseid
)) {
1254 $mform->addElement('hidden', 'gpr_courseid', $this->courseid
);
1255 $mform->setType('gpr_courseid', PARAM_INT
);
1258 if (!empty($this->userid
)) {
1259 $mform->addElement('hidden', 'gpr_userid', $this->userid
);
1260 $mform->setType('gpr_userid', PARAM_INT
);
1263 if (!empty($this->groupid
)) {
1264 $mform->addElement('hidden', 'gpr_groupid', $this->groupid
);
1265 $mform->setType('gpr_groupid', PARAM_INT
);
1268 if (!empty($this->page
)) {
1269 $mform->addElement('hidden', 'gpr_page', $this->page
);
1270 $mform->setType('gpr_page', PARAM_INT
);
1275 * Add return tracking params into url
1277 * @param moodle_url $url A URL
1278 * @return moodle_url with return tracking params
1280 public function add_url_params(moodle_url
$url): moodle_url
{
1281 if (empty($this->type
)) {
1285 $url->param('gpr_type', $this->type
);
1287 if (!empty($this->plugin
)) {
1288 $url->param('gpr_plugin', $this->plugin
);
1291 if (!empty($this->courseid
)) {
1292 $url->param('gpr_courseid' ,$this->courseid
);
1295 if (!empty($this->userid
)) {
1296 $url->param('gpr_userid', $this->userid
);
1299 if (!empty($this->groupid
)) {
1300 $url->param('gpr_groupid', $this->groupid
);
1303 if (!empty($this->page
)) {
1304 $url->param('gpr_page', $this->page
);
1312 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1314 * @param string $path The path of the calling script (using __FILE__?)
1315 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1316 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1317 * an array of keys and values (e.g courseid => $courseid, itemid...)
1321 function grade_build_nav($path, $pagename=null, $id=null) {
1322 global $CFG, $COURSE, $PAGE;
1324 $strgrades = get_string('grades', 'grades');
1326 // Parse the path and build navlinks from its elements
1327 $dirroot_length = strlen($CFG->dirroot
) +
1; // Add 1 for the first slash
1328 $path = substr($path, $dirroot_length);
1329 $path = str_replace('\\', '/', $path);
1331 $path_elements = explode('/', $path);
1333 $path_elements_count = count($path_elements);
1335 // First link is always 'grade'
1336 $PAGE->navbar
->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id
)));
1339 $numberofelements = 3;
1341 // Prepare URL params string
1342 $linkparams = array();
1343 if (!is_null($id)) {
1344 if (is_array($id)) {
1345 foreach ($id as $idkey => $idvalue) {
1346 $linkparams[$idkey] = $idvalue;
1349 $linkparams['id'] = $id;
1355 // Remove file extensions from filenames
1356 foreach ($path_elements as $key => $filename) {
1357 $path_elements[$key] = str_replace('.php', '', $filename);
1360 // Second level links
1361 switch ($path_elements[1]) {
1362 case 'edit': // No link
1363 if ($path_elements[3] != 'index.php') {
1364 $numberofelements = 4;
1367 case 'import': // No link
1369 case 'export': // No link
1372 // $id is required for this link. Do not print it if $id isn't given
1373 if (!is_null($id)) {
1374 $link = new moodle_url('/grade/report/index.php', $linkparams);
1377 if ($path_elements[2] == 'grader') {
1378 $numberofelements = 4;
1383 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1384 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1385 " as the second path element after 'grade'.");
1388 $PAGE->navbar
->add(get_string($path_elements[1], 'grades'), $link);
1390 // Third level links
1391 if (empty($pagename)) {
1392 $pagename = get_string($path_elements[2], 'grades');
1395 switch ($numberofelements) {
1397 $PAGE->navbar
->add($pagename, $link);
1400 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1401 $PAGE->navbar
->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1403 $PAGE->navbar
->add($pagename);
1411 * General structure representing grade items in course
1413 * @package core_grades
1414 * @copyright 2009 Nicolas Connault
1415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1417 class grade_structure
{
1423 * Reference to modinfo for current course (for performance, to save
1424 * retrieving it from courseid every time). Not actually set except for
1425 * the grade_tree type.
1426 * @var course_modinfo
1431 * 1D array of grade items only
1436 * Returns icon of element
1438 * @param array &$element An array representing an element in the grade_tree
1439 * @param bool $spacerifnone return spacer if no icon found
1441 * @return string icon or spacer
1442 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_icon()}
1443 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1445 public function get_element_icon(&$element, $spacerifnone=false) {
1446 debugging('The function get_element_icon() is deprecated, please use grade_helper::get_element_icon() instead.',
1448 return grade_helper
::get_element_icon($element, $spacerifnone);
1452 * Returns the string that describes the type of the element.
1454 * @param array $element An array representing an element in the grade_tree
1455 * @return string The string that describes the type of the grade element
1456 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_type_string()}
1457 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1459 public function get_element_type_string(array $element): string {
1460 debugging('The function get_element_type_string() is deprecated,' .
1461 ' please use grade_helper::get_element_type_string() instead.',
1463 return grade_helper
::get_element_type_string($element);
1467 * Returns name of element optionally with icon and link
1469 * @param array &$element An array representing an element in the grade_tree
1470 * @param bool $withlink Whether or not this header has a link
1471 * @param bool $icon Whether or not to display an icon with this header
1472 * @param bool $spacerifnone return spacer if no icon found
1473 * @param bool $withdescription Show description if defined by this item.
1474 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1475 * instead of "Category total" or "Course total"
1476 * @param moodle_url|null $sortlink Link to sort column.
1478 * @return string header
1479 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_element_header()}
1480 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1482 public function get_element_header(array &$element, bool $withlink = false, bool $icon = true,
1483 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
1484 ?moodle_url
$sortlink = null) {
1485 debugging('The function get_element_header() is deprecated, please use grade_helper::get_element_header() instead.',
1487 return grade_helper
::get_element_header($element, $withlink, $icon, $spacerifnone, $withdescription,
1488 $fulltotal, $sortlink);
1492 * @deprecated since Moodle 4.4 - please use {@see grade_helper::get_activity_link()}
1493 * @todo MDL-79907 This will be deleted in Moodle 4.8.
1495 private function get_activity_link($element) {
1496 debugging('The function get_activity_link() is deprecated, please use grade_helper::get_activity_link() instead.',
1498 return grade_helper
::get_activity_link($element);
1502 * Returns URL of a page that is supposed to contain detailed grade analysis
1504 * At the moment, only activity modules are supported. The method generates link
1505 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1506 * gradeid and userid. If the grade.php does not exist, null is returned.
1508 * @return moodle_url|null URL or null if unable to construct it
1510 public function get_grade_analysis_url(grade_grade
$grade) {
1512 /** @var array static cache of the grade.php file existence flags */
1513 static $hasgradephp = array();
1515 if (empty($grade->grade_item
) or !($grade->grade_item
instanceof grade_item
)) {
1516 throw new coding_exception('Passed grade without the associated grade item');
1518 $item = $grade->grade_item
;
1520 if (!$item->is_external_item()) {
1521 // at the moment, only activity modules are supported
1524 if ($item->itemtype
!== 'mod') {
1525 throw new coding_exception('Unknown external itemtype: '.$item->itemtype
);
1527 if (empty($item->iteminstance
) or empty($item->itemmodule
) or empty($this->modinfo
)) {
1531 if (!array_key_exists($item->itemmodule
, $hasgradephp)) {
1532 if (file_exists($CFG->dirroot
. '/mod/' . $item->itemmodule
. '/grade.php')) {
1533 $hasgradephp[$item->itemmodule
] = true;
1535 $hasgradephp[$item->itemmodule
] = false;
1539 if (!$hasgradephp[$item->itemmodule
]) {
1543 $instances = $this->modinfo
->get_instances();
1544 if (empty($instances[$item->itemmodule
][$item->iteminstance
])) {
1547 $cm = $instances[$item->itemmodule
][$item->iteminstance
];
1548 if (!$cm->uservisible
) {
1552 $url = new moodle_url('/mod/'.$item->itemmodule
.'/grade.php', array(
1554 'itemid' => $item->id
,
1555 'itemnumber' => $item->itemnumber
,
1556 'gradeid' => $grade->id
,
1557 'userid' => $grade->userid
,
1564 * Returns an action icon leading to the grade analysis page
1566 * @param grade_grade $grade
1568 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1569 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1571 public function get_grade_analysis_icon(grade_grade
$grade) {
1573 debugging('The function get_grade_analysis_icon() is deprecated, please do not use it anymore.',
1576 $url = $this->get_grade_analysis_url($grade);
1577 if (is_null($url)) {
1581 $title = get_string('gradeanalysis', 'core_grades');
1582 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1583 ['title' => $title, 'aria-label' => $title]);
1587 * Returns a link leading to the grade analysis page
1589 * @param grade_grade $grade
1590 * @return string|null
1592 public function get_grade_analysis_link(grade_grade
$grade): ?
string {
1593 $url = $this->get_grade_analysis_url($grade);
1594 if (is_null($url)) {
1598 $gradeanalysisstring = get_string('gradeanalysis', 'grades');
1599 return html_writer
::link($url, $gradeanalysisstring,
1600 ['class' => 'dropdown-item', 'aria-label' => $gradeanalysisstring, 'role' => 'menuitem']);
1604 * Returns an action menu for the grade.
1606 * @param grade_grade $grade A grade_grade object
1609 public function get_grade_action_menu(grade_grade
$grade) : string {
1614 $url = $this->get_grade_analysis_url($grade);
1616 $title = get_string('gradeanalysis', 'core_grades');
1617 $menuitems[] = new action_menu_link_secondary($url, null, $title);
1621 $menu = new action_menu($menuitems);
1622 $icon = $OUTPUT->pix_icon('i/moremenu', get_string('actions'));
1623 $extraclasses = 'btn btn-link btn-icon icon-size-3 d-flex align-items-center justify-content-center';
1624 $menu->set_menu_trigger($icon, $extraclasses);
1625 $menu->set_menu_left();
1627 return $OUTPUT->render($menu);
1634 * Returns the grade eid - the grade may not exist yet.
1636 * @param grade_grade $grade_grade A grade_grade object
1638 * @return string eid
1640 public function get_grade_eid($grade_grade) {
1641 if (empty($grade_grade->id
)) {
1642 return 'n'.$grade_grade->itemid
.'u'.$grade_grade->userid
;
1644 return 'g'.$grade_grade->id
;
1649 * Returns the grade_item eid
1650 * @param grade_item $grade_item A grade_item object
1651 * @return string eid
1653 public function get_item_eid($grade_item) {
1654 return 'ig'.$grade_item->id
;
1658 * Given a grade_tree element, returns an array of parameters
1659 * used to build an icon for that element.
1661 * @param array $element An array representing an element in the grade_tree
1665 public function get_params_for_iconstr($element) {
1666 $strparams = new stdClass();
1667 $strparams->category
= '';
1668 $strparams->itemname
= '';
1669 $strparams->itemmodule
= '';
1671 if (!method_exists($element['object'], 'get_name')) {
1675 $strparams->itemname
= html_to_text($element['object']->get_name());
1677 // If element name is categorytotal, get the name of the parent category
1678 if ($strparams->itemname
== get_string('categorytotal', 'grades')) {
1679 $parent = $element['object']->get_parent_category();
1680 $strparams->category
= $parent->get_name() . ' ';
1682 $strparams->category
= '';
1685 $strparams->itemmodule
= null;
1686 if (isset($element['object']->itemmodule
)) {
1687 $strparams->itemmodule
= $element['object']->itemmodule
;
1693 * Return a reset icon for the given element.
1695 * @param array $element An array representing an element in the grade_tree
1696 * @param object $gpr A grade_plugin_return object
1697 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1698 * @return string|action_menu_link
1699 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1700 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1702 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1703 global $CFG, $OUTPUT;
1704 debugging('The function get_reset_icon() is deprecated, please do not use it anymore.',
1707 // Limit to category items set to use the natural weights aggregation method, and users
1708 // with the capability to manage grades.
1709 if ($element['type'] != 'category' ||
$element['object']->aggregation
!= GRADE_AGGREGATE_SUM ||
1710 !has_capability('moodle/grade:manage', $this->context
)) {
1711 return $returnactionmenulink ?
null : '';
1714 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1715 $url = new moodle_url('/grade/edit/tree/action.php', array(
1716 'id' => $this->courseid
,
1717 'action' => 'resetweights',
1718 'eid' => $element['eid'],
1719 'sesskey' => sesskey(),
1722 if ($returnactionmenulink) {
1723 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1724 get_string('resetweightsshort', 'grades'));
1726 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1731 * Returns a link to reset weights for the given element.
1733 * @param array $element An array representing an element in the grade_tree
1734 * @param object $gpr A grade_plugin_return object
1735 * @return string|null
1737 public function get_reset_weights_link(array $element, object $gpr): ?
string {
1739 // Limit to category items set to use the natural weights aggregation method, and users
1740 // with the capability to manage grades.
1741 if ($element['type'] != 'category' ||
$element['object']->aggregation
!= GRADE_AGGREGATE_SUM ||
1742 !has_capability('moodle/grade:manage', $this->context
)) {
1746 $title = get_string('resetweightsshort', 'grades');
1747 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1748 $url = new moodle_url('/grade/edit/tree/action.php', [
1749 'id' => $this->courseid
,
1750 'action' => 'resetweights',
1751 'eid' => $element['eid'],
1752 'sesskey' => sesskey(),
1754 $gpr->add_url_params($url);
1755 return html_writer
::link($url, $title,
1756 ['class' => 'dropdown-item', 'aria-label' => $str, 'role' => 'menuitem']);
1760 * Returns a link to delete a given element.
1762 * @param array $element An array representing an element in the grade_tree
1763 * @param object $gpr A grade_plugin_return object
1764 * @return string|null
1766 public function get_delete_link(array $element, object $gpr): ?
string {
1767 if ($element['type'] == 'item' ||
($element['type'] == 'category' && $element['depth'] > 1)) {
1768 if (grade_edit_tree
::element_deletable($element)) {
1769 $deleteconfirmationurl = new moodle_url('index.php', [
1770 'id' => $this->courseid
,
1771 'action' => 'delete',
1773 'eid' => $element['eid'],
1774 'sesskey' => sesskey(),
1776 $gpr->add_url_params($deleteconfirmationurl);
1777 $title = get_string('delete');
1778 return html_writer
::link(
1782 'class' => 'dropdown-item',
1783 'aria-label' => $title,
1784 'role' => 'menuitem',
1785 'data-modal' => 'confirmation',
1786 'data-modal-title-str' => json_encode(['confirm', 'core']),
1787 'data-modal-content-str' => json_encode([
1790 $element['object']->get_name()
1792 'data-modal-yes-button-str' => json_encode(['delete', 'core']),
1793 'data-modal-destination' => $deleteconfirmationurl->out(false),
1802 * Returns a link to duplicate a given element.
1804 * @param array $element An array representing an element in the grade_tree
1805 * @param object $gpr A grade_plugin_return object
1806 * @return string|null
1808 public function get_duplicate_link(array $element, object $gpr): ?
string {
1809 if ($element['type'] == 'item' ||
($element['type'] == 'category' && $element['depth'] > 1)) {
1810 if (grade_edit_tree
::element_duplicatable($element)) {
1811 $duplicateparams = [];
1812 $duplicateparams['id'] = $this->courseid
;
1813 $duplicateparams['action'] = 'duplicate';
1814 $duplicateparams['eid'] = $element['eid'];
1815 $duplicateparams['sesskey'] = sesskey();
1816 $url = new moodle_url('index.php', $duplicateparams);
1817 $title = get_string('duplicate');
1818 $gpr->add_url_params($url);
1819 return html_writer
::link($url, $title,
1820 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1827 * Return edit icon for give element
1829 * @param array $element An array representing an element in the grade_tree
1830 * @param object $gpr A grade_plugin_return object
1831 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1832 * @return string|action_menu_link
1833 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1834 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1836 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1837 global $CFG, $OUTPUT;
1839 debugging('The function get_edit_icon() is deprecated, please do not use it anymore.',
1842 if (!has_capability('moodle/grade:manage', $this->context
)) {
1843 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context
)) {
1844 // oki - let them override grade
1846 return $returnactionmenulink ?
null : '';
1850 static $strfeedback = null;
1851 static $streditgrade = null;
1852 if (is_null($streditgrade)) {
1853 $streditgrade = get_string('editgrade', 'grades');
1854 $strfeedback = get_string('feedback');
1857 $strparams = $this->get_params_for_iconstr($element);
1859 $object = $element['object'];
1861 switch ($element['type']) {
1863 case 'categoryitem':
1865 $stredit = get_string('editverbose', 'grades', $strparams);
1866 if (empty($object->outcomeid
) ||
empty($CFG->enableoutcomes
)) {
1867 $url = new moodle_url('/grade/edit/tree/item.php',
1868 array('courseid' => $this->courseid
, 'id' => $object->id
));
1870 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1871 array('courseid' => $this->courseid
, 'id' => $object->id
));
1876 $stredit = get_string('editverbose', 'grades', $strparams);
1877 $url = new moodle_url('/grade/edit/tree/category.php',
1878 array('courseid' => $this->courseid
, 'id' => $object->id
));
1882 $stredit = $streditgrade;
1883 if (empty($object->id
)) {
1884 $url = new moodle_url('/grade/edit/tree/grade.php',
1885 array('courseid' => $this->courseid
, 'itemid' => $object->itemid
, 'userid' => $object->userid
));
1887 $url = new moodle_url('/grade/edit/tree/grade.php',
1888 array('courseid' => $this->courseid
, 'id' => $object->id
));
1890 if (!empty($object->feedback
)) {
1891 $feedback = addslashes_js(trim(format_string($object->feedback
, $object->feedbackformat
)));
1900 if ($returnactionmenulink) {
1901 return new action_menu_link_secondary($gpr->add_url_params($url),
1902 new pix_icon('t/edit', $stredit),
1903 get_string('editsettings'));
1905 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1909 return $returnactionmenulink ?
null : '';
1914 * Returns a link leading to the edit grade/grade item/category page
1916 * @param array $element An array representing an element in the grade_tree
1917 * @param object $gpr A grade_plugin_return object
1918 * @return string|null
1920 public function get_edit_link(array $element, object $gpr): ?
string {
1925 if ((!has_capability('moodle/grade:manage', $this->context
) &&
1926 (!($element['type'] == 'grade') ||
!has_capability('moodle/grade:edit', $this->context
)))) {
1930 $object = $element['object'];
1932 if ($element['type'] == 'grade') {
1933 if (empty($object->id
)) {
1934 $url = new moodle_url('/grade/edit/tree/grade.php',
1935 ['courseid' => $this->courseid
, 'itemid' => $object->itemid
, 'userid' => $object->userid
]);
1937 $url = new moodle_url('/grade/edit/tree/grade.php',
1938 ['courseid' => $this->courseid
, 'id' => $object->id
]);
1940 $url = $gpr->add_url_params($url);
1941 $title = get_string('editgrade', 'grades');
1942 } else if (($element['type'] == 'item') ||
($element['type'] == 'categoryitem') ||
1943 ($element['type'] == 'courseitem')) {
1944 $url = new moodle_url('#');
1945 if (empty($object->outcomeid
) ||
empty($CFG->enableoutcomes
)) {
1946 return html_writer
::link($url, get_string('itemsedit', 'grades'), [
1947 'class' => 'dropdown-item',
1948 'aria-label' => get_string('itemsedit', 'grades'),
1949 'role' => 'menuitem',
1950 'data-gprplugin' => $gpr->plugin
,
1951 'data-courseid' => $this->courseid
,
1952 'data-itemid' => $object->id
, 'data-trigger' => 'add-item-form'
1954 } else if (count(grade_outcome
::fetch_all_available($this->courseid
)) > 0) {
1955 return html_writer
::link($url, get_string('itemsedit', 'grades'), [
1956 'class' => 'dropdown-item',
1957 get_string('itemsedit', 'grades'),
1958 'role' => 'menuitem',
1959 'data-gprplugin' => $gpr->plugin
,
1960 'data-courseid' => $this->courseid
,
1961 'data-itemid' => $object->id
, 'data-trigger' => 'add-outcome-form'
1964 } else if ($element['type'] == 'category') {
1965 $url = new moodle_url('#');
1966 $title = get_string('categoryedit', 'grades');
1967 return html_writer
::link($url, $title, [
1968 'class' => 'dropdown-item',
1969 'aria-label' => $title,
1970 'role' => 'menuitem',
1971 'data-gprplugin' => $gpr->plugin
,
1972 'data-courseid' => $this->courseid
,
1973 'data-category' => $object->id
,
1974 'data-trigger' => 'add-category-form'
1977 return html_writer
::link($url, $title,
1978 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1982 * Returns link to the advanced grading page
1984 * @param array $element An array representing an element in the grade_tree
1985 * @param object $gpr A grade_plugin_return object
1986 * @return string|null
1988 public function get_advanced_grading_link(array $element, object $gpr): ?
string {
1991 /** @var array static cache of the grade.php file existence flags */
1992 static $hasgradephp = [];
1994 $itemtype = $element['object']->itemtype
;
1995 $itemmodule = $element['object']->itemmodule
;
1996 $iteminstance = $element['object']->iteminstance
;
1997 $itemnumber = $element['object']->itemnumber
;
1999 // Links only for module items that have valid instance, module and are
2000 // called from grade_tree with valid modinfo.
2001 if ($itemtype == 'mod' && $iteminstance && $itemmodule && $this->modinfo
) {
2003 // Get $cm efficiently and with visibility information using modinfo.
2004 $instances = $this->modinfo
->get_instances();
2005 if (!empty($instances[$itemmodule][$iteminstance])) {
2006 $cm = $instances[$itemmodule][$iteminstance];
2008 // Do not add link if activity is not visible to the current user.
2009 if ($cm->uservisible
) {
2010 if (!array_key_exists($itemmodule, $hasgradephp)) {
2011 if (file_exists($CFG->dirroot
. '/mod/' . $itemmodule . '/grade.php')) {
2012 $hasgradephp[$itemmodule] = true;
2014 $hasgradephp[$itemmodule] = false;
2018 // If module has grade.php, add link to that.
2019 if ($hasgradephp[$itemmodule]) {
2020 $args = array('id' => $cm->id
, 'itemnumber' => $itemnumber);
2021 if (isset($element['userid'])) {
2022 $args['userid'] = $element['userid'];
2025 $url = new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
2026 $title = get_string('advancedgrading', 'gradereport_grader',
2027 get_string('pluginname', "mod_{$itemmodule}"));
2028 $gpr->add_url_params($url);
2029 return html_writer
::link($url, $title,
2030 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2040 * Return hiding icon for give element
2042 * @param array $element An array representing an element in the grade_tree
2043 * @param object $gpr A grade_plugin_return object
2044 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2045 * @return string|action_menu_link
2046 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2047 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2049 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
2050 global $CFG, $OUTPUT;
2051 debugging('The function get_hiding_icon() is deprecated, please do not use it anymore.',
2054 if (!$element['object']->can_control_visibility()) {
2055 return $returnactionmenulink ?
null : '';
2058 if (!has_capability('moodle/grade:manage', $this->context
) and
2059 !has_capability('moodle/grade:hide', $this->context
)) {
2060 return $returnactionmenulink ?
null : '';
2063 $strparams = $this->get_params_for_iconstr($element);
2064 $strshow = get_string('showverbose', 'grades', $strparams);
2065 $strhide = get_string('hideverbose', 'grades', $strparams);
2067 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2068 $url = $gpr->add_url_params($url);
2070 if ($element['object']->is_hidden()) {
2072 $tooltip = $strshow;
2074 // Change the icon and add a tooltip showing the date
2075 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
2076 $type = 'hiddenuntil';
2077 $tooltip = get_string('hiddenuntildate', 'grades',
2078 userdate($element['object']->get_hidden()));
2081 $url->param('action', 'show');
2083 if ($returnactionmenulink) {
2084 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2086 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2090 $url->param('action', 'hide');
2091 if ($returnactionmenulink) {
2092 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2094 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2102 * Returns a link with url to hide/unhide grade/grade item/grade category
2104 * @param array $element An array representing an element in the grade_tree
2105 * @param object $gpr A grade_plugin_return object
2106 * @return string|null
2108 public function get_hiding_link(array $element, object $gpr): ?
string {
2109 if (!$element['object']->can_control_visibility() ||
!has_capability('moodle/grade:manage', $this->context
) ||
2110 !has_capability('moodle/grade:hide', $this->context
)) {
2114 $url = new moodle_url('/grade/edit/tree/action.php',
2115 ['id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2116 $url = $gpr->add_url_params($url);
2118 if ($element['object']->is_hidden()) {
2119 $url->param('action', 'show');
2120 $title = get_string('show');
2122 $url->param('action', 'hide');
2123 $title = get_string('hide');
2126 $url = html_writer
::link($url, $title,
2127 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2129 if ($element['type'] == 'grade') {
2130 $item = $element['object']->grade_item
;
2131 if ($item->hidden
) {
2132 $strparamobj = new stdClass();
2133 $strparamobj->itemname
= $item->get_name(true, true);
2134 $strnonunhideable = get_string('nonunhideableverbose', 'grades', $strparamobj);
2135 $url = html_writer
::span($title, 'text-muted dropdown-item',
2136 ['title' => $strnonunhideable, 'aria-label' => $title, 'role' => 'menuitem']);
2144 * Return locking icon for given element
2146 * @param array $element An array representing an element in the grade_tree
2147 * @param object $gpr A grade_plugin_return object
2150 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2151 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2153 public function get_locking_icon($element, $gpr) {
2154 global $CFG, $OUTPUT;
2155 debugging('The function get_locking_icon() is deprecated, please do not use it anymore.',
2158 $strparams = $this->get_params_for_iconstr($element);
2159 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2160 $strlock = get_string('lockverbose', 'grades', $strparams);
2162 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2163 $url = $gpr->add_url_params($url);
2165 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2166 if ($element['type'] == 'grade' && $element['object']->grade_item
->is_locked()) {
2167 $strparamobj = new stdClass();
2168 $strparamobj->itemname
= $element['object']->grade_item
->itemname
;
2169 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2171 $action = html_writer
::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2172 array('class' => 'action-icon'));
2174 } else if ($element['object']->is_locked()) {
2176 $tooltip = $strunlock;
2178 // Change the icon and add a tooltip showing the date
2179 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
2181 $tooltip = get_string('locktimedate', 'grades',
2182 userdate($element['object']->get_locktime()));
2185 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:unlock', $this->context
)) {
2188 $url->param('action', 'unlock');
2189 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
2193 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:lock', $this->context
)) {
2196 $url->param('action', 'lock');
2197 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
2205 * Returns link to lock/unlock grade/grade item/grade category
2207 * @param array $element An array representing an element in the grade_tree
2208 * @param object $gpr A grade_plugin_return object
2210 * @return string|null
2212 public function get_locking_link(array $element, object $gpr): ?
string {
2214 if (has_capability('moodle/grade:manage', $this->context
) && isset($element['object'])) {
2216 $url = new moodle_url('/grade/edit/tree/action.php',
2217 ['id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2218 $url = $gpr->add_url_params($url);
2220 if ($element['type'] == 'category') {
2221 // Grade categories themselves cannot be locked. We lock/unlock their grade items.
2222 $children = $element['object']->get_children(true);
2224 foreach ($children as $child) {
2225 if (!$child['object']->is_locked()) {
2230 if ($alllocked && has_capability('moodle/grade:unlock', $this->context
)) {
2231 $title = get_string('unlock', 'grades');
2232 $url->param('action', 'unlock');
2233 } else if (!$alllocked && has_capability('moodle/grade:lock', $this->context
)) {
2234 $title = get_string('lock', 'grades');
2235 $url->param('action', 'lock');
2239 } else if (($element['type'] == 'grade') && ($element['object']->grade_item
->is_locked())) {
2240 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon.
2241 $strparamobj = new stdClass();
2242 $strparamobj->itemname
= $element['object']->grade_item
->get_name(true, true);
2243 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2244 $title = get_string('unlock', 'grades');
2245 return html_writer
::span($title, 'text-muted dropdown-item', ['title' => $strnonunlockable,
2246 'aria-label' => $title, 'role' => 'menuitem']);
2247 } else if ($element['object']->is_locked()) {
2248 if (has_capability('moodle/grade:unlock', $this->context
)) {
2249 $title = get_string('unlock', 'grades');
2250 $url->param('action', 'unlock');
2255 if (has_capability('moodle/grade:lock', $this->context
)) {
2256 $title = get_string('lock', 'grades');
2257 $url->param('action', 'lock');
2263 return html_writer
::link($url, $title,
2264 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2271 * Return calculation icon for given element
2273 * @param array $element An array representing an element in the grade_tree
2274 * @param object $gpr A grade_plugin_return object
2275 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2276 * @return string|action_menu_link
2277 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2278 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2280 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
2281 global $CFG, $OUTPUT;
2282 debugging('The function get_calculation_icon() is deprecated, please do not use it anymore.',
2285 if (!has_capability('moodle/grade:manage', $this->context
)) {
2286 return $returnactionmenulink ?
null : '';
2289 $type = $element['type'];
2290 $object = $element['object'];
2292 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
2293 $strparams = $this->get_params_for_iconstr($element);
2294 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2296 $is_scale = $object->gradetype
== GRADE_TYPE_SCALE
;
2297 $is_value = $object->gradetype
== GRADE_TYPE_VALUE
;
2299 // show calculation icon only when calculation possible
2300 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2301 if ($object->is_calculated()) {
2304 $icon = 't/calc_off';
2307 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid
, 'id' => $object->id
));
2308 $url = $gpr->add_url_params($url);
2309 if ($returnactionmenulink) {
2310 return new action_menu_link_secondary($url,
2311 new pix_icon($icon, $streditcalculation),
2312 get_string('editcalculation', 'grades'));
2314 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2319 return $returnactionmenulink ?
null : '';
2323 * Returns link to edit calculation for a grade item.
2325 * @param array $element An array representing an element in the grade_tree
2326 * @param object $gpr A grade_plugin_return object
2328 * @return string|null
2330 public function get_edit_calculation_link(array $element, object $gpr): ?
string {
2332 if (has_capability('moodle/grade:manage', $this->context
) && isset($element['object'])) {
2333 $object = $element['object'];
2334 $isscale = $object->gradetype
== GRADE_TYPE_SCALE
;
2335 $isvalue = $object->gradetype
== GRADE_TYPE_VALUE
;
2337 // Show calculation icon only when calculation possible.
2338 if (!$object->is_external_item() && ($isscale ||
$isvalue)) {
2339 $editcalculationstring = get_string('editcalculation', 'grades');
2340 $url = new moodle_url('/grade/edit/tree/calculation.php',
2341 ['courseid' => $this->courseid
, 'id' => $object->id
]);
2342 $url = $gpr->add_url_params($url);
2343 return html_writer
::link($url, $editcalculationstring,
2344 ['class' => 'dropdown-item', 'aria-label' => $editcalculationstring, 'role' => 'menuitem']);
2351 * Sets status icons for the grade.
2353 * @param array $element array with grade item info
2354 * @return string|null status icons container HTML
2356 public function set_grade_status_icons(array $element): ?
string {
2360 'hidden' => $element['object']->is_hidden(),
2363 if ($element['object'] instanceof grade_grade
) {
2364 $grade = $element['object'];
2365 $context['overridden'] = $grade->is_overridden();
2366 $context['excluded'] = $grade->is_excluded();
2367 $context['feedback'] = !empty($grade->feedback
) && $grade->load_grade_item()->gradetype
!= GRADE_TYPE_TEXT
;
2370 $context['classes'] = 'grade_icons data-collapse_gradeicons';
2372 if ($element['object'] instanceof grade_category
) {
2373 $context['classes'] = 'category_grade_icons';
2375 $children = $element['object']->get_children(true);
2377 foreach ($children as $child) {
2378 if (!$child['object']->is_locked()) {
2384 $context['locked'] = true;
2387 $context['locked'] = $element['object']->is_locked();
2390 // Don't even attempt rendering if there is no status to show.
2391 if (in_array(true, $context)) {
2392 return $OUTPUT->render_from_template('core_grades/status_icons', $context);
2399 * Returns an action menu for the grade.
2401 * @param array $element Array with cell info.
2402 * @param string $mode Mode - gradeitem or user
2403 * @param grade_plugin_return $gpr
2404 * @param moodle_url|null $baseurl
2407 public function get_cell_action_menu(array $element, string $mode, grade_plugin_return
$gpr,
2408 ?moodle_url
$baseurl = null): string {
2409 global $OUTPUT, $USER;
2411 $context = new stdClass();
2413 if ($mode == 'gradeitem' ||
$mode == 'setup') {
2416 if ($element['type'] == 'grade') {
2417 $context->datatype
= 'grade';
2419 $item = $element['object']->grade_item
;
2420 if ($item->is_course_item() ||
$item->is_category_item()) {
2421 $editable = (bool)get_config('moodle', 'grade_overridecat');;
2424 if (!empty($USER->editing
)) {
2426 $context->editurl
= $this->get_edit_link($element, $gpr);
2428 $context->hideurl
= $this->get_hiding_link($element, $gpr);
2429 $context->lockurl
= $this->get_locking_link($element, $gpr);
2432 $context->gradeanalysisurl
= $this->get_grade_analysis_link($element['object']);
2433 } else if (($element['type'] == 'item') ||
($element['type'] == 'categoryitem') ||
2434 ($element['type'] == 'courseitem') ||
($element['type'] == 'userfield')) {
2436 $context->datatype
= 'item';
2438 if ($element['type'] == 'item') {
2439 if ($mode == 'setup') {
2440 $context->deleteurl
= $this->get_delete_link($element, $gpr);
2441 $context->duplicateurl
= $this->get_duplicate_link($element, $gpr);
2444 grade_report
::get_additional_context($this->context
, $this->courseid
,
2445 $element, $gpr, $mode, $context, true);
2446 $context->advancedgradingurl
= $this->get_advanced_grading_link($element, $gpr);
2448 $context->divider1
= true;
2451 if (($element['type'] == 'item') ||
2452 (($element['type'] == 'userfield') && ($element['name'] !== 'fullname'))) {
2453 $context->divider2
= true;
2456 if (!empty($USER->editing
) ||
$mode == 'setup') {
2457 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) {
2458 $context->divider2
= true;
2459 } else if (($mode !== 'setup') && ($element['type'] !== 'userfield')) {
2460 $context->divider1
= true;
2461 $context->divider2
= true;
2464 if ($element['type'] == 'item') {
2465 $context->editurl
= $this->get_edit_link($element, $gpr);
2468 $context->editcalculationurl
=
2469 $this->get_edit_calculation_link($element, $gpr);
2471 if (isset($element['object'])) {
2472 $object = $element['object'];
2473 if ($object->itemmodule
!== 'quiz') {
2474 $context->hideurl
= $this->get_hiding_link($element, $gpr);
2477 $context->lockurl
= $this->get_locking_link($element, $gpr);
2482 $sortlink = clone($baseurl);
2483 if (isset($element['object']->id
)) {
2484 $sortlink->param('sortitemid', $element['object']->id
);
2485 } else if ($element['type'] == 'userfield') {
2486 $context->datatype
= $element['name'];
2487 $sortlink->param('sortitemid', $element['name']);
2490 if (($element['type'] == 'userfield') && ($element['name'] == 'fullname')) {
2491 $sortlink->param('sortitemid', 'firstname');
2492 $context->ascendingfirstnameurl
= $this->get_sorting_link($sortlink, $gpr);
2493 $context->descendingfirstnameurl
= $this->get_sorting_link($sortlink, $gpr, 'desc');
2495 $sortlink->param('sortitemid', 'lastname');
2496 $context->ascendinglastnameurl
= $this->get_sorting_link($sortlink, $gpr);
2497 $context->descendinglastnameurl
= $this->get_sorting_link($sortlink, $gpr, 'desc');
2499 $context->ascendingurl
= $this->get_sorting_link($sortlink, $gpr);
2500 $context->descendingurl
= $this->get_sorting_link($sortlink, $gpr, 'desc');
2503 if ($mode !== 'setup') {
2504 $context = grade_report
::get_additional_context($this->context
, $this->courseid
,
2505 $element, $gpr, $mode, $context);
2507 } else if ($element['type'] == 'category') {
2508 $context->datatype
= 'category';
2509 if ($mode !== 'setup') {
2511 $context = grade_report
::get_additional_context($this->context
, $this->courseid
,
2512 $element, $gpr, $mode, $context);
2514 $context->deleteurl
= $this->get_delete_link($element, $gpr);
2515 $context->resetweightsurl
= $this->get_reset_weights_link($element, $gpr);
2518 if (!empty($USER->editing
) ||
$mode == 'setup') {
2519 if ($mode !== 'setup') {
2520 $context->divider1
= true;
2522 $context->editurl
= $this->get_edit_link($element, $gpr);
2523 $context->hideurl
= $this->get_hiding_link($element, $gpr);
2524 $context->lockurl
= $this->get_locking_link($element, $gpr);
2528 if (isset($element['object'])) {
2529 $context->dataid
= $element['object']->id
;
2530 } else if ($element['type'] == 'userfield') {
2531 $context->dataid
= $element['name'];
2534 if ($element['type'] != 'text' && !empty($element['object']->feedback
)) {
2535 $viewfeedbackstring = get_string('viewfeedback', 'grades');
2536 $context->viewfeedbackurl
= html_writer
::link('#', $viewfeedbackstring, ['class' => 'dropdown-item',
2537 'aria-label' => $viewfeedbackstring, 'role' => 'menuitem', 'data-action' => 'feedback',
2538 'data-courseid' => $this->courseid
]);
2540 } else if ($mode == 'user') {
2541 $context->datatype
= 'user';
2542 $context = grade_report
::get_additional_context($this->context
, $this->courseid
, $element, $gpr, $mode, $context, true);
2543 $context->dataid
= $element['userid'];
2546 // Omit the second divider if there is nothing between it and the first divider.
2547 if (!isset($context->ascendingfirstnameurl
) && !isset($context->ascendingurl
)) {
2548 $context->divider2
= false;
2551 if ($mode == 'setup') {
2552 $context->databoundary
= 'window';
2555 if (!empty($USER->editing
) ||
isset($context->gradeanalysisurl
) ||
isset($context->gradesonlyurl
)
2556 ||
isset($context->aggregatesonlyurl
) ||
isset($context->fullmodeurl
) ||
isset($context->reporturl0
)
2557 ||
isset($context->ascendingfirstnameurl
) ||
isset($context->ascendingurl
)
2558 ||
isset($context->viewfeedbackurl
) ||
($mode == 'setup')) {
2559 return $OUTPUT->render_from_template('core_grades/cellmenu', $context);
2565 * Returns link to sort grade item column
2567 * @param moodle_url $sortlink A base link for sorting
2568 * @param object $gpr A grade_plugin_return object
2569 * @param string $direction Direction od sorting
2572 public function get_sorting_link(moodle_url
$sortlink, object $gpr, string $direction = 'asc'): string {
2574 if ($direction == 'asc') {
2575 $title = get_string('asc');
2577 $title = get_string('desc');
2580 $sortlink->param('sort', $direction);
2581 $gpr->add_url_params($sortlink);
2582 return html_writer
::link($sortlink, $title,
2583 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2589 * Flat structure similar to grade tree.
2591 * @uses grade_structure
2592 * @package core_grades
2593 * @copyright 2009 Nicolas Connault
2594 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2596 class grade_seq
extends grade_structure
{
2599 * 1D array of elements
2604 * Constructor, retrieves and stores array of all grade_category and grade_item
2605 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2607 * @param int $courseid The course id
2608 * @param bool $category_grade_last category grade item is the last child
2609 * @param bool $nooutcomes Whether or not outcomes should be included
2611 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2614 $this->courseid
= $courseid;
2615 $this->context
= context_course
::instance($courseid);
2617 // get course grade tree
2618 $top_element = grade_category
::fetch_course_tree($courseid, true);
2620 $this->elements
= grade_seq
::flatten($top_element, $category_grade_last, $nooutcomes);
2622 foreach ($this->elements
as $key=>$unused) {
2623 $this->items
[$this->elements
[$key]['object']->id
] =& $this->elements
[$key]['object'];
2628 * Old syntax of class constructor. Deprecated in PHP7.
2630 * @deprecated since Moodle 3.1
2632 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2633 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2634 self
::__construct($courseid, $category_grade_last, $nooutcomes);
2638 * Static recursive helper - makes the grade_item for category the last children
2640 * @param array &$element The seed of the recursion
2641 * @param bool $category_grade_last category grade item is the last child
2642 * @param bool $nooutcomes Whether or not outcomes should be included
2646 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2647 if (empty($element['children'])) {
2650 $children = array();
2652 foreach ($element['children'] as $sortorder=>$unused) {
2653 if ($nooutcomes and $element['type'] != 'category' and
2654 $element['children'][$sortorder]['object']->is_outcome_item()) {
2657 $children[] = $element['children'][$sortorder];
2659 unset($element['children']);
2661 if ($category_grade_last and count($children) > 1 and
2663 $children[0]['type'] === 'courseitem' or
2664 $children[0]['type'] === 'categoryitem'
2667 $cat_item = array_shift($children);
2668 array_push($children, $cat_item);
2672 foreach ($children as $child) {
2673 if ($child['type'] == 'category') {
2674 $result = $result + grade_seq
::flatten($child, $category_grade_last, $nooutcomes);
2676 $child['eid'] = 'i'.$child['object']->id
;
2677 $result[$child['object']->id
] = $child;
2685 * Parses the array in search of a given eid and returns a element object with
2686 * information about the element it has found.
2688 * @param int $eid Gradetree Element ID
2690 * @return object element
2692 public function locate_element($eid) {
2693 // it is a grade - construct a new object
2694 if (strpos($eid, 'n') === 0) {
2695 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2699 $itemid = $matches[1];
2700 $userid = $matches[2];
2702 //extra security check - the grade item must be in this tree
2703 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2707 // $gradea->id may be null - means does not exist yet
2708 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2710 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2711 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2713 } else if (strpos($eid, 'g') === 0) {
2714 $id = (int) substr($eid, 1);
2715 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
2718 //extra security check - the grade item must be in this tree
2719 if (!$item_el = $this->locate_element('ig'.$grade->itemid
)) {
2722 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2723 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2726 // it is a category or item
2727 foreach ($this->elements
as $element) {
2728 if ($element['eid'] == $eid) {
2738 * This class represents a complete tree of categories, grade_items and final grades,
2739 * organises as an array primarily, but which can also be converted to other formats.
2740 * It has simple method calls with complex implementations, allowing for easy insertion,
2741 * deletion and moving of items and categories within the tree.
2743 * @uses grade_structure
2744 * @package core_grades
2745 * @copyright 2009 Nicolas Connault
2746 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2748 class grade_tree
extends grade_structure
{
2751 * The basic representation of the tree as a hierarchical, 3-tiered array.
2752 * @var object $top_element
2754 public $top_element;
2757 * 2D array of grade items and categories
2758 * @var array $levels
2769 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2770 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2772 * @param int $courseid The Course ID
2773 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2774 * @param bool $category_grade_last category grade item is the last child
2775 * @param array $collapsed array of collapsed categories
2776 * @param bool $nooutcomes Whether or not outcomes should be included
2778 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2779 $collapsed=null, $nooutcomes=false) {
2780 global $USER, $CFG, $COURSE, $DB;
2782 $this->courseid
= $courseid;
2783 $this->levels
= array();
2784 $this->context
= context_course
::instance($courseid);
2786 if (!empty($COURSE->id
) && $COURSE->id
== $this->courseid
) {
2789 $course = $DB->get_record('course', array('id' => $this->courseid
));
2791 $this->modinfo
= get_fast_modinfo($course);
2793 // get course grade tree
2794 $this->top_element
= grade_category
::fetch_course_tree($courseid, true);
2796 // collapse the categories if requested
2797 if (!empty($collapsed)) {
2798 grade_tree
::category_collapse($this->top_element
, $collapsed);
2801 // no otucomes if requested
2802 if (!empty($nooutcomes)) {
2803 grade_tree
::no_outcomes($this->top_element
);
2806 // move category item to last position in category
2807 if ($category_grade_last) {
2808 grade_tree
::category_grade_last($this->top_element
);
2812 // inject fake categories == fillers
2813 grade_tree
::inject_fillers($this->top_element
, 0);
2814 // add colspans to categories and fillers
2815 grade_tree
::inject_colspans($this->top_element
);
2818 grade_tree
::fill_levels($this->levels
, $this->top_element
, 0);
2823 * Old syntax of class constructor. Deprecated in PHP7.
2825 * @deprecated since Moodle 3.1
2827 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2828 $collapsed=null, $nooutcomes=false) {
2829 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2830 self
::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2834 * Static recursive helper - removes items from collapsed categories
2836 * @param array &$element The seed of the recursion
2837 * @param array $collapsed array of collapsed categories
2841 public function category_collapse(&$element, $collapsed) {
2842 if ($element['type'] != 'category') {
2845 if (empty($element['children']) or count($element['children']) < 2) {
2849 if (in_array($element['object']->id
, $collapsed['aggregatesonly'])) {
2850 $category_item = reset($element['children']); //keep only category item
2851 $element['children'] = array(key($element['children'])=>$category_item);
2854 if (in_array($element['object']->id
, $collapsed['gradesonly'])) { // Remove category item
2855 reset($element['children']);
2856 $first_key = key($element['children']);
2857 unset($element['children'][$first_key]);
2859 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2860 grade_tree
::category_collapse($element['children'][$sortorder], $collapsed);
2866 * Static recursive helper - removes all outcomes
2868 * @param array &$element The seed of the recursion
2872 public function no_outcomes(&$element) {
2873 if ($element['type'] != 'category') {
2876 foreach ($element['children'] as $sortorder=>$child) {
2877 if ($element['children'][$sortorder]['type'] == 'item'
2878 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2879 unset($element['children'][$sortorder]);
2881 } else if ($element['children'][$sortorder]['type'] == 'category') {
2882 grade_tree
::no_outcomes($element['children'][$sortorder]);
2888 * Static recursive helper - makes the grade_item for category the last children
2890 * @param array &$element The seed of the recursion
2894 public function category_grade_last(&$element) {
2895 if (empty($element['children'])) {
2898 if (count($element['children']) < 2) {
2901 $first_item = reset($element['children']);
2902 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2903 // the category item might have been already removed
2904 $order = key($element['children']);
2905 unset($element['children'][$order]);
2906 $element['children'][$order] =& $first_item;
2908 foreach ($element['children'] as $sortorder => $child) {
2909 grade_tree
::category_grade_last($element['children'][$sortorder]);
2914 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2916 * @param array &$levels The levels of the grade tree through which to recurse
2917 * @param array &$element The seed of the recursion
2918 * @param int $depth How deep are we?
2921 public function fill_levels(&$levels, &$element, $depth) {
2922 if (!array_key_exists($depth, $levels)) {
2923 $levels[$depth] = array();
2926 // prepare unique identifier
2927 if ($element['type'] == 'category') {
2928 $element['eid'] = 'cg'.$element['object']->id
;
2929 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2930 $element['eid'] = 'ig'.$element['object']->id
;
2931 $this->items
[$element['object']->id
] =& $element['object'];
2934 $levels[$depth][] =& $element;
2936 if (empty($element['children'])) {
2940 foreach ($element['children'] as $sortorder=>$child) {
2941 grade_tree
::fill_levels($levels, $element['children'][$sortorder], $depth);
2942 $element['children'][$sortorder]['prev'] = $prev;
2943 $element['children'][$sortorder]['next'] = 0;
2945 $element['children'][$prev]['next'] = $sortorder;
2952 * Determines whether the grade tree item can be displayed.
2953 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2954 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2957 * @param array $element The grade category element.
2958 * @return bool True if the grade tree item can be displayed. False, otherwise.
2960 public static function can_output_item($element) {
2963 if ($element['type'] === 'category') {
2964 $object = $element['object'];
2965 $category = grade_category
::fetch(array('id' => $object->id
));
2966 // Category has total, we can output this.
2967 if ($category->get_grade_item()->gradetype
!= GRADE_TYPE_NONE
) {
2971 // Category has no total and has no children, no need to output this.
2972 if (empty($element['children'])) {
2977 // Loop over children and make sure at least one child can be output.
2978 foreach ($element['children'] as $child) {
2979 $canoutput = self
::can_output_item($child);
2990 * Static recursive helper - makes full tree (all leafes are at the same level)
2992 * @param array &$element The seed of the recursion
2993 * @param int $depth How deep are we?
2997 public function inject_fillers(&$element, $depth) {
3000 if (empty($element['children'])) {
3003 $chdepths = array();
3004 $chids = array_keys($element['children']);
3005 $last_child = end($chids);
3006 $first_child = reset($chids);
3008 foreach ($chids as $chid) {
3009 $chdepths[$chid] = grade_tree
::inject_fillers($element['children'][$chid], $depth);
3013 $maxdepth = reset($chdepths);
3014 foreach ($chdepths as $chid=>$chd) {
3015 if ($chd == $maxdepth) {
3018 if (!self
::can_output_item($element['children'][$chid])) {
3021 for ($i=0; $i < $maxdepth-$chd; $i++
) {
3022 if ($chid == $first_child) {
3023 $type = 'fillerfirst';
3024 } else if ($chid == $last_child) {
3025 $type = 'fillerlast';
3029 $oldchild =& $element['children'][$chid];
3030 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
3031 'eid'=>'', 'depth'=>$element['object']->depth
,
3032 'children'=>array($oldchild));
3040 * Static recursive helper - add colspan information into categories
3042 * @param array &$element The seed of the recursion
3046 public function inject_colspans(&$element) {
3047 if (empty($element['children'])) {
3051 foreach ($element['children'] as $key=>$child) {
3052 if (!self
::can_output_item($child)) {
3055 $count +
= grade_tree
::inject_colspans($element['children'][$key]);
3057 $element['colspan'] = $count;
3062 * Parses the array in search of a given eid and returns a element object with
3063 * information about the element it has found.
3064 * @param int $eid Gradetree Element ID
3065 * @return object element
3067 public function locate_element($eid) {
3068 // it is a grade - construct a new object
3069 if (strpos($eid, 'n') === 0) {
3070 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
3074 $itemid = $matches[1];
3075 $userid = $matches[2];
3077 //extra security check - the grade item must be in this tree
3078 if (!$item_el = $this->locate_element('ig'.$itemid)) {
3082 // $gradea->id may be null - means does not exist yet
3083 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
3085 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
3086 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
3088 } else if (strpos($eid, 'g') === 0) {
3089 $id = (int) substr($eid, 1);
3090 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
3093 //extra security check - the grade item must be in this tree
3094 if (!$item_el = $this->locate_element('ig'.$grade->itemid
)) {
3097 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
3098 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
3101 // it is a category or item
3102 foreach ($this->levels
as $row) {
3103 foreach ($row as $element) {
3104 if ($element['type'] == 'filler') {
3107 if ($element['eid'] == $eid) {
3117 * Returns a well-formed XML representation of the grade-tree using recursion.
3119 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3120 * @param string $tabs The control character to use for tabs
3122 * @return string $xml
3124 public function exporttoxml($root=null, $tabs="\t") {
3127 if (is_null($root)) {
3128 $root = $this->top_element
;
3129 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
3130 $xml .= "<gradetree>\n";
3134 $type = 'undefined';
3135 if (strpos($root['object']->table
, 'grade_categories') !== false) {
3137 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
3139 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
3143 $xml .= "$tabs<element type=\"$type\">\n";
3144 foreach ($root['object'] as $var => $value) {
3145 if (!is_object($value) && !is_array($value) && !empty($value)) {
3146 $xml .= "$tabs\t<$var>$value</$var>\n";
3150 if (!empty($root['children'])) {
3151 $xml .= "$tabs\t<children>\n";
3152 foreach ($root['children'] as $sortorder => $child) {
3153 $xml .= $this->exportToXML($child, $tabs."\t\t");
3155 $xml .= "$tabs\t</children>\n";
3158 $xml .= "$tabs</element>\n";
3161 $xml .= "</gradetree>";
3168 * Returns a JSON representation of the grade-tree using recursion.
3170 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3171 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
3175 public function exporttojson($root=null, $tabs="\t") {
3178 if (is_null($root)) {
3179 $root = $this->top_element
;
3186 if (strpos($root['object']->table
, 'grade_categories') !== false) {
3187 $name = $root['object']->fullname
;
3189 $name = $root['object']->get_name();
3191 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
3192 $name = $root['object']->itemname
;
3193 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
3194 $name = $root['object']->itemname
;
3197 $json .= "$tabs {\n";
3198 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
3199 $json .= "$tabs\t \"name\": \"$name\",\n";
3201 foreach ($root['object'] as $var => $value) {
3202 if (!is_object($value) && !is_array($value) && !empty($value)) {
3203 $json .= "$tabs\t \"$var\": \"$value\",\n";
3207 $json = substr($json, 0, strrpos($json, ','));
3209 if (!empty($root['children'])) {
3210 $json .= ",\n$tabs\t\"children\": [\n";
3211 foreach ($root['children'] as $sortorder => $child) {
3212 $json .= $this->exportToJSON($child, $tabs."\t\t");
3214 $json = substr($json, 0, strrpos($json, ','));
3215 $json .= "\n$tabs\t]\n";
3221 $json .= "\n$tabs},\n";
3228 * Returns the array of levels
3232 public function get_levels() {
3233 return $this->levels
;
3237 * Returns the array of grade items
3241 public function get_items() {
3242 return $this->items
;
3246 * Returns a specific Grade Item
3248 * @param int $itemid The ID of the grade_item object
3250 * @return grade_item
3252 public function get_item($itemid) {
3253 if (array_key_exists($itemid, $this->items
)) {
3254 return $this->items
[$itemid];
3262 * Local shortcut function for creating an edit/delete button for a grade_* object.
3263 * @param string $type 'edit' or 'delete'
3264 * @param int $courseid The Course ID
3265 * @param grade_* $object The grade_* object
3266 * @return string html
3268 function grade_button($type, $courseid, $object) {
3269 global $CFG, $OUTPUT;
3270 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
3271 $objectidstring = $matches[1] . 'id';
3273 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
3276 $strdelete = get_string('delete');
3277 $stredit = get_string('edit');
3279 if ($type == 'delete') {
3280 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id
, 'action' => 'delete', 'sesskey' => sesskey()));
3281 } else if ($type == 'edit') {
3282 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id
));
3285 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $
{'str'.$type}, '', array('class' => 'iconsmall')));
3290 * This method adds settings to the settings block for the grade system and its
3293 * @global moodle_page $PAGE
3295 function grade_extend_settings($plugininfo, $courseid) {
3298 $gradenode = $PAGE->settingsnav
->prepend(get_string('gradeadministration', 'grades'), null, navigation_node
::TYPE_CONTAINER
,
3299 null, 'gradeadmin');
3301 $strings = array_shift($plugininfo);
3303 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
3304 foreach ($reports as $report) {
3305 $gradenode->add($report->string, $report->link
, navigation_node
::TYPE_SETTING
, null, $report->id
, new pix_icon('i/report', ''));
3309 if ($settings = grade_helper
::get_info_manage_settings($courseid)) {
3310 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node
::TYPE_CONTAINER
);
3311 foreach ($settings as $setting) {
3312 $settingsnode->add($setting->string, $setting->link
, navigation_node
::TYPE_SETTING
, null, $setting->id
, new pix_icon('i/settings', ''));
3316 if ($imports = grade_helper
::get_plugins_import($courseid)) {
3317 $importnode = $gradenode->add($strings['import'], null, navigation_node
::TYPE_CONTAINER
);
3318 foreach ($imports as $import) {
3319 $importnode->add($import->string, $import->link
, navigation_node
::TYPE_SETTING
, null, $import->id
, new pix_icon('i/import', ''));
3323 if ($exports = grade_helper
::get_plugins_export($courseid)) {
3324 $exportnode = $gradenode->add($strings['export'], null, navigation_node
::TYPE_CONTAINER
);
3325 foreach ($exports as $export) {
3326 $exportnode->add($export->string, $export->link
, navigation_node
::TYPE_SETTING
, null, $export->id
, new pix_icon('i/export', ''));
3330 if ($letters = grade_helper
::get_info_letters($courseid)) {
3331 $letters = array_shift($letters);
3332 $gradenode->add($strings['letter'], $letters->link
, navigation_node
::TYPE_SETTING
, null, $letters->id
, new pix_icon('i/settings', ''));
3335 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
3336 $outcomes = array_shift($outcomes);
3337 $gradenode->add($strings['outcome'], $outcomes->link
, navigation_node
::TYPE_SETTING
, null, $outcomes->id
, new pix_icon('i/outcomes', ''));
3340 if ($scales = grade_helper
::get_info_scales($courseid)) {
3341 $gradenode->add($strings['scale'], $scales->link
, navigation_node
::TYPE_SETTING
, null, $scales->id
, new pix_icon('i/scales', ''));
3344 if ($gradenode->contains_active_node()) {
3345 // If the gradenode is active include the settings base node (gradeadministration) in
3346 // the navbar, typcially this is ignored.
3347 $PAGE->navbar
->includesettingsbase
= true;
3349 // If we can get the course admin node make sure it is closed by default
3350 // as in this case the gradenode will be opened
3351 if ($coursenode = $PAGE->settingsnav
->get('courseadmin', navigation_node
::TYPE_COURSE
)){
3352 $coursenode->make_inactive();
3353 $coursenode->forceopen
= false;
3359 * Grade helper class
3361 * This class provides several helpful functions that work irrespective of any
3364 * @copyright 2010 Sam Hemelryk
3365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3367 abstract class grade_helper
{
3369 * Cached manage settings info {@see get_info_settings}
3370 * @var grade_plugin_info|false
3372 protected static $managesetting = null;
3374 * Cached grade report plugins {@see get_plugins_reports}
3377 protected static $gradereports = null;
3379 * Cached grade report plugins preferences {@see get_info_scales}
3382 protected static $gradereportpreferences = null;
3384 * Cached scale info {@see get_info_scales}
3385 * @var grade_plugin_info|false
3387 protected static $scaleinfo = null;
3389 * Cached outcome info {@see get_info_outcomes}
3390 * @var grade_plugin_info|false
3392 protected static $outcomeinfo = null;
3394 * Cached leftter info {@see get_info_letters}
3395 * @var grade_plugin_info|false
3397 protected static $letterinfo = null;
3399 * Cached grade import plugins {@see get_plugins_import}
3402 protected static $importplugins = null;
3404 * Cached grade export plugins {@see get_plugins_export}
3407 protected static $exportplugins = null;
3409 * Cached grade plugin strings
3412 protected static $pluginstrings = null;
3414 * Cached grade aggregation strings
3417 protected static $aggregationstrings = null;
3420 * Cached grade tree plugin strings
3423 protected static $langstrings = [];
3426 * First checks the cached language strings, then returns match if found, or uses get_string()
3427 * to get it from the DB, caches it then returns it.
3429 * @deprecated since 4.3
3430 * @todo MDL-78780 This will be deleted in Moodle 4.7.
3431 * @param string $strcode
3432 * @param string|null $section Optional language section
3435 public static function get_lang_string(string $strcode, ?
string $section = null): string {
3436 debugging('grade_helper::get_lang_string() is deprecated, please use' .
3437 ' get_string() instead.', DEBUG_DEVELOPER
);
3439 if (empty(self
::$langstrings[$strcode])) {
3440 self
::$langstrings[$strcode] = get_string($strcode, $section);
3442 return self
::$langstrings[$strcode];
3446 * Gets strings commonly used by the describe plugins
3448 * report => get_string('view'),
3449 * scale => get_string('scales'),
3450 * outcome => get_string('outcomes', 'grades'),
3451 * letter => get_string('letters', 'grades'),
3452 * export => get_string('export', 'grades'),
3453 * import => get_string('import'),
3454 * settings => get_string('settings')
3458 public static function get_plugin_strings() {
3459 if (self
::$pluginstrings === null) {
3460 self
::$pluginstrings = array(
3461 'report' => get_string('view'),
3462 'scale' => get_string('scales'),
3463 'outcome' => get_string('outcomes', 'grades'),
3464 'letter' => get_string('letters', 'grades'),
3465 'export' => get_string('export', 'grades'),
3466 'import' => get_string('import'),
3467 'settings' => get_string('edittree', 'grades')
3470 return self
::$pluginstrings;
3474 * Gets strings describing the available aggregation methods.
3478 public static function get_aggregation_strings() {
3479 if (self
::$aggregationstrings === null) {
3480 self
::$aggregationstrings = array(
3481 GRADE_AGGREGATE_MEAN
=> get_string('aggregatemean', 'grades'),
3482 GRADE_AGGREGATE_WEIGHTED_MEAN
=> get_string('aggregateweightedmean', 'grades'),
3483 GRADE_AGGREGATE_WEIGHTED_MEAN2
=> get_string('aggregateweightedmean2', 'grades'),
3484 GRADE_AGGREGATE_EXTRACREDIT_MEAN
=> get_string('aggregateextracreditmean', 'grades'),
3485 GRADE_AGGREGATE_MEDIAN
=> get_string('aggregatemedian', 'grades'),
3486 GRADE_AGGREGATE_MIN
=> get_string('aggregatemin', 'grades'),
3487 GRADE_AGGREGATE_MAX
=> get_string('aggregatemax', 'grades'),
3488 GRADE_AGGREGATE_MODE
=> get_string('aggregatemode', 'grades'),
3489 GRADE_AGGREGATE_SUM
=> get_string('aggregatesum', 'grades')
3492 return self
::$aggregationstrings;
3496 * Get grade_plugin_info object for managing settings if the user can
3498 * @param int $courseid
3499 * @return grade_plugin_info[]
3501 public static function get_info_manage_settings($courseid) {
3502 if (self
::$managesetting !== null) {
3503 return self
::$managesetting;
3505 $context = context_course
::instance($courseid);
3506 self
::$managesetting = array();
3507 if ($courseid != SITEID
&& has_capability('moodle/grade:manage', $context)) {
3508 self
::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
3509 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
3510 get_string('gradebooksetup', 'grades'));
3511 self
::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3512 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3513 get_string('coursegradesettings', 'grades'));
3515 if (self
::$gradereportpreferences === null) {
3516 self
::get_plugins_reports($courseid);
3518 if (self
::$gradereportpreferences) {
3519 self
::$managesetting = array_merge(self
::$managesetting, self
::$gradereportpreferences);
3521 return self
::$managesetting;
3524 * Returns an array of plugin reports as grade_plugin_info objects
3526 * @param int $courseid
3529 public static function get_plugins_reports($courseid) {
3532 if (self
::$gradereports !== null) {
3533 return self
::$gradereports;
3535 $context = context_course
::instance($courseid);
3536 $gradereports = array();
3537 $gradepreferences = array();
3538 foreach (core_component
::get_plugin_list('gradereport') as $plugin => $plugindir) {
3539 //some reports make no sense if we're not within a course
3540 if ($courseid==$SITE->id
&& ($plugin=='grader' ||
$plugin=='user')) {
3544 // Remove outcomes report if outcomes not enabled.
3545 if ($plugin === 'outcomes' && empty($CFG->enableoutcomes
)) {
3549 // Remove ones we can't see
3550 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3554 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3555 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3556 'moodle/grade:edit'), $context)) {
3560 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
3561 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3562 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3564 // Add link to preferences tab if such a page exists
3565 if (file_exists($plugindir.'/preferences.php')) {
3566 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id' => $courseid));
3567 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
3568 get_string('preferences', 'grades') . ': ' . $pluginstr);
3571 if (count($gradereports) == 0) {
3572 $gradereports = false;
3573 $gradepreferences = false;
3574 } else if (count($gradepreferences) == 0) {
3575 $gradepreferences = false;
3576 asort($gradereports);
3578 asort($gradereports);
3579 asort($gradepreferences);
3581 self
::$gradereports = $gradereports;
3582 self
::$gradereportpreferences = $gradepreferences;
3583 return self
::$gradereports;
3587 * Get information on scales
3588 * @param int $courseid
3589 * @return grade_plugin_info
3591 public static function get_info_scales($courseid) {
3592 if (self
::$scaleinfo !== null) {
3593 return self
::$scaleinfo;
3595 if (has_capability('moodle/course:managescales', context_course
::instance($courseid))) {
3596 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3597 self
::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3599 self
::$scaleinfo = false;
3601 return self
::$scaleinfo;
3604 * Get information on outcomes
3605 * @param int $courseid
3606 * @return grade_plugin_info[]|false
3608 public static function get_info_outcomes($courseid) {
3611 if (self
::$outcomeinfo !== null) {
3612 return self
::$outcomeinfo;
3614 $context = context_course
::instance($courseid);
3615 $canmanage = has_capability('moodle/grade:manage', $context);
3616 $canupdate = has_capability('moodle/course:update', $context);
3617 if (!empty($CFG->enableoutcomes
) && ($canmanage ||
$canupdate)) {
3618 $outcomes = array();
3620 if ($courseid!=$SITE->id
) {
3621 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3622 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3624 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3625 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3626 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3627 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3629 if ($courseid!=$SITE->id
) {
3630 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3631 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3634 self
::$outcomeinfo = $outcomes;
3636 self
::$outcomeinfo = false;
3638 return self
::$outcomeinfo;
3641 * Get information on letters
3642 * @param int $courseid
3645 public static function get_info_letters($courseid) {
3647 if (self
::$letterinfo !== null) {
3648 return self
::$letterinfo;
3650 $context = context_course
::instance($courseid);
3651 $canmanage = has_capability('moodle/grade:manage', $context);
3652 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3653 if ($canmanage ||
$canmanageletters) {
3654 // Redirect to system context when report is accessed from admin settings MDL-31633
3655 if ($context->instanceid
== $SITE->id
) {
3656 $param = array('edit' => 1);
3658 $param = array('edit' => 1,'id' => $context->id
);
3660 self
::$letterinfo = array(
3661 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id
)), get_string('view')),
3662 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3665 self
::$letterinfo = false;
3667 return self
::$letterinfo;
3670 * Get information import plugins
3671 * @param int $courseid
3674 public static function get_plugins_import($courseid) {
3677 if (self
::$importplugins !== null) {
3678 return self
::$importplugins;
3680 $importplugins = array();
3681 $context = context_course
::instance($courseid);
3683 if (has_capability('moodle/grade:import', $context)) {
3684 foreach (core_component
::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3685 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3688 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3689 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3690 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3693 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3694 // XML is the only grade import plugin that has publishing feature.
3695 if ($CFG->gradepublishing
&& has_capability('gradeimport/xml:publish', $context)) {
3696 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3697 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3701 if (count($importplugins) > 0) {
3702 asort($importplugins);
3703 self
::$importplugins = $importplugins;
3705 self
::$importplugins = false;
3707 return self
::$importplugins;
3710 * Get information export plugins
3711 * @param int $courseid
3714 public static function get_plugins_export($courseid) {
3717 if (self
::$exportplugins !== null) {
3718 return self
::$exportplugins;
3720 $context = context_course
::instance($courseid);
3721 $exportplugins = array();
3722 $canpublishgrades = 0;
3723 if (has_capability('moodle/grade:export', $context)) {
3724 foreach (core_component
::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3725 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3728 // All the grade export plugins has grade publishing capabilities.
3729 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3730 $canpublishgrades++
;
3733 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3734 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3735 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3738 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3739 if ($CFG->gradepublishing
&& $canpublishgrades != 0) {
3740 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3741 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3744 if (count($exportplugins) > 0) {
3745 asort($exportplugins);
3746 self
::$exportplugins = $exportplugins;
3748 self
::$exportplugins = false;
3750 return self
::$exportplugins;
3754 * Returns the value of a field from a user record
3756 * @param stdClass $user object
3757 * @param stdClass $field object
3758 * @return string value of the field
3760 public static function get_user_field_value($user, $field) {
3761 if (!empty($field->customid
)) {
3762 $fieldname = 'customfield_' . $field->customid
;
3763 if (!empty($user->{$fieldname}) ||
is_numeric($user->{$fieldname})) {
3764 $fieldvalue = $user->{$fieldname};
3766 $fieldvalue = $field->default;
3769 $fieldvalue = $user->{$field->shortname
};
3775 * Returns an array of user profile fields to be included in export
3777 * @param int $courseid
3778 * @param bool $includecustomfields
3779 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3781 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3784 // Gets the fields that have to be hidden
3785 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields
));
3786 $context = context_course
::instance($courseid);
3787 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3788 if ($canseehiddenfields) {
3789 $hiddenfields = array();
3793 require_once($CFG->dirroot
.'/user/lib.php'); // Loads user_get_default_fields()
3794 require_once($CFG->dirroot
.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3795 $userdefaultfields = user_get_default_fields();
3797 // Sets the list of profile fields
3798 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields
));
3799 if (!empty($userprofilefields)) {
3800 foreach ($userprofilefields as $field) {
3801 $field = trim($field);
3802 if (in_array($field, $hiddenfields) ||
!in_array($field, $userdefaultfields)) {
3805 $obj = new stdClass();
3807 $obj->shortname
= $field;
3808 $obj->fullname
= get_string($field);
3813 // Sets the list of custom profile fields
3814 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields
));
3815 if ($includecustomfields && !empty($customprofilefields)) {
3816 $customfields = profile_get_user_fields_with_data(0);
3818 foreach ($customfields as $fieldobj) {
3819 $field = (object)$fieldobj->get_field_config_for_external();
3820 // Make sure we can display this custom field
3821 if (!in_array($field->shortname
, $customprofilefields)) {
3823 } else if (in_array($field->shortname
, $hiddenfields)) {
3825 } else if ($field->visible
!= PROFILE_VISIBLE_ALL
&& !$canseehiddenfields) {
3829 $obj = new stdClass();
3830 $obj->customid
= $field->id
;
3831 $obj->shortname
= $field->shortname
;
3832 $obj->fullname
= format_string($field->name
);
3833 $obj->datatype
= $field->datatype
;
3834 $obj->default = $field->defaultdata
;
3843 * This helper method gets a snapshot of all the weights for a course.
3844 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3845 * @param int $courseid
3846 * @return array of itemid -> aggregationcoef2
3848 public static function fetch_all_natural_weights_for_course($courseid) {
3852 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3853 foreach ($records as $record) {
3854 $result[$record->id
] = $record->aggregationcoef2
;
3860 * Resets all static caches.
3864 public static function reset_caches() {
3865 self
::$managesetting = null;
3866 self
::$gradereports = null;
3867 self
::$gradereportpreferences = null;
3868 self
::$scaleinfo = null;
3869 self
::$outcomeinfo = null;
3870 self
::$letterinfo = null;
3871 self
::$importplugins = null;
3872 self
::$exportplugins = null;
3873 self
::$pluginstrings = null;
3874 self
::$aggregationstrings = null;
3878 * Returns icon of element
3880 * @param array $element An array representing an element in the grade_tree
3881 * @param bool $spacerifnone return spacer if no icon found
3883 * @return string icon or spacer
3885 public static function get_element_icon(array $element, bool $spacerifnone = false): string {
3886 global $CFG, $OUTPUT;
3887 require_once($CFG->libdir
. '/filelib.php');
3891 // Object holding pix_icon information before instantiation.
3892 $icon = new stdClass();
3893 $icon->attributes
= ['class' => 'icon itemicon'];
3894 $icon->component
= 'moodle';
3897 switch ($element['type']) {
3900 case 'categoryitem':
3903 $iscourse = $element['object']->is_course_item();
3904 $iscategory = $element['object']->is_category_item();
3905 $isscale = $element['object']->gradetype
== GRADE_TYPE_SCALE
;
3906 $isvalue = $element['object']->gradetype
== GRADE_TYPE_VALUE
;
3907 $isoutcome = !empty($element['object']->outcomeid
);
3909 if ($element['object']->is_calculated()) {
3910 $icon->pix
= 'i/calc';
3911 $icon->title
= s(get_string('calculatedgrade', 'grades'));
3913 } else if (($iscourse ||
$iscategory) && ($isscale ||
$isvalue)) {
3914 if ($category = $element['object']->get_item_category()) {
3915 $aggrstrings = self
::get_aggregation_strings();
3916 $stragg = $aggrstrings[$category->aggregation
];
3918 $icon->pix
= 'i/calc';
3919 $icon->title
= s($stragg);
3921 switch ($category->aggregation
) {
3922 case GRADE_AGGREGATE_MEAN
:
3923 case GRADE_AGGREGATE_MEDIAN
:
3924 case GRADE_AGGREGATE_WEIGHTED_MEAN
:
3925 case GRADE_AGGREGATE_WEIGHTED_MEAN2
:
3926 case GRADE_AGGREGATE_EXTRACREDIT_MEAN
:
3927 $icon->pix
= 'i/agg_mean';
3929 case GRADE_AGGREGATE_SUM
:
3930 $icon->pix
= 'i/agg_sum';
3935 } else if ($element['object']->itemtype
== 'mod') {
3936 // Prevent outcomes displaying the same icon as the activity they are attached to.
3938 $icon->pix
= 'i/outcomes';
3939 $icon->title
= s(get_string('outcome', 'grades'));
3941 $modinfo = get_fast_modinfo($element['object']->courseid
);
3942 $module = $element['object']->itemmodule
;
3943 $instanceid = $element['object']->iteminstance
;
3944 if (isset($modinfo->instances
[$module][$instanceid])) {
3945 $icon->url
= $modinfo->instances
[$module][$instanceid]->get_icon_url();
3947 $icon->pix
= 'monologo';
3948 $icon->component
= $element['object']->itemmodule
;
3950 $icon->title
= s(get_string('modulename', $element['object']->itemmodule
));
3952 } else if ($element['object']->itemtype
== 'manual') {
3953 if ($element['object']->is_outcome_item()) {
3954 $icon->pix
= 'i/outcomes';
3955 $icon->title
= s(get_string('outcome', 'grades'));
3957 $icon->pix
= 'i/manual_item';
3958 $icon->title
= s(get_string('manualitem', 'grades'));
3965 $icon->pix
= 'i/folder';
3966 $icon->title
= s(get_string('category', 'grades'));
3971 if ($spacerifnone) {
3972 $outputstr = $OUTPUT->spacer() . ' ';
3974 } else if (isset($icon->url
)) {
3975 $outputstr = html_writer
::img($icon->url
, $icon->title
, $icon->attributes
);
3977 $outputstr = $OUTPUT->pix_icon($icon->pix
, $icon->title
, $icon->component
, $icon->attributes
);
3984 * Returns the string that describes the type of the element.
3986 * @param array $element An array representing an element in the grade_tree
3987 * @return string The string that describes the type of the grade element
3989 public static function get_element_type_string(array $element): string {
3990 // If the element is a grade category.
3991 if ($element['type'] == 'category') {
3992 return get_string('category', 'grades');
3994 // If the element is a grade item.
3995 if (in_array($element['type'], ['item', 'courseitem', 'categoryitem'])) {
3996 // If calculated grade item.
3997 if ($element['object']->is_calculated()) {
3998 return get_string('calculatedgrade', 'grades');
4000 // If aggregated type grade item.
4001 if ($element['object']->is_aggregate_item()) {
4002 return get_string('aggregation', 'core_grades');
4004 // If external grade item (module, plugin, etc.).
4005 if ($element['object']->is_external_item()) {
4006 // If outcome grade item.
4007 if ($element['object']->is_outcome_item()) {
4008 return get_string('outcome', 'grades');
4010 return get_string('modulename', $element['object']->itemmodule
);
4012 // If manual grade item.
4013 if ($element['object']->itemtype
== 'manual') {
4014 // If outcome grade item.
4015 if ($element['object']->is_outcome_item()) {
4016 return get_string('outcome', 'grades');
4018 return get_string('manualitem', 'grades');
4026 * Returns name of element optionally with icon and link
4028 * @param array $element An array representing an element in the grade_tree
4029 * @param bool $withlink Whether or not this header has a link
4030 * @param bool $icon Whether or not to display an icon with this header
4031 * @param bool $spacerifnone return spacer if no icon found
4032 * @param bool $withdescription Show description if defined by this item.
4033 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
4034 * instead of "Category total" or "Course total"
4035 * @param moodle_url|null $sortlink Link to sort column.
4037 * @return string header
4039 public static function get_element_header(array $element, bool $withlink = false, bool $icon = true,
4040 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
4041 ?moodle_url
$sortlink = null): string {
4045 $header .= self
::get_element_icon($element, $spacerifnone);
4048 $title = $element['object']->get_name($fulltotal);
4049 $titleunescaped = $element['object']->get_name($fulltotal, false);
4052 if ($element['type'] != 'item' && $element['type'] != 'categoryitem' && $element['type'] != 'courseitem') {
4058 $header = html_writer
::link($url, $header, [
4059 'title' => $titleunescaped,
4060 'class' => 'gradeitemheader ',
4063 if ($withlink && $url = self
::get_activity_link($element)) {
4064 $a = new stdClass();
4065 $a->name
= get_string('modulename', $element['object']->itemmodule
);
4066 $a->title
= $titleunescaped;
4067 $title = get_string('linktoactivity', 'grades', $a);
4068 $header = html_writer
::link($url, $header, [
4070 'class' => 'gradeitemheader ',
4073 $header = html_writer
::span($header, 'gradeitemheader ', [
4074 'title' => $titleunescaped,
4080 if ($withdescription) {
4081 $desc = $element['object']->get_description();
4082 if (!empty($desc)) {
4083 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
4091 * Returns a link to grading page if grade.php exists in the module or link to activity
4093 * @param array $element An array representing an element in the grade_tree
4095 * @return string|null link to grading page|activity or null if not found
4097 public static function get_activity_link(array $element): ?
string {
4099 /** @var array static cache of the grade.php file existence flags */
4100 static $hasgradephp = [];
4102 $itemtype = $element['object']->itemtype
;
4103 $itemmodule = $element['object']->itemmodule
;
4104 $iteminstance = $element['object']->iteminstance
;
4105 $itemnumber = $element['object']->itemnumber
;
4107 // Links only for module items that have valid instance, module and are
4108 // called from grade_tree with valid modinfo.
4109 $modinfo = get_fast_modinfo($element['object']->courseid
);
4110 if ($itemtype != 'mod' ||
!$iteminstance ||
!$itemmodule ||
!$modinfo) {
4114 // Get $cm efficiently and with visibility information using modinfo.
4115 $instances = $modinfo->get_instances();
4116 if (empty($instances[$itemmodule][$iteminstance])) {
4119 $cm = $instances[$itemmodule][$iteminstance];
4121 // Do not add link if activity is not visible to the current user.
4122 if (!$cm->uservisible
) {
4126 if (!array_key_exists($itemmodule, $hasgradephp)) {
4127 if (file_exists($CFG->dirroot
. '/mod/' . $itemmodule . '/grade.php')) {
4128 $hasgradephp[$itemmodule] = true;
4130 $hasgradephp[$itemmodule] = false;
4134 // If module has grade.php, link to that, otherwise view.php.
4135 if ($hasgradephp[$itemmodule]) {
4136 $args = ['id' => $cm->id
, 'itemnumber' => $itemnumber];
4137 if (isset($element['userid'])) {
4138 $args['userid'] = $element['userid'];
4140 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
4142 return new moodle_url('/mod/' . $itemmodule . '/view.php', ['id' => $cm->id
]);