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')) {
774 if ($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 * @return array $users A list of enrolled gradable users.
791 function get_gradable_users(int $courseid, ?
int $groupid = null): array {
794 $context = context_course
::instance($courseid);
795 // Create a graded_users_iterator because it will properly check the groups etc.
796 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol
);
797 $onlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol) ||
798 !has_capability('moodle/course:viewsuspendedusers', $context);
800 $course = get_course($courseid);
801 $gui = new graded_users_iterator($course, null, $groupid);
802 $gui->require_active_enrolment($onlyactiveenrol);
805 // Flatten the users.
807 while ($user = $gui->next_user()) {
808 $users[$user->user
->id
] = $user->user
;
816 * A simple class containing info about grade plugins.
817 * Can be subclassed for special rules
819 * @package core_grades
820 * @copyright 2009 Nicolas Connault
821 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
823 class grade_plugin_info
{
825 * A unique id for this plugin
831 * A URL to access this plugin
837 * The name of this plugin
843 * Another grade_plugin_info object, parent of the current one
852 * @param int $id A unique id for this plugin
853 * @param string $link A URL to access this plugin
854 * @param string $string The name of this plugin
855 * @param object $parent Another grade_plugin_info object, parent of the current one
859 public function __construct($id, $link, $string, $parent=null) {
862 $this->string = $string;
863 $this->parent
= $parent;
868 * Prints the page headers, breadcrumb trail, page heading, (optional) navigation and for any gradebook page.
869 * All gradebook pages MUST use these functions in favour of the usual print_header(), print_header_simple(),
870 * print_heading() etc.
872 * @param int $courseid Course id
873 * @param string $active_type The type of the current page (report, settings,
874 * import, export, scales, outcomes, letters)
875 * @param string|null $active_plugin The plugin of the current page (grader, fullview etc...)
876 * @param string|bool $heading The heading of the page.
877 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
878 * @param string|bool $buttons Additional buttons to display on the page
879 * @param boolean $shownavigation should the gradebook navigation be shown?
880 * @param string|null $headerhelpidentifier The help string identifier if required.
881 * @param string|null $headerhelpcomponent The component for the help string.
882 * @param stdClass|null $user The user object for use with the user context header.
883 * @param actionbar|null $actionbar The actions bar which will be displayed on the page if $shownavigation is set
884 * to true. If $actionbar is not explicitly defined, the general action bar
885 * (\core_grades\output\general_action_bar) will be used by default.
886 * @param null $unused This parameter has been deprecated since 4.3 and should not be used anymore.
887 * @return string HTML code or nothing if $return == false
889 function print_grade_page_head(int $courseid, string $active_type, ?
string $active_plugin = null, string|
bool $heading = false,
890 bool $return = false, $buttons = false, bool $shownavigation = true, ?
string $headerhelpidentifier = null,
891 ?
string $headerhelpcomponent = null, ?stdClass
$user = null, ?action_bar
$actionbar = null, $unused = null) {
892 global $CFG, $OUTPUT, $PAGE, $USER;
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];
915 if ($active_type == 'report') {
916 $PAGE->set_pagelayout('report');
918 $PAGE->set_pagelayout('admin');
920 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
921 $PAGE->set_heading($PAGE->course
->fullname
);
922 $PAGE->set_secondary_active_tab('grades');
924 if ($buttons instanceof single_button
) {
925 $buttons = $OUTPUT->render($buttons);
927 $PAGE->set_button($buttons);
928 if ($courseid != SITEID
) {
929 grade_extend_settings($plugin_info, $courseid);
932 // Set the current report as active in the breadcrumbs.
933 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav
->find($active_plugin, navigation_node
::TYPE_SETTING
)) {
934 $reportnav->make_active();
937 $returnval = $OUTPUT->header();
943 if ($shownavigation) {
944 $renderer = $PAGE->get_renderer('core_grades');
945 // If the navigation action bar is not explicitly defined, use the general (default) action bar.
947 $actionbar = new general_action_bar($PAGE->context
, $PAGE->url
, $active_type, $active_plugin);
951 $returnval .= $renderer->render_action_bar($actionbar);
953 echo $renderer->render_action_bar($actionbar);
958 // Add a help dialogue box if provided.
959 if (isset($headerhelpidentifier) && !empty($heading)) {
960 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
961 } else if (isset($user)) {
962 $renderer = $PAGE->get_renderer('core_grades');
963 // If the user is viewing their own grade report, no need to show the "Message"
964 // and "Add to contact" buttons in the user heading.
965 $showuserbuttons = $user->id
!= $USER->id
;
966 $output = $renderer->user_heading($user, $courseid, $showuserbuttons);
967 } else if (!empty($heading)) {
968 $output = $OUTPUT->heading($heading);
972 $returnval .= $output;
977 $returnval .= print_natural_aggregation_upgrade_notice($courseid, context_course
::instance($courseid), $PAGE->url
,
986 * Utility class used for return tracking when using edit and other forms in grade plugins
988 * @package core_grades
989 * @copyright 2009 Nicolas Connault
990 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
992 class grade_plugin_return
{
994 * Type of grade plugin (e.g. 'edit', 'report')
1000 * Name of grade plugin (e.g. 'grader', 'overview')
1006 * Course id being viewed
1012 * Id of user whose information is being viewed/edited
1018 * Id of group for which information is being viewed/edited
1024 * Current page # within output
1033 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1035 public function __construct($params = []) {
1036 $this->type
= optional_param('gpr_type', null, PARAM_SAFEDIR
);
1037 $this->plugin
= optional_param('gpr_plugin', null, PARAM_PLUGIN
);
1038 $this->courseid
= optional_param('gpr_courseid', null, PARAM_INT
);
1039 $this->userid
= optional_param('gpr_userid', null, PARAM_INT
);
1040 $this->groupid
= optional_param('gpr_groupid', null, PARAM_INT
);
1041 $this->page
= optional_param('gpr_page', null, PARAM_INT
);
1043 foreach ($params as $key => $value) {
1044 if (property_exists($this, $key)) {
1045 $this->$key = $value;
1048 // Allow course object rather than id to be used to specify course
1049 // - avoid unnecessary use of get_course.
1050 if (array_key_exists('course', $params)) {
1051 $course = $params['course'];
1052 $this->courseid
= $course->id
;
1056 // If group has been explicitly set in constructor parameters,
1057 // we should respect that.
1058 if (!array_key_exists('groupid', $params)) {
1059 // Otherwise, 'group' in request parameters is a request for a change.
1060 // In that case, or if we have no group at all, we should get groupid from
1061 // groups_get_course_group, which will do some housekeeping as well as
1062 // give us the correct value.
1063 $changegroup = optional_param('group', -1, PARAM_INT
);
1064 if ($changegroup !== -1 or (empty($this->groupid
) and !empty($this->courseid
))) {
1065 if ($course === null) {
1066 $course = get_course($this->courseid
);
1068 $this->groupid
= groups_get_course_group($course, true);
1074 * Old syntax of class constructor. Deprecated in PHP7.
1076 * @deprecated since Moodle 3.1
1078 public function grade_plugin_return($params = null) {
1079 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
1080 self
::__construct($params);
1084 * Returns return parameters as options array suitable for buttons.
1085 * @return array options
1087 public function get_options() {
1088 if (empty($this->type
)) {
1094 if (!empty($this->plugin
)) {
1095 $params['plugin'] = $this->plugin
;
1098 if (!empty($this->courseid
)) {
1099 $params['id'] = $this->courseid
;
1102 if (!empty($this->userid
)) {
1103 $params['userid'] = $this->userid
;
1106 if (!empty($this->groupid
)) {
1107 $params['group'] = $this->groupid
;
1110 if (!empty($this->page
)) {
1111 $params['page'] = $this->page
;
1118 * Returns return url
1120 * @param string $default default url when params not set
1121 * @param array $extras Extra URL parameters
1123 * @return string url
1125 public function get_return_url($default, $extras=null) {
1128 if (empty($this->type
) or empty($this->plugin
)) {
1132 $url = $CFG->wwwroot
.'/grade/'.$this->type
.'/'.$this->plugin
.'/index.php';
1135 if (!empty($this->courseid
)) {
1136 $url .= $glue.'id='.$this->courseid
;
1140 if (!empty($this->userid
)) {
1141 $url .= $glue.'userid='.$this->userid
;
1145 if (!empty($this->groupid
)) {
1146 $url .= $glue.'group='.$this->groupid
;
1150 if (!empty($this->page
)) {
1151 $url .= $glue.'page='.$this->page
;
1155 if (!empty($extras)) {
1156 foreach ($extras as $key=>$value) {
1157 $url .= $glue.$key.'='.$value;
1166 * Returns string with hidden return tracking form elements.
1169 public function get_form_fields() {
1170 if (empty($this->type
)) {
1174 $result = '<input type="hidden" name="gpr_type" value="'.$this->type
.'" />';
1176 if (!empty($this->plugin
)) {
1177 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin
.'" />';
1180 if (!empty($this->courseid
)) {
1181 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid
.'" />';
1184 if (!empty($this->userid
)) {
1185 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid
.'" />';
1188 if (!empty($this->groupid
)) {
1189 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid
.'" />';
1192 if (!empty($this->page
)) {
1193 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page
.'" />';
1199 * Add hidden elements into mform
1201 * @param object &$mform moodle form object
1205 public function add_mform_elements(&$mform) {
1206 if (empty($this->type
)) {
1210 $mform->addElement('hidden', 'gpr_type', $this->type
);
1211 $mform->setType('gpr_type', PARAM_SAFEDIR
);
1213 if (!empty($this->plugin
)) {
1214 $mform->addElement('hidden', 'gpr_plugin', $this->plugin
);
1215 $mform->setType('gpr_plugin', PARAM_PLUGIN
);
1218 if (!empty($this->courseid
)) {
1219 $mform->addElement('hidden', 'gpr_courseid', $this->courseid
);
1220 $mform->setType('gpr_courseid', PARAM_INT
);
1223 if (!empty($this->userid
)) {
1224 $mform->addElement('hidden', 'gpr_userid', $this->userid
);
1225 $mform->setType('gpr_userid', PARAM_INT
);
1228 if (!empty($this->groupid
)) {
1229 $mform->addElement('hidden', 'gpr_groupid', $this->groupid
);
1230 $mform->setType('gpr_groupid', PARAM_INT
);
1233 if (!empty($this->page
)) {
1234 $mform->addElement('hidden', 'gpr_page', $this->page
);
1235 $mform->setType('gpr_page', PARAM_INT
);
1240 * Add return tracking params into url
1242 * @param moodle_url $url A URL
1243 * @return moodle_url with return tracking params
1245 public function add_url_params(moodle_url
$url): moodle_url
{
1246 if (empty($this->type
)) {
1250 $url->param('gpr_type', $this->type
);
1252 if (!empty($this->plugin
)) {
1253 $url->param('gpr_plugin', $this->plugin
);
1256 if (!empty($this->courseid
)) {
1257 $url->param('gpr_courseid' ,$this->courseid
);
1260 if (!empty($this->userid
)) {
1261 $url->param('gpr_userid', $this->userid
);
1264 if (!empty($this->groupid
)) {
1265 $url->param('gpr_groupid', $this->groupid
);
1268 if (!empty($this->page
)) {
1269 $url->param('gpr_page', $this->page
);
1277 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1279 * @param string $path The path of the calling script (using __FILE__?)
1280 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1281 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1282 * an array of keys and values (e.g courseid => $courseid, itemid...)
1286 function grade_build_nav($path, $pagename=null, $id=null) {
1287 global $CFG, $COURSE, $PAGE;
1289 $strgrades = get_string('grades', 'grades');
1291 // Parse the path and build navlinks from its elements
1292 $dirroot_length = strlen($CFG->dirroot
) +
1; // Add 1 for the first slash
1293 $path = substr($path, $dirroot_length);
1294 $path = str_replace('\\', '/', $path);
1296 $path_elements = explode('/', $path);
1298 $path_elements_count = count($path_elements);
1300 // First link is always 'grade'
1301 $PAGE->navbar
->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id
)));
1304 $numberofelements = 3;
1306 // Prepare URL params string
1307 $linkparams = array();
1308 if (!is_null($id)) {
1309 if (is_array($id)) {
1310 foreach ($id as $idkey => $idvalue) {
1311 $linkparams[$idkey] = $idvalue;
1314 $linkparams['id'] = $id;
1320 // Remove file extensions from filenames
1321 foreach ($path_elements as $key => $filename) {
1322 $path_elements[$key] = str_replace('.php', '', $filename);
1325 // Second level links
1326 switch ($path_elements[1]) {
1327 case 'edit': // No link
1328 if ($path_elements[3] != 'index.php') {
1329 $numberofelements = 4;
1332 case 'import': // No link
1334 case 'export': // No link
1337 // $id is required for this link. Do not print it if $id isn't given
1338 if (!is_null($id)) {
1339 $link = new moodle_url('/grade/report/index.php', $linkparams);
1342 if ($path_elements[2] == 'grader') {
1343 $numberofelements = 4;
1348 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1349 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1350 " as the second path element after 'grade'.");
1353 $PAGE->navbar
->add(get_string($path_elements[1], 'grades'), $link);
1355 // Third level links
1356 if (empty($pagename)) {
1357 $pagename = get_string($path_elements[2], 'grades');
1360 switch ($numberofelements) {
1362 $PAGE->navbar
->add($pagename, $link);
1365 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1366 $PAGE->navbar
->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1368 $PAGE->navbar
->add($pagename);
1376 * General structure representing grade items in course
1378 * @package core_grades
1379 * @copyright 2009 Nicolas Connault
1380 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1382 class grade_structure
{
1388 * Reference to modinfo for current course (for performance, to save
1389 * retrieving it from courseid every time). Not actually set except for
1390 * the grade_tree type.
1391 * @var course_modinfo
1396 * 1D array of grade items only
1401 * Returns icon of element
1403 * @param array &$element An array representing an element in the grade_tree
1404 * @param bool $spacerifnone return spacer if no icon found
1406 * @return string icon or spacer
1408 public function get_element_icon(&$element, $spacerifnone=false) {
1409 global $CFG, $OUTPUT;
1410 require_once $CFG->libdir
.'/filelib.php';
1414 // Object holding pix_icon information before instantiation.
1415 $icon = new stdClass();
1416 $icon->attributes
= array(
1417 'class' => 'icon itemicon'
1419 $icon->component
= 'moodle';
1422 switch ($element['type']) {
1425 case 'categoryitem':
1428 $is_course = $element['object']->is_course_item();
1429 $is_category = $element['object']->is_category_item();
1430 $is_scale = $element['object']->gradetype
== GRADE_TYPE_SCALE
;
1431 $is_value = $element['object']->gradetype
== GRADE_TYPE_VALUE
;
1432 $is_outcome = !empty($element['object']->outcomeid
);
1434 if ($element['object']->is_calculated()) {
1435 $icon->pix
= 'i/calc';
1436 $icon->title
= s(get_string('calculatedgrade', 'grades'));
1438 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1439 if ($category = $element['object']->get_item_category()) {
1440 $aggrstrings = grade_helper
::get_aggregation_strings();
1441 $stragg = $aggrstrings[$category->aggregation
];
1443 $icon->pix
= 'i/calc';
1444 $icon->title
= s($stragg);
1446 switch ($category->aggregation
) {
1447 case GRADE_AGGREGATE_MEAN
:
1448 case GRADE_AGGREGATE_MEDIAN
:
1449 case GRADE_AGGREGATE_WEIGHTED_MEAN
:
1450 case GRADE_AGGREGATE_WEIGHTED_MEAN2
:
1451 case GRADE_AGGREGATE_EXTRACREDIT_MEAN
:
1452 $icon->pix
= 'i/agg_mean';
1454 case GRADE_AGGREGATE_SUM
:
1455 $icon->pix
= 'i/agg_sum';
1460 } else if ($element['object']->itemtype
== 'mod') {
1461 // Prevent outcomes displaying the same icon as the activity they are attached to.
1463 $icon->pix
= 'i/outcomes';
1464 $icon->title
= s(get_string('outcome', 'grades'));
1466 $modinfo = get_fast_modinfo($element['object']->courseid
);
1467 $module = $element['object']->itemmodule
;
1468 $instanceid = $element['object']->iteminstance
;
1469 if (isset($modinfo->instances
[$module][$instanceid])) {
1470 $icon->url
= $modinfo->instances
[$module][$instanceid]->get_icon_url();
1472 $icon->pix
= 'monologo';
1473 $icon->component
= $element['object']->itemmodule
;
1475 $icon->title
= s(get_string('modulename', $element['object']->itemmodule
));
1477 } else if ($element['object']->itemtype
== 'manual') {
1478 if ($element['object']->is_outcome_item()) {
1479 $icon->pix
= 'i/outcomes';
1480 $icon->title
= s(get_string('outcome', 'grades'));
1482 $icon->pix
= 'i/manual_item';
1483 $icon->title
= s(get_string('manualitem', 'grades'));
1490 $icon->pix
= 'i/folder';
1491 $icon->title
= s(get_string('category', 'grades'));
1496 if ($spacerifnone) {
1497 $outputstr = $OUTPUT->spacer() . ' ';
1499 } else if (isset($icon->url
)) {
1500 $outputstr = html_writer
::img($icon->url
, $icon->title
, $icon->attributes
);
1502 $outputstr = $OUTPUT->pix_icon($icon->pix
, $icon->title
, $icon->component
, $icon->attributes
);
1509 * Returns the string that describes the type of the element.
1511 * @param array $element An array representing an element in the grade_tree
1512 * @return string The string that describes the type of the grade element
1514 public function get_element_type_string(array $element): string {
1515 // If the element is a grade category.
1516 if ($element['type'] == 'category') {
1517 return get_string('category', 'grades');
1519 // If the element is a grade item.
1520 if (in_array($element['type'], ['item', 'courseitem', 'categoryitem'])) {
1521 // If calculated grade item.
1522 if ($element['object']->is_calculated()) {
1523 return get_string('calculatedgrade', 'grades');
1525 // If aggregated type grade item.
1526 if ($element['object']->is_aggregate_item()) {
1527 return get_string('aggregation', 'core_grades');
1529 // If external grade item (module, plugin, etc.).
1530 if ($element['object']->is_external_item()) {
1531 // If outcome grade item.
1532 if ($element['object']->is_outcome_item()) {
1533 return get_string('outcome', 'grades');
1535 return get_string('modulename', $element['object']->itemmodule
);
1537 // If manual grade item.
1538 if ($element['object']->itemtype
== 'manual') {
1539 // If outcome grade item.
1540 if ($element['object']->is_outcome_item()) {
1541 return get_string('outcome', 'grades');
1543 return get_string('manualitem', 'grades');
1551 * Returns name of element optionally with icon and link
1553 * @param array &$element An array representing an element in the grade_tree
1554 * @param bool $withlink Whether or not this header has a link
1555 * @param bool $icon Whether or not to display an icon with this header
1556 * @param bool $spacerifnone return spacer if no icon found
1557 * @param bool $withdescription Show description if defined by this item.
1558 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1559 * instead of "Category total" or "Course total"
1560 * @param moodle_url|null $sortlink Link to sort column.
1562 * @return string header
1564 public function get_element_header(array &$element, bool $withlink = false, bool $icon = true,
1565 bool $spacerifnone = false, bool $withdescription = false, bool $fulltotal = false,
1566 ?moodle_url
$sortlink = null) {
1570 $header .= $this->get_element_icon($element, $spacerifnone);
1573 $title = $element['object']->get_name($fulltotal);
1574 $titleunescaped = $element['object']->get_name($fulltotal, false);
1577 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1578 $element['type'] != 'courseitem') {
1584 $header = html_writer
::link($url, $header, [
1585 'title' => $titleunescaped,
1586 'class' => 'gradeitemheader '
1589 if ($withlink && $url = $this->get_activity_link($element)) {
1590 $a = new stdClass();
1591 $a->name
= get_string('modulename', $element['object']->itemmodule
);
1592 $a->title
= $titleunescaped;
1593 $title = get_string('linktoactivity', 'grades', $a);
1594 $header = html_writer
::link($url, $header, [
1596 'class' => 'gradeitemheader ',
1599 $header = html_writer
::span($header, 'gradeitemheader ', [
1600 'title' => $titleunescaped,
1606 if ($withdescription) {
1607 $desc = $element['object']->get_description();
1608 if (!empty($desc)) {
1609 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1616 private function get_activity_link($element) {
1618 /** @var array static cache of the grade.php file existence flags */
1619 static $hasgradephp = array();
1621 $itemtype = $element['object']->itemtype
;
1622 $itemmodule = $element['object']->itemmodule
;
1623 $iteminstance = $element['object']->iteminstance
;
1624 $itemnumber = $element['object']->itemnumber
;
1626 // Links only for module items that have valid instance, module and are
1627 // called from grade_tree with valid modinfo
1628 if ($itemtype != 'mod' ||
!$iteminstance ||
!$itemmodule ||
!$this->modinfo
) {
1632 // Get $cm efficiently and with visibility information using modinfo
1633 $instances = $this->modinfo
->get_instances();
1634 if (empty($instances[$itemmodule][$iteminstance])) {
1637 $cm = $instances[$itemmodule][$iteminstance];
1639 // Do not add link if activity is not visible to the current user
1640 if (!$cm->uservisible
) {
1644 if (!array_key_exists($itemmodule, $hasgradephp)) {
1645 if (file_exists($CFG->dirroot
. '/mod/' . $itemmodule . '/grade.php')) {
1646 $hasgradephp[$itemmodule] = true;
1648 $hasgradephp[$itemmodule] = false;
1652 // If module has grade.php, link to that, otherwise view.php
1653 if ($hasgradephp[$itemmodule]) {
1654 $args = array('id' => $cm->id
, 'itemnumber' => $itemnumber);
1655 if (isset($element['userid'])) {
1656 $args['userid'] = $element['userid'];
1658 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1660 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id
));
1665 * Returns URL of a page that is supposed to contain detailed grade analysis
1667 * At the moment, only activity modules are supported. The method generates link
1668 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1669 * gradeid and userid. If the grade.php does not exist, null is returned.
1671 * @return moodle_url|null URL or null if unable to construct it
1673 public function get_grade_analysis_url(grade_grade
$grade) {
1675 /** @var array static cache of the grade.php file existence flags */
1676 static $hasgradephp = array();
1678 if (empty($grade->grade_item
) or !($grade->grade_item
instanceof grade_item
)) {
1679 throw new coding_exception('Passed grade without the associated grade item');
1681 $item = $grade->grade_item
;
1683 if (!$item->is_external_item()) {
1684 // at the moment, only activity modules are supported
1687 if ($item->itemtype
!== 'mod') {
1688 throw new coding_exception('Unknown external itemtype: '.$item->itemtype
);
1690 if (empty($item->iteminstance
) or empty($item->itemmodule
) or empty($this->modinfo
)) {
1694 if (!array_key_exists($item->itemmodule
, $hasgradephp)) {
1695 if (file_exists($CFG->dirroot
. '/mod/' . $item->itemmodule
. '/grade.php')) {
1696 $hasgradephp[$item->itemmodule
] = true;
1698 $hasgradephp[$item->itemmodule
] = false;
1702 if (!$hasgradephp[$item->itemmodule
]) {
1706 $instances = $this->modinfo
->get_instances();
1707 if (empty($instances[$item->itemmodule
][$item->iteminstance
])) {
1710 $cm = $instances[$item->itemmodule
][$item->iteminstance
];
1711 if (!$cm->uservisible
) {
1715 $url = new moodle_url('/mod/'.$item->itemmodule
.'/grade.php', array(
1717 'itemid' => $item->id
,
1718 'itemnumber' => $item->itemnumber
,
1719 'gradeid' => $grade->id
,
1720 'userid' => $grade->userid
,
1727 * Returns an action icon leading to the grade analysis page
1729 * @param grade_grade $grade
1731 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1732 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1734 public function get_grade_analysis_icon(grade_grade
$grade) {
1736 debugging('The function get_grade_analysis_icon() is deprecated, please do not use it anymore.',
1739 $url = $this->get_grade_analysis_url($grade);
1740 if (is_null($url)) {
1744 $title = get_string('gradeanalysis', 'core_grades');
1745 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1746 ['title' => $title, 'aria-label' => $title]);
1750 * Returns a link leading to the grade analysis page
1752 * @param grade_grade $grade
1753 * @return string|null
1755 public function get_grade_analysis_link(grade_grade
$grade): ?
string {
1756 $url = $this->get_grade_analysis_url($grade);
1757 if (is_null($url)) {
1761 $gradeanalysisstring = get_string('gradeanalysis', 'grades');
1762 return html_writer
::link($url, $gradeanalysisstring,
1763 ['class' => 'dropdown-item', 'aria-label' => $gradeanalysisstring, 'role' => 'menuitem']);
1767 * Returns an action menu for the grade.
1769 * @param grade_grade $grade A grade_grade object
1772 public function get_grade_action_menu(grade_grade
$grade) : string {
1777 $url = $this->get_grade_analysis_url($grade);
1779 $title = get_string('gradeanalysis', 'core_grades');
1780 $menuitems[] = new action_menu_link_secondary($url, null, $title);
1784 $menu = new action_menu($menuitems);
1785 $icon = $OUTPUT->pix_icon('i/moremenu', get_string('actions'));
1786 $extraclasses = 'btn btn-link btn-icon icon-size-3 d-flex align-items-center justify-content-center';
1787 $menu->set_menu_trigger($icon, $extraclasses);
1788 $menu->set_menu_left();
1790 return $OUTPUT->render($menu);
1797 * Returns the grade eid - the grade may not exist yet.
1799 * @param grade_grade $grade_grade A grade_grade object
1801 * @return string eid
1803 public function get_grade_eid($grade_grade) {
1804 if (empty($grade_grade->id
)) {
1805 return 'n'.$grade_grade->itemid
.'u'.$grade_grade->userid
;
1807 return 'g'.$grade_grade->id
;
1812 * Returns the grade_item eid
1813 * @param grade_item $grade_item A grade_item object
1814 * @return string eid
1816 public function get_item_eid($grade_item) {
1817 return 'ig'.$grade_item->id
;
1821 * Given a grade_tree element, returns an array of parameters
1822 * used to build an icon for that element.
1824 * @param array $element An array representing an element in the grade_tree
1828 public function get_params_for_iconstr($element) {
1829 $strparams = new stdClass();
1830 $strparams->category
= '';
1831 $strparams->itemname
= '';
1832 $strparams->itemmodule
= '';
1834 if (!method_exists($element['object'], 'get_name')) {
1838 $strparams->itemname
= html_to_text($element['object']->get_name());
1840 // If element name is categorytotal, get the name of the parent category
1841 if ($strparams->itemname
== get_string('categorytotal', 'grades')) {
1842 $parent = $element['object']->get_parent_category();
1843 $strparams->category
= $parent->get_name() . ' ';
1845 $strparams->category
= '';
1848 $strparams->itemmodule
= null;
1849 if (isset($element['object']->itemmodule
)) {
1850 $strparams->itemmodule
= $element['object']->itemmodule
;
1856 * Return a reset icon for the given element.
1858 * @param array $element An array representing an element in the grade_tree
1859 * @param object $gpr A grade_plugin_return object
1860 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1861 * @return string|action_menu_link
1862 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1863 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1865 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1866 global $CFG, $OUTPUT;
1867 debugging('The function get_reset_icon() is deprecated, please do not use it anymore.',
1870 // Limit to category items set to use the natural weights aggregation method, and users
1871 // with the capability to manage grades.
1872 if ($element['type'] != 'category' ||
$element['object']->aggregation
!= GRADE_AGGREGATE_SUM ||
1873 !has_capability('moodle/grade:manage', $this->context
)) {
1874 return $returnactionmenulink ?
null : '';
1877 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1878 $url = new moodle_url('/grade/edit/tree/action.php', array(
1879 'id' => $this->courseid
,
1880 'action' => 'resetweights',
1881 'eid' => $element['eid'],
1882 'sesskey' => sesskey(),
1885 if ($returnactionmenulink) {
1886 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1887 get_string('resetweightsshort', 'grades'));
1889 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1894 * Returns a link to reset weights for the given element.
1896 * @param array $element An array representing an element in the grade_tree
1897 * @param object $gpr A grade_plugin_return object
1898 * @return string|null
1900 public function get_reset_weights_link(array $element, object $gpr): ?
string {
1902 // Limit to category items set to use the natural weights aggregation method, and users
1903 // with the capability to manage grades.
1904 if ($element['type'] != 'category' ||
$element['object']->aggregation
!= GRADE_AGGREGATE_SUM ||
1905 !has_capability('moodle/grade:manage', $this->context
)) {
1909 $title = get_string('resetweightsshort', 'grades');
1910 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1911 $url = new moodle_url('/grade/edit/tree/action.php', [
1912 'id' => $this->courseid
,
1913 'action' => 'resetweights',
1914 'eid' => $element['eid'],
1915 'sesskey' => sesskey(),
1917 $gpr->add_url_params($url);
1918 return html_writer
::link($url, $title,
1919 ['class' => 'dropdown-item', 'aria-label' => $str, 'role' => 'menuitem']);
1923 * Returns a link to delete a given element.
1925 * @param array $element An array representing an element in the grade_tree
1926 * @param object $gpr A grade_plugin_return object
1927 * @return string|null
1929 public function get_delete_link(array $element, object $gpr): ?
string {
1930 if ($element['type'] == 'item' ||
($element['type'] == 'category' && $element['depth'] > 1)) {
1931 if (grade_edit_tree
::element_deletable($element)) {
1932 $deleteconfirmationurl = new moodle_url('index.php', [
1933 'id' => $this->courseid
,
1934 'action' => 'delete',
1936 'eid' => $element['eid'],
1937 'sesskey' => sesskey(),
1939 $gpr->add_url_params($deleteconfirmationurl);
1940 $title = get_string('delete');
1941 return html_writer
::link(
1945 'class' => 'dropdown-item',
1946 'aria-label' => $title,
1947 'role' => 'menuitem',
1948 'data-modal' => 'confirmation',
1949 'data-modal-title-str' => json_encode(['confirm', 'core']),
1950 'data-modal-content-str' => json_encode([
1953 $element['object']->get_name()
1955 'data-modal-yes-button-str' => json_encode(['delete', 'core']),
1956 'data-modal-destination' => $deleteconfirmationurl->out(false),
1965 * Returns a link to duplicate a given element.
1967 * @param array $element An array representing an element in the grade_tree
1968 * @param object $gpr A grade_plugin_return object
1969 * @return string|null
1971 public function get_duplicate_link(array $element, object $gpr): ?
string {
1972 if ($element['type'] == 'item' ||
($element['type'] == 'category' && $element['depth'] > 1)) {
1973 if (grade_edit_tree
::element_duplicatable($element)) {
1974 $duplicateparams = [];
1975 $duplicateparams['id'] = $this->courseid
;
1976 $duplicateparams['action'] = 'duplicate';
1977 $duplicateparams['eid'] = $element['eid'];
1978 $duplicateparams['sesskey'] = sesskey();
1979 $url = new moodle_url('index.php', $duplicateparams);
1980 $title = get_string('duplicate');
1981 $gpr->add_url_params($url);
1982 return html_writer
::link($url, $title,
1983 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
1990 * Return edit icon for give element
1992 * @param array $element An array representing an element in the grade_tree
1993 * @param object $gpr A grade_plugin_return object
1994 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1995 * @return string|action_menu_link
1996 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
1997 * @todo MDL-77307 This will be deleted in Moodle 4.6.
1999 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
2000 global $CFG, $OUTPUT;
2002 debugging('The function get_edit_icon() is deprecated, please do not use it anymore.',
2005 if (!has_capability('moodle/grade:manage', $this->context
)) {
2006 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context
)) {
2007 // oki - let them override grade
2009 return $returnactionmenulink ?
null : '';
2013 static $strfeedback = null;
2014 static $streditgrade = null;
2015 if (is_null($streditgrade)) {
2016 $streditgrade = get_string('editgrade', 'grades');
2017 $strfeedback = get_string('feedback');
2020 $strparams = $this->get_params_for_iconstr($element);
2022 $object = $element['object'];
2024 switch ($element['type']) {
2026 case 'categoryitem':
2028 $stredit = get_string('editverbose', 'grades', $strparams);
2029 if (empty($object->outcomeid
) ||
empty($CFG->enableoutcomes
)) {
2030 $url = new moodle_url('/grade/edit/tree/item.php',
2031 array('courseid' => $this->courseid
, 'id' => $object->id
));
2033 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
2034 array('courseid' => $this->courseid
, 'id' => $object->id
));
2039 $stredit = get_string('editverbose', 'grades', $strparams);
2040 $url = new moodle_url('/grade/edit/tree/category.php',
2041 array('courseid' => $this->courseid
, 'id' => $object->id
));
2045 $stredit = $streditgrade;
2046 if (empty($object->id
)) {
2047 $url = new moodle_url('/grade/edit/tree/grade.php',
2048 array('courseid' => $this->courseid
, 'itemid' => $object->itemid
, 'userid' => $object->userid
));
2050 $url = new moodle_url('/grade/edit/tree/grade.php',
2051 array('courseid' => $this->courseid
, 'id' => $object->id
));
2053 if (!empty($object->feedback
)) {
2054 $feedback = addslashes_js(trim(format_string($object->feedback
, $object->feedbackformat
)));
2063 if ($returnactionmenulink) {
2064 return new action_menu_link_secondary($gpr->add_url_params($url),
2065 new pix_icon('t/edit', $stredit),
2066 get_string('editsettings'));
2068 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
2072 return $returnactionmenulink ?
null : '';
2077 * Returns a link leading to the edit grade/grade item/category page
2079 * @param array $element An array representing an element in the grade_tree
2080 * @param object $gpr A grade_plugin_return object
2081 * @return string|null
2083 public function get_edit_link(array $element, object $gpr): ?
string {
2088 if ((!has_capability('moodle/grade:manage', $this->context
) &&
2089 (!($element['type'] == 'grade') ||
!has_capability('moodle/grade:edit', $this->context
)))) {
2093 $object = $element['object'];
2095 if ($element['type'] == 'grade') {
2096 if (empty($object->id
)) {
2097 $url = new moodle_url('/grade/edit/tree/grade.php',
2098 ['courseid' => $this->courseid
, 'itemid' => $object->itemid
, 'userid' => $object->userid
]);
2100 $url = new moodle_url('/grade/edit/tree/grade.php',
2101 ['courseid' => $this->courseid
, 'id' => $object->id
]);
2103 $url = $gpr->add_url_params($url);
2104 $title = get_string('editgrade', 'grades');
2105 } else if (($element['type'] == 'item') ||
($element['type'] == 'categoryitem') ||
2106 ($element['type'] == 'courseitem')) {
2107 $url = new moodle_url('#');
2108 if (empty($object->outcomeid
) ||
empty($CFG->enableoutcomes
)) {
2109 return html_writer
::link($url, get_string('itemsedit', 'grades'), [
2110 'class' => 'dropdown-item',
2111 'aria-label' => get_string('itemsedit', 'grades'),
2112 'role' => 'menuitem',
2113 'data-gprplugin' => $gpr->plugin
,
2114 'data-courseid' => $this->courseid
,
2115 'data-itemid' => $object->id
, 'data-trigger' => 'add-item-form'
2117 } else if (count(grade_outcome
::fetch_all_available($this->courseid
)) > 0) {
2118 return html_writer
::link($url, get_string('itemsedit', 'grades'), [
2119 'class' => 'dropdown-item',
2120 get_string('itemsedit', 'grades'),
2121 'role' => 'menuitem',
2122 'data-gprplugin' => $gpr->plugin
,
2123 'data-courseid' => $this->courseid
,
2124 'data-itemid' => $object->id
, 'data-trigger' => 'add-outcome-form'
2127 } else if ($element['type'] == 'category') {
2128 $url = new moodle_url('#');
2129 $title = get_string('categoryedit', 'grades');
2130 return html_writer
::link($url, $title, [
2131 'class' => 'dropdown-item',
2132 'aria-label' => $title,
2133 'role' => 'menuitem',
2134 'data-gprplugin' => $gpr->plugin
,
2135 'data-courseid' => $this->courseid
,
2136 'data-category' => $object->id
,
2137 'data-trigger' => 'add-category-form'
2140 return html_writer
::link($url, $title,
2141 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2145 * Returns link to the advanced grading page
2147 * @param array $element An array representing an element in the grade_tree
2148 * @param object $gpr A grade_plugin_return object
2149 * @return string|null
2151 public function get_advanced_grading_link(array $element, object $gpr): ?
string {
2154 /** @var array static cache of the grade.php file existence flags */
2155 static $hasgradephp = [];
2157 $itemtype = $element['object']->itemtype
;
2158 $itemmodule = $element['object']->itemmodule
;
2159 $iteminstance = $element['object']->iteminstance
;
2160 $itemnumber = $element['object']->itemnumber
;
2162 // Links only for module items that have valid instance, module and are
2163 // called from grade_tree with valid modinfo.
2164 if ($itemtype == 'mod' && $iteminstance && $itemmodule && $this->modinfo
) {
2166 // Get $cm efficiently and with visibility information using modinfo.
2167 $instances = $this->modinfo
->get_instances();
2168 if (!empty($instances[$itemmodule][$iteminstance])) {
2169 $cm = $instances[$itemmodule][$iteminstance];
2171 // Do not add link if activity is not visible to the current user.
2172 if ($cm->uservisible
) {
2173 if (!array_key_exists($itemmodule, $hasgradephp)) {
2174 if (file_exists($CFG->dirroot
. '/mod/' . $itemmodule . '/grade.php')) {
2175 $hasgradephp[$itemmodule] = true;
2177 $hasgradephp[$itemmodule] = false;
2181 // If module has grade.php, add link to that.
2182 if ($hasgradephp[$itemmodule]) {
2183 $args = array('id' => $cm->id
, 'itemnumber' => $itemnumber);
2184 if (isset($element['userid'])) {
2185 $args['userid'] = $element['userid'];
2188 $url = new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
2189 $title = get_string('advancedgrading', 'gradereport_grader', $itemmodule);
2190 $gpr->add_url_params($url);
2191 return html_writer
::link($url, $title,
2192 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2202 * Return hiding icon for give element
2204 * @param array $element An array representing an element in the grade_tree
2205 * @param object $gpr A grade_plugin_return object
2206 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2207 * @return string|action_menu_link
2208 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2209 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2211 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
2212 global $CFG, $OUTPUT;
2213 debugging('The function get_hiding_icon() is deprecated, please do not use it anymore.',
2216 if (!$element['object']->can_control_visibility()) {
2217 return $returnactionmenulink ?
null : '';
2220 if (!has_capability('moodle/grade:manage', $this->context
) and
2221 !has_capability('moodle/grade:hide', $this->context
)) {
2222 return $returnactionmenulink ?
null : '';
2225 $strparams = $this->get_params_for_iconstr($element);
2226 $strshow = get_string('showverbose', 'grades', $strparams);
2227 $strhide = get_string('hideverbose', 'grades', $strparams);
2229 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2230 $url = $gpr->add_url_params($url);
2232 if ($element['object']->is_hidden()) {
2234 $tooltip = $strshow;
2236 // Change the icon and add a tooltip showing the date
2237 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
2238 $type = 'hiddenuntil';
2239 $tooltip = get_string('hiddenuntildate', 'grades',
2240 userdate($element['object']->get_hidden()));
2243 $url->param('action', 'show');
2245 if ($returnactionmenulink) {
2246 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
2248 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
2252 $url->param('action', 'hide');
2253 if ($returnactionmenulink) {
2254 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
2256 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
2264 * Returns a link with url to hide/unhide grade/grade item/grade category
2266 * @param array $element An array representing an element in the grade_tree
2267 * @param object $gpr A grade_plugin_return object
2268 * @return string|null
2270 public function get_hiding_link(array $element, object $gpr): ?
string {
2271 if (!$element['object']->can_control_visibility() ||
!has_capability('moodle/grade:manage', $this->context
) ||
2272 !has_capability('moodle/grade:hide', $this->context
)) {
2276 $url = new moodle_url('/grade/edit/tree/action.php',
2277 ['id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2278 $url = $gpr->add_url_params($url);
2280 if ($element['object']->is_hidden()) {
2281 $url->param('action', 'show');
2282 $title = get_string('show');
2284 $url->param('action', 'hide');
2285 $title = get_string('hide');
2288 $url = html_writer
::link($url, $title,
2289 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2291 if ($element['type'] == 'grade') {
2292 $item = $element['object']->grade_item
;
2293 if ($item->hidden
) {
2294 $strparamobj = new stdClass();
2295 $strparamobj->itemname
= $item->get_name(true, true);
2296 $strnonunhideable = get_string('nonunhideableverbose', 'grades', $strparamobj);
2297 $url = html_writer
::span($title, 'text-muted dropdown-item',
2298 ['title' => $strnonunhideable, 'aria-label' => $title, 'role' => 'menuitem']);
2306 * Return locking icon for given element
2308 * @param array $element An array representing an element in the grade_tree
2309 * @param object $gpr A grade_plugin_return object
2312 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2313 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2315 public function get_locking_icon($element, $gpr) {
2316 global $CFG, $OUTPUT;
2317 debugging('The function get_locking_icon() is deprecated, please do not use it anymore.',
2320 $strparams = $this->get_params_for_iconstr($element);
2321 $strunlock = get_string('unlockverbose', 'grades', $strparams);
2322 $strlock = get_string('lockverbose', 'grades', $strparams);
2324 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']));
2325 $url = $gpr->add_url_params($url);
2327 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
2328 if ($element['type'] == 'grade' && $element['object']->grade_item
->is_locked()) {
2329 $strparamobj = new stdClass();
2330 $strparamobj->itemname
= $element['object']->grade_item
->itemname
;
2331 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2333 $action = html_writer
::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
2334 array('class' => 'action-icon'));
2336 } else if ($element['object']->is_locked()) {
2338 $tooltip = $strunlock;
2340 // Change the icon and add a tooltip showing the date
2341 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
2343 $tooltip = get_string('locktimedate', 'grades',
2344 userdate($element['object']->get_locktime()));
2347 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:unlock', $this->context
)) {
2350 $url->param('action', 'unlock');
2351 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
2355 if (!has_capability('moodle/grade:manage', $this->context
) and !has_capability('moodle/grade:lock', $this->context
)) {
2358 $url->param('action', 'lock');
2359 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
2367 * Returns link to lock/unlock grade/grade item/grade category
2369 * @param array $element An array representing an element in the grade_tree
2370 * @param object $gpr A grade_plugin_return object
2372 * @return string|null
2374 public function get_locking_link(array $element, object $gpr): ?
string {
2376 if (has_capability('moodle/grade:manage', $this->context
) && isset($element['object'])) {
2378 $url = new moodle_url('/grade/edit/tree/action.php',
2379 ['id' => $this->courseid
, 'sesskey' => sesskey(), 'eid' => $element['eid']]);
2380 $url = $gpr->add_url_params($url);
2382 if (($element['type'] == 'grade') && ($element['object']->grade_item
->is_locked())) {
2383 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon.
2384 $strparamobj = new stdClass();
2385 $strparamobj->itemname
= $element['object']->grade_item
->get_name(true, true);
2386 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
2387 $title = get_string('unlock', 'grades');
2388 return html_writer
::span($title, 'text-muted dropdown-item', ['title' => $strnonunlockable,
2389 'aria-label' => $title, 'role' => 'menuitem']);
2390 } else if ($element['object']->is_locked()) {
2391 if (has_capability('moodle/grade:unlock', $this->context
)) {
2392 $title = get_string('unlock', 'grades');
2393 $url->param('action', 'unlock');
2398 if (has_capability('moodle/grade:lock', $this->context
)) {
2399 $title = get_string('lock', 'grades');
2400 $url->param('action', 'lock');
2406 return html_writer
::link($url, $title,
2407 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2414 * Return calculation icon for given element
2416 * @param array $element An array representing an element in the grade_tree
2417 * @param object $gpr A grade_plugin_return object
2418 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
2419 * @return string|action_menu_link
2420 * @deprecated since Moodle 4.2 - The row is not shown anymore - we have actions menu.
2421 * @todo MDL-77307 This will be deleted in Moodle 4.6.
2423 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
2424 global $CFG, $OUTPUT;
2425 debugging('The function get_calculation_icon() is deprecated, please do not use it anymore.',
2428 if (!has_capability('moodle/grade:manage', $this->context
)) {
2429 return $returnactionmenulink ?
null : '';
2432 $type = $element['type'];
2433 $object = $element['object'];
2435 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
2436 $strparams = $this->get_params_for_iconstr($element);
2437 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2439 $is_scale = $object->gradetype
== GRADE_TYPE_SCALE
;
2440 $is_value = $object->gradetype
== GRADE_TYPE_VALUE
;
2442 // show calculation icon only when calculation possible
2443 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2444 if ($object->is_calculated()) {
2447 $icon = 't/calc_off';
2450 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid
, 'id' => $object->id
));
2451 $url = $gpr->add_url_params($url);
2452 if ($returnactionmenulink) {
2453 return new action_menu_link_secondary($url,
2454 new pix_icon($icon, $streditcalculation),
2455 get_string('editcalculation', 'grades'));
2457 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2462 return $returnactionmenulink ?
null : '';
2466 * Returns link to edit calculation for a grade item.
2468 * @param array $element An array representing an element in the grade_tree
2469 * @param object $gpr A grade_plugin_return object
2471 * @return string|null
2473 public function get_edit_calculation_link(array $element, object $gpr): ?
string {
2475 if (has_capability('moodle/grade:manage', $this->context
) && isset($element['object'])) {
2476 $object = $element['object'];
2477 $isscale = $object->gradetype
== GRADE_TYPE_SCALE
;
2478 $isvalue = $object->gradetype
== GRADE_TYPE_VALUE
;
2480 // Show calculation icon only when calculation possible.
2481 if (!$object->is_external_item() && ($isscale ||
$isvalue)) {
2482 $editcalculationstring = get_string('editcalculation', 'grades');
2483 $url = new moodle_url('/grade/edit/tree/calculation.php',
2484 ['courseid' => $this->courseid
, 'id' => $object->id
]);
2485 $url = $gpr->add_url_params($url);
2486 return html_writer
::link($url, $editcalculationstring,
2487 ['class' => 'dropdown-item', 'aria-label' => $editcalculationstring, 'role' => 'menuitem']);
2494 * Sets status icons for the grade.
2496 * @param array $element array with grade item info
2497 * @return string|null status icons container HTML
2499 public function set_grade_status_icons(array $element): ?
string {
2503 'hidden' => $element['object']->is_hidden(),
2504 'locked' => $element['object']->is_locked(),
2507 if ($element['object'] instanceof grade_grade
) {
2508 $grade = $element['object'];
2509 $context['overridden'] = $grade->is_overridden();
2510 $context['excluded'] = $grade->is_excluded();
2511 $context['feedback'] = !empty($grade->feedback
) && $grade->load_grade_item()->gradetype
!= GRADE_TYPE_TEXT
;
2514 // Early return if there aren't any statuses that we need to show.
2515 if (!in_array(true, $context)) {
2519 $context['classes'] = 'grade_icons data-collapse_gradeicons';
2521 if (isset($element['type']) && ($element['type'] == 'category')) {
2522 $context['classes'] = 'category_grade_icons';
2525 return $OUTPUT->render_from_template('core_grades/status_icons', $context);
2529 * Returns an action menu for the grade.
2531 * @param array $element Array with cell info.
2532 * @param string $mode Mode - gradeitem or user
2533 * @param grade_plugin_return $gpr
2534 * @param moodle_url|null $baseurl
2537 public function get_cell_action_menu(array $element, string $mode, grade_plugin_return
$gpr,
2538 ?moodle_url
$baseurl = null): string {
2539 global $OUTPUT, $USER;
2541 $context = new stdClass();
2543 if ($mode == 'gradeitem' ||
$mode == 'setup') {
2546 if ($element['type'] == 'grade') {
2547 $context->datatype
= 'grade';
2549 $item = $element['object']->grade_item
;
2550 if ($item->is_course_item() ||
$item->is_category_item()) {
2551 $editable = (bool)get_config('moodle', 'grade_overridecat');;
2554 if (!empty($USER->editing
)) {
2556 $context->editurl
= $this->get_edit_link($element, $gpr);
2558 $context->hideurl
= $this->get_hiding_link($element, $gpr);
2559 $context->lockurl
= $this->get_locking_link($element, $gpr);
2562 $context->gradeanalysisurl
= $this->get_grade_analysis_link($element['object']);
2563 } else if (($element['type'] == 'item') ||
($element['type'] == 'categoryitem') ||
2564 ($element['type'] == 'courseitem') ||
($element['type'] == 'userfield')) {
2566 $context->datatype
= 'item';
2568 if ($element['type'] == 'item') {
2569 if ($mode == 'setup') {
2570 $context->deleteurl
= $this->get_delete_link($element, $gpr);
2571 $context->duplicateurl
= $this->get_duplicate_link($element, $gpr);
2574 grade_report
::get_additional_context($this->context
, $this->courseid
,
2575 $element, $gpr, $mode, $context, true);
2576 $context->advancedgradingurl
= $this->get_advanced_grading_link($element, $gpr);
2578 $context->divider1
= true;
2581 if (($element['type'] == 'item') ||
2582 (($element['type'] == 'userfield') && ($element['name'] !== 'fullname'))) {
2583 $context->divider2
= true;
2586 if (!empty($USER->editing
) ||
$mode == 'setup') {
2587 if (($element['type'] == 'userfield') && ($element['name'] !== 'fullname')) {
2588 $context->divider2
= true;
2589 } else if (($mode !== 'setup') && ($element['type'] !== 'userfield')) {
2590 $context->divider1
= true;
2591 $context->divider2
= true;
2594 if ($element['type'] == 'item') {
2595 $context->editurl
= $this->get_edit_link($element, $gpr);
2598 $context->editcalculationurl
=
2599 $this->get_edit_calculation_link($element, $gpr);
2601 if (isset($element['object'])) {
2602 $object = $element['object'];
2603 if ($object->itemmodule
!== 'quiz') {
2604 $context->hideurl
= $this->get_hiding_link($element, $gpr);
2607 $context->lockurl
= $this->get_locking_link($element, $gpr);
2612 $sortlink = clone($baseurl);
2613 if (isset($element['object']->id
)) {
2614 $sortlink->param('sortitemid', $element['object']->id
);
2615 } else if ($element['type'] == 'userfield') {
2616 $context->datatype
= $element['name'];
2617 $sortlink->param('sortitemid', $element['name']);
2620 if (($element['type'] == 'userfield') && ($element['name'] == 'fullname')) {
2621 $sortlink->param('sortitemid', 'firstname');
2622 $context->ascendingfirstnameurl
= $this->get_sorting_link($sortlink, $gpr);
2623 $context->descendingfirstnameurl
= $this->get_sorting_link($sortlink, $gpr, 'desc');
2625 $sortlink->param('sortitemid', 'lastname');
2626 $context->ascendinglastnameurl
= $this->get_sorting_link($sortlink, $gpr);
2627 $context->descendinglastnameurl
= $this->get_sorting_link($sortlink, $gpr, 'desc');
2629 $context->ascendingurl
= $this->get_sorting_link($sortlink, $gpr);
2630 $context->descendingurl
= $this->get_sorting_link($sortlink, $gpr, 'desc');
2633 if ($mode !== 'setup') {
2634 $context = grade_report
::get_additional_context($this->context
, $this->courseid
,
2635 $element, $gpr, $mode, $context);
2637 } else if ($element['type'] == 'category') {
2638 $context->datatype
= 'category';
2639 if ($mode !== 'setup') {
2641 $context = grade_report
::get_additional_context($this->context
, $this->courseid
,
2642 $element, $gpr, $mode, $context);
2644 $context->deleteurl
= $this->get_delete_link($element, $gpr);
2645 $context->resetweightsurl
= $this->get_reset_weights_link($element, $gpr);
2648 if (!empty($USER->editing
) ||
$mode == 'setup') {
2649 if ($mode !== 'setup') {
2650 $context->divider1
= true;
2652 $context->editurl
= $this->get_edit_link($element, $gpr);
2653 $context->hideurl
= $this->get_hiding_link($element, $gpr);
2654 $context->lockurl
= $this->get_locking_link($element, $gpr);
2658 if (isset($element['object'])) {
2659 $context->dataid
= $element['object']->id
;
2660 } else if ($element['type'] == 'userfield') {
2661 $context->dataid
= $element['name'];
2664 if ($element['type'] != 'text' && !empty($element['object']->feedback
)) {
2665 $viewfeedbackstring = get_string('viewfeedback', 'grades');
2666 $context->viewfeedbackurl
= html_writer
::link('#', $viewfeedbackstring, ['class' => 'dropdown-item',
2667 'aria-label' => $viewfeedbackstring, 'role' => 'menuitem', 'data-action' => 'feedback',
2668 'data-courseid' => $this->courseid
]);
2670 } else if ($mode == 'user') {
2671 $context->datatype
= 'user';
2672 $context = grade_report
::get_additional_context($this->context
, $this->courseid
, $element, $gpr, $mode, $context, true);
2673 $context->dataid
= $element['userid'];
2676 // Omit the second divider if there is nothing between it and the first divider.
2677 if (!isset($context->ascendingfirstnameurl
) && !isset($context->ascendingurl
)) {
2678 $context->divider2
= false;
2681 if ($mode == 'setup') {
2682 $context->databoundary
= 'window';
2685 if (!empty($USER->editing
) ||
isset($context->gradeanalysisurl
) ||
isset($context->gradesonlyurl
)
2686 ||
isset($context->aggregatesonlyurl
) ||
isset($context->fullmodeurl
) ||
isset($context->reporturl0
)
2687 ||
isset($context->ascendingfirstnameurl
) ||
isset($context->ascendingurl
)
2688 ||
isset($context->viewfeedbackurl
) ||
($mode == 'setup')) {
2689 return $OUTPUT->render_from_template('core_grades/cellmenu', $context);
2695 * Returns link to sort grade item column
2697 * @param moodle_url $sortlink A base link for sorting
2698 * @param object $gpr A grade_plugin_return object
2699 * @param string $direction Direction od sorting
2702 public function get_sorting_link(moodle_url
$sortlink, object $gpr, string $direction = 'asc'): string {
2704 if ($direction == 'asc') {
2705 $title = get_string('asc');
2707 $title = get_string('desc');
2710 $sortlink->param('sort', $direction);
2711 $gpr->add_url_params($sortlink);
2712 return html_writer
::link($sortlink, $title,
2713 ['class' => 'dropdown-item', 'aria-label' => $title, 'role' => 'menuitem']);
2719 * Flat structure similar to grade tree.
2721 * @uses grade_structure
2722 * @package core_grades
2723 * @copyright 2009 Nicolas Connault
2724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2726 class grade_seq
extends grade_structure
{
2729 * 1D array of elements
2734 * Constructor, retrieves and stores array of all grade_category and grade_item
2735 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2737 * @param int $courseid The course id
2738 * @param bool $category_grade_last category grade item is the last child
2739 * @param bool $nooutcomes Whether or not outcomes should be included
2741 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2744 $this->courseid
= $courseid;
2745 $this->context
= context_course
::instance($courseid);
2747 // get course grade tree
2748 $top_element = grade_category
::fetch_course_tree($courseid, true);
2750 $this->elements
= grade_seq
::flatten($top_element, $category_grade_last, $nooutcomes);
2752 foreach ($this->elements
as $key=>$unused) {
2753 $this->items
[$this->elements
[$key]['object']->id
] =& $this->elements
[$key]['object'];
2758 * Old syntax of class constructor. Deprecated in PHP7.
2760 * @deprecated since Moodle 3.1
2762 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2763 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2764 self
::__construct($courseid, $category_grade_last, $nooutcomes);
2768 * Static recursive helper - makes the grade_item for category the last children
2770 * @param array &$element The seed of the recursion
2771 * @param bool $category_grade_last category grade item is the last child
2772 * @param bool $nooutcomes Whether or not outcomes should be included
2776 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2777 if (empty($element['children'])) {
2780 $children = array();
2782 foreach ($element['children'] as $sortorder=>$unused) {
2783 if ($nooutcomes and $element['type'] != 'category' and
2784 $element['children'][$sortorder]['object']->is_outcome_item()) {
2787 $children[] = $element['children'][$sortorder];
2789 unset($element['children']);
2791 if ($category_grade_last and count($children) > 1 and
2793 $children[0]['type'] === 'courseitem' or
2794 $children[0]['type'] === 'categoryitem'
2797 $cat_item = array_shift($children);
2798 array_push($children, $cat_item);
2802 foreach ($children as $child) {
2803 if ($child['type'] == 'category') {
2804 $result = $result + grade_seq
::flatten($child, $category_grade_last, $nooutcomes);
2806 $child['eid'] = 'i'.$child['object']->id
;
2807 $result[$child['object']->id
] = $child;
2815 * Parses the array in search of a given eid and returns a element object with
2816 * information about the element it has found.
2818 * @param int $eid Gradetree Element ID
2820 * @return object element
2822 public function locate_element($eid) {
2823 // it is a grade - construct a new object
2824 if (strpos($eid, 'n') === 0) {
2825 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2829 $itemid = $matches[1];
2830 $userid = $matches[2];
2832 //extra security check - the grade item must be in this tree
2833 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2837 // $gradea->id may be null - means does not exist yet
2838 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2840 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2841 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2843 } else if (strpos($eid, 'g') === 0) {
2844 $id = (int) substr($eid, 1);
2845 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
2848 //extra security check - the grade item must be in this tree
2849 if (!$item_el = $this->locate_element('ig'.$grade->itemid
)) {
2852 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
2853 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2856 // it is a category or item
2857 foreach ($this->elements
as $element) {
2858 if ($element['eid'] == $eid) {
2868 * This class represents a complete tree of categories, grade_items and final grades,
2869 * organises as an array primarily, but which can also be converted to other formats.
2870 * It has simple method calls with complex implementations, allowing for easy insertion,
2871 * deletion and moving of items and categories within the tree.
2873 * @uses grade_structure
2874 * @package core_grades
2875 * @copyright 2009 Nicolas Connault
2876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2878 class grade_tree
extends grade_structure
{
2881 * The basic representation of the tree as a hierarchical, 3-tiered array.
2882 * @var object $top_element
2884 public $top_element;
2887 * 2D array of grade items and categories
2888 * @var array $levels
2899 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2900 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2902 * @param int $courseid The Course ID
2903 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2904 * @param bool $category_grade_last category grade item is the last child
2905 * @param array $collapsed array of collapsed categories
2906 * @param bool $nooutcomes Whether or not outcomes should be included
2908 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2909 $collapsed=null, $nooutcomes=false) {
2910 global $USER, $CFG, $COURSE, $DB;
2912 $this->courseid
= $courseid;
2913 $this->levels
= array();
2914 $this->context
= context_course
::instance($courseid);
2916 if (!empty($COURSE->id
) && $COURSE->id
== $this->courseid
) {
2919 $course = $DB->get_record('course', array('id' => $this->courseid
));
2921 $this->modinfo
= get_fast_modinfo($course);
2923 // get course grade tree
2924 $this->top_element
= grade_category
::fetch_course_tree($courseid, true);
2926 // collapse the categories if requested
2927 if (!empty($collapsed)) {
2928 grade_tree
::category_collapse($this->top_element
, $collapsed);
2931 // no otucomes if requested
2932 if (!empty($nooutcomes)) {
2933 grade_tree
::no_outcomes($this->top_element
);
2936 // move category item to last position in category
2937 if ($category_grade_last) {
2938 grade_tree
::category_grade_last($this->top_element
);
2942 // inject fake categories == fillers
2943 grade_tree
::inject_fillers($this->top_element
, 0);
2944 // add colspans to categories and fillers
2945 grade_tree
::inject_colspans($this->top_element
);
2948 grade_tree
::fill_levels($this->levels
, $this->top_element
, 0);
2953 * Old syntax of class constructor. Deprecated in PHP7.
2955 * @deprecated since Moodle 3.1
2957 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2958 $collapsed=null, $nooutcomes=false) {
2959 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
2960 self
::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2964 * Static recursive helper - removes items from collapsed categories
2966 * @param array &$element The seed of the recursion
2967 * @param array $collapsed array of collapsed categories
2971 public function category_collapse(&$element, $collapsed) {
2972 if ($element['type'] != 'category') {
2975 if (empty($element['children']) or count($element['children']) < 2) {
2979 if (in_array($element['object']->id
, $collapsed['aggregatesonly'])) {
2980 $category_item = reset($element['children']); //keep only category item
2981 $element['children'] = array(key($element['children'])=>$category_item);
2984 if (in_array($element['object']->id
, $collapsed['gradesonly'])) { // Remove category item
2985 reset($element['children']);
2986 $first_key = key($element['children']);
2987 unset($element['children'][$first_key]);
2989 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2990 grade_tree
::category_collapse($element['children'][$sortorder], $collapsed);
2996 * Static recursive helper - removes all outcomes
2998 * @param array &$element The seed of the recursion
3002 public function no_outcomes(&$element) {
3003 if ($element['type'] != 'category') {
3006 foreach ($element['children'] as $sortorder=>$child) {
3007 if ($element['children'][$sortorder]['type'] == 'item'
3008 and $element['children'][$sortorder]['object']->is_outcome_item()) {
3009 unset($element['children'][$sortorder]);
3011 } else if ($element['children'][$sortorder]['type'] == 'category') {
3012 grade_tree
::no_outcomes($element['children'][$sortorder]);
3018 * Static recursive helper - makes the grade_item for category the last children
3020 * @param array &$element The seed of the recursion
3024 public function category_grade_last(&$element) {
3025 if (empty($element['children'])) {
3028 if (count($element['children']) < 2) {
3031 $first_item = reset($element['children']);
3032 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3033 // the category item might have been already removed
3034 $order = key($element['children']);
3035 unset($element['children'][$order]);
3036 $element['children'][$order] =& $first_item;
3038 foreach ($element['children'] as $sortorder => $child) {
3039 grade_tree
::category_grade_last($element['children'][$sortorder]);
3044 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
3046 * @param array &$levels The levels of the grade tree through which to recurse
3047 * @param array &$element The seed of the recursion
3048 * @param int $depth How deep are we?
3051 public function fill_levels(&$levels, &$element, $depth) {
3052 if (!array_key_exists($depth, $levels)) {
3053 $levels[$depth] = array();
3056 // prepare unique identifier
3057 if ($element['type'] == 'category') {
3058 $element['eid'] = 'cg'.$element['object']->id
;
3059 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
3060 $element['eid'] = 'ig'.$element['object']->id
;
3061 $this->items
[$element['object']->id
] =& $element['object'];
3064 $levels[$depth][] =& $element;
3066 if (empty($element['children'])) {
3070 foreach ($element['children'] as $sortorder=>$child) {
3071 grade_tree
::fill_levels($levels, $element['children'][$sortorder], $depth);
3072 $element['children'][$sortorder]['prev'] = $prev;
3073 $element['children'][$sortorder]['next'] = 0;
3075 $element['children'][$prev]['next'] = $sortorder;
3082 * Determines whether the grade tree item can be displayed.
3083 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
3084 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
3087 * @param array $element The grade category element.
3088 * @return bool True if the grade tree item can be displayed. False, otherwise.
3090 public static function can_output_item($element) {
3093 if ($element['type'] === 'category') {
3094 $object = $element['object'];
3095 $category = grade_category
::fetch(array('id' => $object->id
));
3096 // Category has total, we can output this.
3097 if ($category->get_grade_item()->gradetype
!= GRADE_TYPE_NONE
) {
3101 // Category has no total and has no children, no need to output this.
3102 if (empty($element['children'])) {
3107 // Loop over children and make sure at least one child can be output.
3108 foreach ($element['children'] as $child) {
3109 $canoutput = self
::can_output_item($child);
3120 * Static recursive helper - makes full tree (all leafes are at the same level)
3122 * @param array &$element The seed of the recursion
3123 * @param int $depth How deep are we?
3127 public function inject_fillers(&$element, $depth) {
3130 if (empty($element['children'])) {
3133 $chdepths = array();
3134 $chids = array_keys($element['children']);
3135 $last_child = end($chids);
3136 $first_child = reset($chids);
3138 foreach ($chids as $chid) {
3139 $chdepths[$chid] = grade_tree
::inject_fillers($element['children'][$chid], $depth);
3143 $maxdepth = reset($chdepths);
3144 foreach ($chdepths as $chid=>$chd) {
3145 if ($chd == $maxdepth) {
3148 if (!self
::can_output_item($element['children'][$chid])) {
3151 for ($i=0; $i < $maxdepth-$chd; $i++
) {
3152 if ($chid == $first_child) {
3153 $type = 'fillerfirst';
3154 } else if ($chid == $last_child) {
3155 $type = 'fillerlast';
3159 $oldchild =& $element['children'][$chid];
3160 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
3161 'eid'=>'', 'depth'=>$element['object']->depth
,
3162 'children'=>array($oldchild));
3170 * Static recursive helper - add colspan information into categories
3172 * @param array &$element The seed of the recursion
3176 public function inject_colspans(&$element) {
3177 if (empty($element['children'])) {
3181 foreach ($element['children'] as $key=>$child) {
3182 if (!self
::can_output_item($child)) {
3185 $count +
= grade_tree
::inject_colspans($element['children'][$key]);
3187 $element['colspan'] = $count;
3192 * Parses the array in search of a given eid and returns a element object with
3193 * information about the element it has found.
3194 * @param int $eid Gradetree Element ID
3195 * @return object element
3197 public function locate_element($eid) {
3198 // it is a grade - construct a new object
3199 if (strpos($eid, 'n') === 0) {
3200 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
3204 $itemid = $matches[1];
3205 $userid = $matches[2];
3207 //extra security check - the grade item must be in this tree
3208 if (!$item_el = $this->locate_element('ig'.$itemid)) {
3212 // $gradea->id may be null - means does not exist yet
3213 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
3215 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
3216 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
3218 } else if (strpos($eid, 'g') === 0) {
3219 $id = (int) substr($eid, 1);
3220 if (!$grade = grade_grade
::fetch(array('id'=>$id))) {
3223 //extra security check - the grade item must be in this tree
3224 if (!$item_el = $this->locate_element('ig'.$grade->itemid
)) {
3227 $grade->grade_item
=& $item_el['object']; // this may speedup grade_grade methods!
3228 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
3231 // it is a category or item
3232 foreach ($this->levels
as $row) {
3233 foreach ($row as $element) {
3234 if ($element['type'] == 'filler') {
3237 if ($element['eid'] == $eid) {
3247 * Returns a well-formed XML representation of the grade-tree using recursion.
3249 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3250 * @param string $tabs The control character to use for tabs
3252 * @return string $xml
3254 public function exporttoxml($root=null, $tabs="\t") {
3257 if (is_null($root)) {
3258 $root = $this->top_element
;
3259 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
3260 $xml .= "<gradetree>\n";
3264 $type = 'undefined';
3265 if (strpos($root['object']->table
, 'grade_categories') !== false) {
3267 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
3269 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
3273 $xml .= "$tabs<element type=\"$type\">\n";
3274 foreach ($root['object'] as $var => $value) {
3275 if (!is_object($value) && !is_array($value) && !empty($value)) {
3276 $xml .= "$tabs\t<$var>$value</$var>\n";
3280 if (!empty($root['children'])) {
3281 $xml .= "$tabs\t<children>\n";
3282 foreach ($root['children'] as $sortorder => $child) {
3283 $xml .= $this->exportToXML($child, $tabs."\t\t");
3285 $xml .= "$tabs\t</children>\n";
3288 $xml .= "$tabs</element>\n";
3291 $xml .= "</gradetree>";
3298 * Returns a JSON representation of the grade-tree using recursion.
3300 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
3301 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
3305 public function exporttojson($root=null, $tabs="\t") {
3308 if (is_null($root)) {
3309 $root = $this->top_element
;
3316 if (strpos($root['object']->table
, 'grade_categories') !== false) {
3317 $name = $root['object']->fullname
;
3319 $name = $root['object']->get_name();
3321 } else if (strpos($root['object']->table
, 'grade_items') !== false) {
3322 $name = $root['object']->itemname
;
3323 } else if (strpos($root['object']->table
, 'grade_outcomes') !== false) {
3324 $name = $root['object']->itemname
;
3327 $json .= "$tabs {\n";
3328 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
3329 $json .= "$tabs\t \"name\": \"$name\",\n";
3331 foreach ($root['object'] as $var => $value) {
3332 if (!is_object($value) && !is_array($value) && !empty($value)) {
3333 $json .= "$tabs\t \"$var\": \"$value\",\n";
3337 $json = substr($json, 0, strrpos($json, ','));
3339 if (!empty($root['children'])) {
3340 $json .= ",\n$tabs\t\"children\": [\n";
3341 foreach ($root['children'] as $sortorder => $child) {
3342 $json .= $this->exportToJSON($child, $tabs."\t\t");
3344 $json = substr($json, 0, strrpos($json, ','));
3345 $json .= "\n$tabs\t]\n";
3351 $json .= "\n$tabs},\n";
3358 * Returns the array of levels
3362 public function get_levels() {
3363 return $this->levels
;
3367 * Returns the array of grade items
3371 public function get_items() {
3372 return $this->items
;
3376 * Returns a specific Grade Item
3378 * @param int $itemid The ID of the grade_item object
3380 * @return grade_item
3382 public function get_item($itemid) {
3383 if (array_key_exists($itemid, $this->items
)) {
3384 return $this->items
[$itemid];
3392 * Local shortcut function for creating an edit/delete button for a grade_* object.
3393 * @param string $type 'edit' or 'delete'
3394 * @param int $courseid The Course ID
3395 * @param grade_* $object The grade_* object
3396 * @return string html
3398 function grade_button($type, $courseid, $object) {
3399 global $CFG, $OUTPUT;
3400 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
3401 $objectidstring = $matches[1] . 'id';
3403 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
3406 $strdelete = get_string('delete');
3407 $stredit = get_string('edit');
3409 if ($type == 'delete') {
3410 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id
, 'action' => 'delete', 'sesskey' => sesskey()));
3411 } else if ($type == 'edit') {
3412 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id
));
3415 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $
{'str'.$type}, '', array('class' => 'iconsmall')));
3420 * This method adds settings to the settings block for the grade system and its
3423 * @global moodle_page $PAGE
3425 function grade_extend_settings($plugininfo, $courseid) {
3428 $gradenode = $PAGE->settingsnav
->prepend(get_string('gradeadministration', 'grades'), null, navigation_node
::TYPE_CONTAINER
,
3429 null, 'gradeadmin');
3431 $strings = array_shift($plugininfo);
3433 if ($reports = grade_helper
::get_plugins_reports($courseid)) {
3434 foreach ($reports as $report) {
3435 $gradenode->add($report->string, $report->link
, navigation_node
::TYPE_SETTING
, null, $report->id
, new pix_icon('i/report', ''));
3439 if ($settings = grade_helper
::get_info_manage_settings($courseid)) {
3440 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node
::TYPE_CONTAINER
);
3441 foreach ($settings as $setting) {
3442 $settingsnode->add($setting->string, $setting->link
, navigation_node
::TYPE_SETTING
, null, $setting->id
, new pix_icon('i/settings', ''));
3446 if ($imports = grade_helper
::get_plugins_import($courseid)) {
3447 $importnode = $gradenode->add($strings['import'], null, navigation_node
::TYPE_CONTAINER
);
3448 foreach ($imports as $import) {
3449 $importnode->add($import->string, $import->link
, navigation_node
::TYPE_SETTING
, null, $import->id
, new pix_icon('i/import', ''));
3453 if ($exports = grade_helper
::get_plugins_export($courseid)) {
3454 $exportnode = $gradenode->add($strings['export'], null, navigation_node
::TYPE_CONTAINER
);
3455 foreach ($exports as $export) {
3456 $exportnode->add($export->string, $export->link
, navigation_node
::TYPE_SETTING
, null, $export->id
, new pix_icon('i/export', ''));
3460 if ($letters = grade_helper
::get_info_letters($courseid)) {
3461 $letters = array_shift($letters);
3462 $gradenode->add($strings['letter'], $letters->link
, navigation_node
::TYPE_SETTING
, null, $letters->id
, new pix_icon('i/settings', ''));
3465 if ($outcomes = grade_helper
::get_info_outcomes($courseid)) {
3466 $outcomes = array_shift($outcomes);
3467 $gradenode->add($strings['outcome'], $outcomes->link
, navigation_node
::TYPE_SETTING
, null, $outcomes->id
, new pix_icon('i/outcomes', ''));
3470 if ($scales = grade_helper
::get_info_scales($courseid)) {
3471 $gradenode->add($strings['scale'], $scales->link
, navigation_node
::TYPE_SETTING
, null, $scales->id
, new pix_icon('i/scales', ''));
3474 if ($gradenode->contains_active_node()) {
3475 // If the gradenode is active include the settings base node (gradeadministration) in
3476 // the navbar, typcially this is ignored.
3477 $PAGE->navbar
->includesettingsbase
= true;
3479 // If we can get the course admin node make sure it is closed by default
3480 // as in this case the gradenode will be opened
3481 if ($coursenode = $PAGE->settingsnav
->get('courseadmin', navigation_node
::TYPE_COURSE
)){
3482 $coursenode->make_inactive();
3483 $coursenode->forceopen
= false;
3489 * Grade helper class
3491 * This class provides several helpful functions that work irrespective of any
3494 * @copyright 2010 Sam Hemelryk
3495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3497 abstract class grade_helper
{
3499 * Cached manage settings info {@see get_info_settings}
3500 * @var grade_plugin_info|false
3502 protected static $managesetting = null;
3504 * Cached grade report plugins {@see get_plugins_reports}
3507 protected static $gradereports = null;
3509 * Cached grade report plugins preferences {@see get_info_scales}
3512 protected static $gradereportpreferences = null;
3514 * Cached scale info {@see get_info_scales}
3515 * @var grade_plugin_info|false
3517 protected static $scaleinfo = null;
3519 * Cached outcome info {@see get_info_outcomes}
3520 * @var grade_plugin_info|false
3522 protected static $outcomeinfo = null;
3524 * Cached leftter info {@see get_info_letters}
3525 * @var grade_plugin_info|false
3527 protected static $letterinfo = null;
3529 * Cached grade import plugins {@see get_plugins_import}
3532 protected static $importplugins = null;
3534 * Cached grade export plugins {@see get_plugins_export}
3537 protected static $exportplugins = null;
3539 * Cached grade plugin strings
3542 protected static $pluginstrings = null;
3544 * Cached grade aggregation strings
3547 protected static $aggregationstrings = null;
3550 * Cached grade tree plugin strings
3553 protected static $langstrings = [];
3556 * First checks the cached language strings, then returns match if found, or uses get_string()
3557 * to get it from the DB, caches it then returns it.
3559 * @deprecated since 4.3
3560 * @todo MDL-78780 This will be deleted in Moodle 4.7.
3561 * @param string $strcode
3562 * @param string|null $section Optional language section
3565 public static function get_lang_string(string $strcode, ?
string $section = null): string {
3566 debugging('grade_helper::get_lang_string() is deprecated, please use' .
3567 ' get_string() instead.', DEBUG_DEVELOPER
);
3569 if (empty(self
::$langstrings[$strcode])) {
3570 self
::$langstrings[$strcode] = get_string($strcode, $section);
3572 return self
::$langstrings[$strcode];
3576 * Gets strings commonly used by the describe plugins
3578 * report => get_string('view'),
3579 * scale => get_string('scales'),
3580 * outcome => get_string('outcomes', 'grades'),
3581 * letter => get_string('letters', 'grades'),
3582 * export => get_string('export', 'grades'),
3583 * import => get_string('import'),
3584 * settings => get_string('settings')
3588 public static function get_plugin_strings() {
3589 if (self
::$pluginstrings === null) {
3590 self
::$pluginstrings = array(
3591 'report' => get_string('view'),
3592 'scale' => get_string('scales'),
3593 'outcome' => get_string('outcomes', 'grades'),
3594 'letter' => get_string('letters', 'grades'),
3595 'export' => get_string('export', 'grades'),
3596 'import' => get_string('import'),
3597 'settings' => get_string('edittree', 'grades')
3600 return self
::$pluginstrings;
3604 * Gets strings describing the available aggregation methods.
3608 public static function get_aggregation_strings() {
3609 if (self
::$aggregationstrings === null) {
3610 self
::$aggregationstrings = array(
3611 GRADE_AGGREGATE_MEAN
=> get_string('aggregatemean', 'grades'),
3612 GRADE_AGGREGATE_WEIGHTED_MEAN
=> get_string('aggregateweightedmean', 'grades'),
3613 GRADE_AGGREGATE_WEIGHTED_MEAN2
=> get_string('aggregateweightedmean2', 'grades'),
3614 GRADE_AGGREGATE_EXTRACREDIT_MEAN
=> get_string('aggregateextracreditmean', 'grades'),
3615 GRADE_AGGREGATE_MEDIAN
=> get_string('aggregatemedian', 'grades'),
3616 GRADE_AGGREGATE_MIN
=> get_string('aggregatemin', 'grades'),
3617 GRADE_AGGREGATE_MAX
=> get_string('aggregatemax', 'grades'),
3618 GRADE_AGGREGATE_MODE
=> get_string('aggregatemode', 'grades'),
3619 GRADE_AGGREGATE_SUM
=> get_string('aggregatesum', 'grades')
3622 return self
::$aggregationstrings;
3626 * Get grade_plugin_info object for managing settings if the user can
3628 * @param int $courseid
3629 * @return grade_plugin_info[]
3631 public static function get_info_manage_settings($courseid) {
3632 if (self
::$managesetting !== null) {
3633 return self
::$managesetting;
3635 $context = context_course
::instance($courseid);
3636 self
::$managesetting = array();
3637 if ($courseid != SITEID
&& has_capability('moodle/grade:manage', $context)) {
3638 self
::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
3639 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
3640 get_string('gradebooksetup', 'grades'));
3641 self
::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
3642 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
3643 get_string('coursegradesettings', 'grades'));
3645 if (self
::$gradereportpreferences === null) {
3646 self
::get_plugins_reports($courseid);
3648 if (self
::$gradereportpreferences) {
3649 self
::$managesetting = array_merge(self
::$managesetting, self
::$gradereportpreferences);
3651 return self
::$managesetting;
3654 * Returns an array of plugin reports as grade_plugin_info objects
3656 * @param int $courseid
3659 public static function get_plugins_reports($courseid) {
3662 if (self
::$gradereports !== null) {
3663 return self
::$gradereports;
3665 $context = context_course
::instance($courseid);
3666 $gradereports = array();
3667 $gradepreferences = array();
3668 foreach (core_component
::get_plugin_list('gradereport') as $plugin => $plugindir) {
3669 //some reports make no sense if we're not within a course
3670 if ($courseid==$SITE->id
&& ($plugin=='grader' ||
$plugin=='user')) {
3674 // Remove outcomes report if outcomes not enabled.
3675 if ($plugin === 'outcomes' && empty($CFG->enableoutcomes
)) {
3679 // Remove ones we can't see
3680 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
3684 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
3685 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
3686 'moodle/grade:edit'), $context)) {
3690 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
3691 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
3692 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3694 // Add link to preferences tab if such a page exists
3695 if (file_exists($plugindir.'/preferences.php')) {
3696 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id' => $courseid));
3697 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
3698 get_string('preferences', 'grades') . ': ' . $pluginstr);
3701 if (count($gradereports) == 0) {
3702 $gradereports = false;
3703 $gradepreferences = false;
3704 } else if (count($gradepreferences) == 0) {
3705 $gradepreferences = false;
3706 asort($gradereports);
3708 asort($gradereports);
3709 asort($gradepreferences);
3711 self
::$gradereports = $gradereports;
3712 self
::$gradereportpreferences = $gradepreferences;
3713 return self
::$gradereports;
3717 * Get information on scales
3718 * @param int $courseid
3719 * @return grade_plugin_info
3721 public static function get_info_scales($courseid) {
3722 if (self
::$scaleinfo !== null) {
3723 return self
::$scaleinfo;
3725 if (has_capability('moodle/course:managescales', context_course
::instance($courseid))) {
3726 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3727 self
::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3729 self
::$scaleinfo = false;
3731 return self
::$scaleinfo;
3734 * Get information on outcomes
3735 * @param int $courseid
3736 * @return grade_plugin_info[]|false
3738 public static function get_info_outcomes($courseid) {
3741 if (self
::$outcomeinfo !== null) {
3742 return self
::$outcomeinfo;
3744 $context = context_course
::instance($courseid);
3745 $canmanage = has_capability('moodle/grade:manage', $context);
3746 $canupdate = has_capability('moodle/course:update', $context);
3747 if (!empty($CFG->enableoutcomes
) && ($canmanage ||
$canupdate)) {
3748 $outcomes = array();
3750 if ($courseid!=$SITE->id
) {
3751 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3752 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3754 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3755 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3756 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3757 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3759 if ($courseid!=$SITE->id
) {
3760 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3761 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3764 self
::$outcomeinfo = $outcomes;
3766 self
::$outcomeinfo = false;
3768 return self
::$outcomeinfo;
3771 * Get information on letters
3772 * @param int $courseid
3775 public static function get_info_letters($courseid) {
3777 if (self
::$letterinfo !== null) {
3778 return self
::$letterinfo;
3780 $context = context_course
::instance($courseid);
3781 $canmanage = has_capability('moodle/grade:manage', $context);
3782 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3783 if ($canmanage ||
$canmanageletters) {
3784 // Redirect to system context when report is accessed from admin settings MDL-31633
3785 if ($context->instanceid
== $SITE->id
) {
3786 $param = array('edit' => 1);
3788 $param = array('edit' => 1,'id' => $context->id
);
3790 self
::$letterinfo = array(
3791 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id
)), get_string('view')),
3792 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3795 self
::$letterinfo = false;
3797 return self
::$letterinfo;
3800 * Get information import plugins
3801 * @param int $courseid
3804 public static function get_plugins_import($courseid) {
3807 if (self
::$importplugins !== null) {
3808 return self
::$importplugins;
3810 $importplugins = array();
3811 $context = context_course
::instance($courseid);
3813 if (has_capability('moodle/grade:import', $context)) {
3814 foreach (core_component
::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3815 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3818 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3819 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3820 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3823 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3824 // XML is the only grade import plugin that has publishing feature.
3825 if ($CFG->gradepublishing
&& has_capability('gradeimport/xml:publish', $context)) {
3826 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3827 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3831 if (count($importplugins) > 0) {
3832 asort($importplugins);
3833 self
::$importplugins = $importplugins;
3835 self
::$importplugins = false;
3837 return self
::$importplugins;
3840 * Get information export plugins
3841 * @param int $courseid
3844 public static function get_plugins_export($courseid) {
3847 if (self
::$exportplugins !== null) {
3848 return self
::$exportplugins;
3850 $context = context_course
::instance($courseid);
3851 $exportplugins = array();
3852 $canpublishgrades = 0;
3853 if (has_capability('moodle/grade:export', $context)) {
3854 foreach (core_component
::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3855 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3858 // All the grade export plugins has grade publishing capabilities.
3859 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3860 $canpublishgrades++
;
3863 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3864 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3865 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3868 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3869 if ($CFG->gradepublishing
&& $canpublishgrades != 0) {
3870 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3871 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3874 if (count($exportplugins) > 0) {
3875 asort($exportplugins);
3876 self
::$exportplugins = $exportplugins;
3878 self
::$exportplugins = false;
3880 return self
::$exportplugins;
3884 * Returns the value of a field from a user record
3886 * @param stdClass $user object
3887 * @param stdClass $field object
3888 * @return string value of the field
3890 public static function get_user_field_value($user, $field) {
3891 if (!empty($field->customid
)) {
3892 $fieldname = 'customfield_' . $field->customid
;
3893 if (!empty($user->{$fieldname}) ||
is_numeric($user->{$fieldname})) {
3894 $fieldvalue = $user->{$fieldname};
3896 $fieldvalue = $field->default;
3899 $fieldvalue = $user->{$field->shortname
};
3905 * Returns an array of user profile fields to be included in export
3907 * @param int $courseid
3908 * @param bool $includecustomfields
3909 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3911 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3914 // Gets the fields that have to be hidden
3915 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields
));
3916 $context = context_course
::instance($courseid);
3917 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3918 if ($canseehiddenfields) {
3919 $hiddenfields = array();
3923 require_once($CFG->dirroot
.'/user/lib.php'); // Loads user_get_default_fields()
3924 require_once($CFG->dirroot
.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3925 $userdefaultfields = user_get_default_fields();
3927 // Sets the list of profile fields
3928 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields
));
3929 if (!empty($userprofilefields)) {
3930 foreach ($userprofilefields as $field) {
3931 $field = trim($field);
3932 if (in_array($field, $hiddenfields) ||
!in_array($field, $userdefaultfields)) {
3935 $obj = new stdClass();
3937 $obj->shortname
= $field;
3938 $obj->fullname
= get_string($field);
3943 // Sets the list of custom profile fields
3944 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields
));
3945 if ($includecustomfields && !empty($customprofilefields)) {
3946 $customfields = profile_get_user_fields_with_data(0);
3948 foreach ($customfields as $fieldobj) {
3949 $field = (object)$fieldobj->get_field_config_for_external();
3950 // Make sure we can display this custom field
3951 if (!in_array($field->shortname
, $customprofilefields)) {
3953 } else if (in_array($field->shortname
, $hiddenfields)) {
3955 } else if ($field->visible
!= PROFILE_VISIBLE_ALL
&& !$canseehiddenfields) {
3959 $obj = new stdClass();
3960 $obj->customid
= $field->id
;
3961 $obj->shortname
= $field->shortname
;
3962 $obj->fullname
= format_string($field->name
);
3963 $obj->datatype
= $field->datatype
;
3964 $obj->default = $field->defaultdata
;
3973 * This helper method gets a snapshot of all the weights for a course.
3974 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3975 * @param int $courseid
3976 * @return array of itemid -> aggregationcoef2
3978 public static function fetch_all_natural_weights_for_course($courseid) {
3982 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3983 foreach ($records as $record) {
3984 $result[$record->id
] = $record->aggregationcoef2
;
3990 * Resets all static caches.
3994 public static function reset_caches() {
3995 self
::$managesetting = null;
3996 self
::$gradereports = null;
3997 self
::$gradereportpreferences = null;
3998 self
::$scaleinfo = null;
3999 self
::$outcomeinfo = null;
4000 self
::$letterinfo = null;
4001 self
::$importplugins = null;
4002 self
::$exportplugins = null;
4003 self
::$pluginstrings = null;
4004 self
::$aggregationstrings = null;