MDL-74802 core_user: Use button label to close notification alert
[moodle.git] / grade / lib.php
blob5e895f6154de9d75671276ed44f32dfe7d5f893f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir . '/gradelib.php');
26 require_once($CFG->dirroot . '/grade/export/lib.php');
28 use \core_grades\output\action_bar;
29 use \core_grades\output\general_action_bar;
31 /**
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 {
40 /**
41 * The couse whose users we are interested in
43 protected $course;
45 /**
46 * An array of grade items or null if only user data was requested
48 protected $grade_items;
50 /**
51 * The group ID we are interested in. 0 means all groups.
53 protected $groupid;
55 /**
56 * A recordset of graded users
58 protected $users_rs;
60 /**
61 * A recordset of user grades (grade_grade instances)
63 protected $grades_rs;
65 /**
66 * Array used when moving to next user while iterating through the grades recordset
68 protected $gradestack;
70 /**
71 * The first field of the users table by which the array of users will be sorted
73 protected $sortfield1;
75 /**
76 * Should sortfield1 be ASC or DESC
78 protected $sortorder1;
80 /**
81 * The second field of the users table by which the array of users will be sorted
83 protected $sortfield2;
85 /**
86 * Should sortfield2 be ASC or DESC
88 protected $sortorder2;
90 /**
91 * Should users whose enrolment has been suspended be ignored?
93 protected $onlyactive = false;
95 /**
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();
107 * Constructor
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() {
137 global $CFG, $DB;
139 $this->close();
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.
145 return false;
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;
161 } else {
162 $groupsql = "";
163 $groupwheresql = "";
166 if (empty($this->sortfield1)) {
167 // We must do some sorting even if not specified.
168 $ofields = ", u.id AS usrt";
169 $order = "usrt ASC";
171 } else {
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";
186 $userfields = 'u.*';
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
205 FROM {user} u
206 JOIN ($enrolledsql) je ON je.id = u.id
207 $groupsql $customfieldssql
208 JOIN (
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
214 WHERE u.deleted = 0
215 $groupwheresql
216 ORDER BY $order";
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);
222 } else {
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
235 $groupsql
236 JOIN (
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
242 WHERE u.deleted = 0
243 AND g.itemid $itemidsql
244 $groupwheresql
245 ORDER BY $order, g.itemid ASC";
246 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
247 } else {
248 $this->grades_rs = false;
251 return true;
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
269 } else {
270 $user = $this->users_rs->current();
271 $this->users_rs->next();
274 // find grades of this user
275 $grade_records = array();
276 while (true) {
277 if (!$current = $this->_pop()) {
278 break; // no more grades
281 if (empty($current->userid)) {
282 break;
285 if ($current->userid != $user->id) {
286 // grade of the next user, we have all for this user
287 $this->_push($current);
288 break;
291 $grade_records[$current->itemid] = $current;
294 $grades = array();
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);
308 } else {
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;
324 return $result;
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
358 * @return void
360 public function allow_user_custom_fields($allow = true) {
361 if ($allow) {
362 $this->allowusercustomfields = true;
363 } else {
364 $this->allowusercustomfields = false;
369 * Add a grade_grade instance to the grade stack
371 * @param grade_grade $grade Grade object
373 * @return void
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() {
386 global $DB;
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();
396 return $current;
397 } else {
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
414 * @return null
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) {
422 global $USER, $CFG;
424 if (is_null($userid)) {
425 $userid = $USER->id;
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);
435 $gui->init();
436 $label = get_string('selectauser', 'grades');
437 if ($includeall) {
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;
446 } else {
447 $menu[$user->id] = $userfullname;
450 $gui->close();
452 if ($includeall) {
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';
466 return $select;
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;
547 $html = '';
549 // Do not do anything if they cannot manage the grades of this course.
550 if (!has_capability('moodle/grade:manage', $context)) {
551 return $html;
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');
673 } else {
674 // Show the warning that there may be extra credit weights problems.
675 $a = new stdClass();
676 $a->gradebookversion = $gradebookcalculationsfreeze;
677 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
678 $a->currentversion = $matches[1];
679 } else {
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);
693 $html .= $fixbutton;
697 if (!empty($html)) {
698 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
701 if ($return) {
702 return $html;
703 } else {
704 echo $html;
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, ...
715 * @return array
717 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
718 global $CFG, $SITE;
720 $context = context_course::instance($courseid);
722 $plugin_info = array();
723 $count = 0;
724 $active = '';
725 $url_prefix = $CFG->wwwroot . '/grade/';
727 // Language strings
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
759 // in the gradebook.
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;
770 break;
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;
781 return $plugin_info;
785 * A simple class containing info about grade plugins.
786 * Can be subclassed for special rules
788 * @package core_grades
789 * @copyright 2009 Nicolas Connault
790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
792 class grade_plugin_info {
794 * A unique id for this plugin
796 * @var mixed
798 public $id;
800 * A URL to access this plugin
802 * @var mixed
804 public $link;
806 * The name of this plugin
808 * @var mixed
810 public $string;
812 * Another grade_plugin_info object, parent of the current one
814 * @var mixed
816 public $parent;
819 * Constructor
821 * @param int $id A unique id for this plugin
822 * @param string $link A URL to access this plugin
823 * @param string $string The name of this plugin
824 * @param object $parent Another grade_plugin_info object, parent of the current one
826 * @return void
828 public function __construct($id, $link, $string, $parent=null) {
829 $this->id = $id;
830 $this->link = $link;
831 $this->string = $string;
832 $this->parent = $parent;
837 * Prints the page headers, breadcrumb trail, page heading, (optional) navigation and for any gradebook page.
838 * All gradebook pages MUST use these functions in favour of the usual print_header(), print_header_simple(),
839 * print_heading() etc.
841 * @param int $courseid Course id
842 * @param string $active_type The type of the current page (report, settings,
843 * import, export, scales, outcomes, letters)
844 * @param string|null $active_plugin The plugin of the current page (grader, fullview etc...)
845 * @param string|bool $heading The heading of the page. Tries to guess if none is given
846 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
847 * @param string|bool $buttons Additional buttons to display on the page
848 * @param boolean $shownavigation should the gradebook navigation be shown?
849 * @param string|null $headerhelpidentifier The help string identifier if required.
850 * @param string|null $headerhelpcomponent The component for the help string.
851 * @param stdClass|null $user The user object for use with the user context header.
852 * @param actionbar|null $actionbar The actions bar which will be displayed on the page if $shownavigation is set
853 * to true. If $actionbar is not explicitly defined, the general action bar
854 * (\core_grades\output\general_action_bar) will be used by default.
855 * @return string HTML code or nothing if $return == false
857 function print_grade_page_head(int $courseid, string $active_type, ?string $active_plugin = null, $heading = false,
858 bool $return = false, $buttons = false, bool $shownavigation = true, ?string $headerhelpidentifier = null,
859 ?string $headerhelpcomponent = null, ?stdClass $user = null, ?action_bar $actionbar = null) {
860 global $CFG, $OUTPUT, $PAGE;
862 // Put a warning on all gradebook pages if the course has modules currently scheduled for background deletion.
863 require_once($CFG->dirroot . '/course/lib.php');
864 if (course_modules_pending_deletion($courseid, true)) {
865 \core\notification::add(get_string('gradesmoduledeletionpendingwarning', 'grades'),
866 \core\output\notification::NOTIFY_WARNING);
869 if ($active_type === 'preferences') {
870 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
871 $active_type = 'settings';
874 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
876 // Determine the string of the active plugin
877 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
878 $stractive_type = $plugin_info['strings'][$active_type];
880 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
881 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
882 } else {
883 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
886 if ($active_type == 'report') {
887 $PAGE->set_pagelayout('report');
888 } else {
889 $PAGE->set_pagelayout('admin');
891 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
892 $PAGE->set_heading($title);
893 $PAGE->set_secondary_active_tab('grades');
895 if ($buttons instanceof single_button) {
896 $buttons = $OUTPUT->render($buttons);
898 $PAGE->set_button($buttons);
899 if ($courseid != SITEID) {
900 grade_extend_settings($plugin_info, $courseid);
903 // Set the current report as active in the breadcrumbs.
904 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
905 $reportnav->make_active();
908 $returnval = $OUTPUT->header();
910 if (!$return) {
911 echo $returnval;
914 // Guess heading if not given explicitly
915 if (!$heading) {
916 $heading = $stractive_plugin;
919 if ($shownavigation) {
920 $renderer = $PAGE->get_renderer('core_grades');
921 // If the navigation action bar is not explicitly defined, use the general (default) action bar.
922 if (!$actionbar) {
923 $actionbar = new general_action_bar($PAGE->context, $PAGE->url, $active_type, $active_plugin);
926 if ($return) {
927 $returnval .= $renderer->render_action_bar($actionbar);
928 } else {
929 echo $renderer->render_action_bar($actionbar);
933 $output = '';
934 // Add a help dialogue box if provided.
935 if (isset($headerhelpidentifier)) {
936 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
937 } else {
938 if (isset($user)) {
939 $output = $OUTPUT->context_header(
940 array(
941 'heading' => html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id,
942 'course' => $courseid)), fullname($user)),
943 'user' => $user,
944 'usercontext' => context_user::instance($user->id)
945 ), 2
947 } else {
948 $output = $OUTPUT->heading($heading);
952 if ($return) {
953 $returnval .= $output;
954 } else {
955 echo $output;
958 $returnval .= print_natural_aggregation_upgrade_notice($courseid, context_course::instance($courseid), $PAGE->url,
959 $return);
961 if ($return) {
962 return $returnval;
967 * Utility class used for return tracking when using edit and other forms in grade plugins
969 * @package core_grades
970 * @copyright 2009 Nicolas Connault
971 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
973 class grade_plugin_return {
975 * Type of grade plugin (e.g. 'edit', 'report')
977 * @var string
979 public $type;
981 * Name of grade plugin (e.g. 'grader', 'overview')
983 * @var string
985 public $plugin;
987 * Course id being viewed
989 * @var int
991 public $courseid;
993 * Id of user whose information is being viewed/edited
995 * @var int
997 public $userid;
999 * Id of group for which information is being viewed/edited
1001 * @var int
1003 public $groupid;
1005 * Current page # within output
1007 * @var int
1009 public $page;
1012 * Constructor
1014 * @param array $params - associative array with return parameters, if not supplied parameter are taken from _GET or _POST
1016 public function __construct($params = []) {
1017 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1018 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1019 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1020 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1021 $this->groupid = optional_param('gpr_groupid', null, PARAM_INT);
1022 $this->page = optional_param('gpr_page', null, PARAM_INT);
1024 foreach ($params as $key => $value) {
1025 if (property_exists($this, $key)) {
1026 $this->$key = $value;
1029 // Allow course object rather than id to be used to specify course
1030 // - avoid unnecessary use of get_course.
1031 if (array_key_exists('course', $params)) {
1032 $course = $params['course'];
1033 $this->courseid = $course->id;
1034 } else {
1035 $course = null;
1037 // If group has been explicitly set in constructor parameters,
1038 // we should respect that.
1039 if (!array_key_exists('groupid', $params)) {
1040 // Otherwise, 'group' in request parameters is a request for a change.
1041 // In that case, or if we have no group at all, we should get groupid from
1042 // groups_get_course_group, which will do some housekeeping as well as
1043 // give us the correct value.
1044 $changegroup = optional_param('group', -1, PARAM_INT);
1045 if ($changegroup !== -1 or (empty($this->groupid) and !empty($this->courseid))) {
1046 if ($course === null) {
1047 $course = get_course($this->courseid);
1049 $this->groupid = groups_get_course_group($course, true);
1055 * Old syntax of class constructor. Deprecated in PHP7.
1057 * @deprecated since Moodle 3.1
1059 public function grade_plugin_return($params = null) {
1060 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1061 self::__construct($params);
1065 * Returns return parameters as options array suitable for buttons.
1066 * @return array options
1068 public function get_options() {
1069 if (empty($this->type)) {
1070 return array();
1073 $params = array();
1075 if (!empty($this->plugin)) {
1076 $params['plugin'] = $this->plugin;
1079 if (!empty($this->courseid)) {
1080 $params['id'] = $this->courseid;
1083 if (!empty($this->userid)) {
1084 $params['userid'] = $this->userid;
1087 if (!empty($this->groupid)) {
1088 $params['group'] = $this->groupid;
1091 if (!empty($this->page)) {
1092 $params['page'] = $this->page;
1095 return $params;
1099 * Returns return url
1101 * @param string $default default url when params not set
1102 * @param array $extras Extra URL parameters
1104 * @return string url
1106 public function get_return_url($default, $extras=null) {
1107 global $CFG;
1109 if (empty($this->type) or empty($this->plugin)) {
1110 return $default;
1113 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1114 $glue = '?';
1116 if (!empty($this->courseid)) {
1117 $url .= $glue.'id='.$this->courseid;
1118 $glue = '&amp;';
1121 if (!empty($this->userid)) {
1122 $url .= $glue.'userid='.$this->userid;
1123 $glue = '&amp;';
1126 if (!empty($this->groupid)) {
1127 $url .= $glue.'group='.$this->groupid;
1128 $glue = '&amp;';
1131 if (!empty($this->page)) {
1132 $url .= $glue.'page='.$this->page;
1133 $glue = '&amp;';
1136 if (!empty($extras)) {
1137 foreach ($extras as $key=>$value) {
1138 $url .= $glue.$key.'='.$value;
1139 $glue = '&amp;';
1143 return $url;
1147 * Returns string with hidden return tracking form elements.
1148 * @return string
1150 public function get_form_fields() {
1151 if (empty($this->type)) {
1152 return '';
1155 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1157 if (!empty($this->plugin)) {
1158 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1161 if (!empty($this->courseid)) {
1162 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1165 if (!empty($this->userid)) {
1166 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1169 if (!empty($this->groupid)) {
1170 $result .= '<input type="hidden" name="gpr_groupid" value="'.$this->groupid.'" />';
1173 if (!empty($this->page)) {
1174 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1176 return $result;
1180 * Add hidden elements into mform
1182 * @param object &$mform moodle form object
1184 * @return void
1186 public function add_mform_elements(&$mform) {
1187 if (empty($this->type)) {
1188 return;
1191 $mform->addElement('hidden', 'gpr_type', $this->type);
1192 $mform->setType('gpr_type', PARAM_SAFEDIR);
1194 if (!empty($this->plugin)) {
1195 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1196 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1199 if (!empty($this->courseid)) {
1200 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1201 $mform->setType('gpr_courseid', PARAM_INT);
1204 if (!empty($this->userid)) {
1205 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1206 $mform->setType('gpr_userid', PARAM_INT);
1209 if (!empty($this->groupid)) {
1210 $mform->addElement('hidden', 'gpr_groupid', $this->groupid);
1211 $mform->setType('gpr_groupid', PARAM_INT);
1214 if (!empty($this->page)) {
1215 $mform->addElement('hidden', 'gpr_page', $this->page);
1216 $mform->setType('gpr_page', PARAM_INT);
1221 * Add return tracking params into url
1223 * @param moodle_url $url A URL
1225 * @return string $url with return tracking params
1227 public function add_url_params(moodle_url $url) {
1228 if (empty($this->type)) {
1229 return $url;
1232 $url->param('gpr_type', $this->type);
1234 if (!empty($this->plugin)) {
1235 $url->param('gpr_plugin', $this->plugin);
1238 if (!empty($this->courseid)) {
1239 $url->param('gpr_courseid' ,$this->courseid);
1242 if (!empty($this->userid)) {
1243 $url->param('gpr_userid', $this->userid);
1246 if (!empty($this->groupid)) {
1247 $url->param('gpr_groupid', $this->groupid);
1250 if (!empty($this->page)) {
1251 $url->param('gpr_page', $this->page);
1254 return $url;
1259 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1261 * @param string $path The path of the calling script (using __FILE__?)
1262 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1263 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1264 * an array of keys and values (e.g courseid => $courseid, itemid...)
1266 * @return string
1268 function grade_build_nav($path, $pagename=null, $id=null) {
1269 global $CFG, $COURSE, $PAGE;
1271 $strgrades = get_string('grades', 'grades');
1273 // Parse the path and build navlinks from its elements
1274 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1275 $path = substr($path, $dirroot_length);
1276 $path = str_replace('\\', '/', $path);
1278 $path_elements = explode('/', $path);
1280 $path_elements_count = count($path_elements);
1282 // First link is always 'grade'
1283 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1285 $link = null;
1286 $numberofelements = 3;
1288 // Prepare URL params string
1289 $linkparams = array();
1290 if (!is_null($id)) {
1291 if (is_array($id)) {
1292 foreach ($id as $idkey => $idvalue) {
1293 $linkparams[$idkey] = $idvalue;
1295 } else {
1296 $linkparams['id'] = $id;
1300 $navlink4 = null;
1302 // Remove file extensions from filenames
1303 foreach ($path_elements as $key => $filename) {
1304 $path_elements[$key] = str_replace('.php', '', $filename);
1307 // Second level links
1308 switch ($path_elements[1]) {
1309 case 'edit': // No link
1310 if ($path_elements[3] != 'index.php') {
1311 $numberofelements = 4;
1313 break;
1314 case 'import': // No link
1315 break;
1316 case 'export': // No link
1317 break;
1318 case 'report':
1319 // $id is required for this link. Do not print it if $id isn't given
1320 if (!is_null($id)) {
1321 $link = new moodle_url('/grade/report/index.php', $linkparams);
1324 if ($path_elements[2] == 'grader') {
1325 $numberofelements = 4;
1327 break;
1329 default:
1330 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1331 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1332 " as the second path element after 'grade'.");
1333 return false;
1335 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1337 // Third level links
1338 if (empty($pagename)) {
1339 $pagename = get_string($path_elements[2], 'grades');
1342 switch ($numberofelements) {
1343 case 3:
1344 $PAGE->navbar->add($pagename, $link);
1345 break;
1346 case 4:
1347 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1348 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1350 $PAGE->navbar->add($pagename);
1351 break;
1354 return '';
1358 * General structure representing grade items in course
1360 * @package core_grades
1361 * @copyright 2009 Nicolas Connault
1362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1364 class grade_structure {
1365 public $context;
1367 public $courseid;
1370 * Reference to modinfo for current course (for performance, to save
1371 * retrieving it from courseid every time). Not actually set except for
1372 * the grade_tree type.
1373 * @var course_modinfo
1375 public $modinfo;
1378 * 1D array of grade items only
1380 public $items;
1383 * Returns icon of element
1385 * @param array &$element An array representing an element in the grade_tree
1386 * @param bool $spacerifnone return spacer if no icon found
1388 * @return string icon or spacer
1390 public function get_element_icon(&$element, $spacerifnone=false) {
1391 global $CFG, $OUTPUT;
1392 require_once $CFG->libdir.'/filelib.php';
1394 $outputstr = '';
1396 // Object holding pix_icon information before instantiation.
1397 $icon = new stdClass();
1398 $icon->attributes = array(
1399 'class' => 'icon itemicon'
1401 $icon->component = 'moodle';
1403 $none = true;
1404 switch ($element['type']) {
1405 case 'item':
1406 case 'courseitem':
1407 case 'categoryitem':
1408 $none = false;
1410 $is_course = $element['object']->is_course_item();
1411 $is_category = $element['object']->is_category_item();
1412 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1413 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1414 $is_outcome = !empty($element['object']->outcomeid);
1416 if ($element['object']->is_calculated()) {
1417 $icon->pix = 'i/calc';
1418 $icon->title = s(get_string('calculatedgrade', 'grades'));
1420 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1421 if ($category = $element['object']->get_item_category()) {
1422 $aggrstrings = grade_helper::get_aggregation_strings();
1423 $stragg = $aggrstrings[$category->aggregation];
1425 $icon->pix = 'i/calc';
1426 $icon->title = s($stragg);
1428 switch ($category->aggregation) {
1429 case GRADE_AGGREGATE_MEAN:
1430 case GRADE_AGGREGATE_MEDIAN:
1431 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1432 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1433 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1434 $icon->pix = 'i/agg_mean';
1435 break;
1436 case GRADE_AGGREGATE_SUM:
1437 $icon->pix = 'i/agg_sum';
1438 break;
1442 } else if ($element['object']->itemtype == 'mod') {
1443 // Prevent outcomes displaying the same icon as the activity they are attached to.
1444 if ($is_outcome) {
1445 $icon->pix = 'i/outcomes';
1446 $icon->title = s(get_string('outcome', 'grades'));
1447 } else {
1448 $modinfo = get_fast_modinfo($element['object']->courseid);
1449 $module = $element['object']->itemmodule;
1450 $instanceid = $element['object']->iteminstance;
1451 if (isset($modinfo->instances[$module][$instanceid])) {
1452 $icon->url = $modinfo->instances[$module][$instanceid]->get_icon_url();
1453 } else {
1454 $icon->pix = 'monologo';
1455 $icon->component = $element['object']->itemmodule;
1457 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1459 } else if ($element['object']->itemtype == 'manual') {
1460 if ($element['object']->is_outcome_item()) {
1461 $icon->pix = 'i/outcomes';
1462 $icon->title = s(get_string('outcome', 'grades'));
1463 } else {
1464 $icon->pix = 'i/manual_item';
1465 $icon->title = s(get_string('manualitem', 'grades'));
1468 break;
1470 case 'category':
1471 $none = false;
1472 $icon->pix = 'i/folder';
1473 $icon->title = s(get_string('category', 'grades'));
1474 break;
1477 if ($none) {
1478 if ($spacerifnone) {
1479 $outputstr = $OUTPUT->spacer() . ' ';
1481 } else if (isset($icon->url)) {
1482 $outputstr = html_writer::img($icon->url, $icon->title, $icon->attributes);
1483 } else {
1484 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1487 return $outputstr;
1491 * Returns name of element optionally with icon and link
1493 * @param array &$element An array representing an element in the grade_tree
1494 * @param bool $withlink Whether or not this header has a link
1495 * @param bool $icon Whether or not to display an icon with this header
1496 * @param bool $spacerifnone return spacer if no icon found
1497 * @param bool $withdescription Show description if defined by this item.
1498 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1499 * instead of "Category total" or "Course total"
1501 * @return string header
1503 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1504 $withdescription = false, $fulltotal = false) {
1505 $header = '';
1507 if ($icon) {
1508 $header .= $this->get_element_icon($element, $spacerifnone);
1511 $title = $element['object']->get_name($fulltotal);
1512 $titleunescaped = $element['object']->get_name($fulltotal, false);
1513 $header .= $title;
1515 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1516 $element['type'] != 'courseitem') {
1517 return $header;
1520 if ($withlink && $url = $this->get_activity_link($element)) {
1521 $a = new stdClass();
1522 $a->name = get_string('modulename', $element['object']->itemmodule);
1523 $a->title = $titleunescaped;
1524 $title = get_string('linktoactivity', 'grades', $a);
1526 $header = html_writer::link($url, $header, array('title' => $title, 'class' => 'gradeitemheader'));
1527 } else {
1528 $header = html_writer::span($header, 'gradeitemheader', array('title' => $titleunescaped, 'tabindex' => '0'));
1531 if ($withdescription) {
1532 $desc = $element['object']->get_description();
1533 if (!empty($desc)) {
1534 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1538 return $header;
1541 private function get_activity_link($element) {
1542 global $CFG;
1543 /** @var array static cache of the grade.php file existence flags */
1544 static $hasgradephp = array();
1546 $itemtype = $element['object']->itemtype;
1547 $itemmodule = $element['object']->itemmodule;
1548 $iteminstance = $element['object']->iteminstance;
1549 $itemnumber = $element['object']->itemnumber;
1551 // Links only for module items that have valid instance, module and are
1552 // called from grade_tree with valid modinfo
1553 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1554 return null;
1557 // Get $cm efficiently and with visibility information using modinfo
1558 $instances = $this->modinfo->get_instances();
1559 if (empty($instances[$itemmodule][$iteminstance])) {
1560 return null;
1562 $cm = $instances[$itemmodule][$iteminstance];
1564 // Do not add link if activity is not visible to the current user
1565 if (!$cm->uservisible) {
1566 return null;
1569 if (!array_key_exists($itemmodule, $hasgradephp)) {
1570 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1571 $hasgradephp[$itemmodule] = true;
1572 } else {
1573 $hasgradephp[$itemmodule] = false;
1577 // If module has grade.php, link to that, otherwise view.php
1578 if ($hasgradephp[$itemmodule]) {
1579 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1580 if (isset($element['userid'])) {
1581 $args['userid'] = $element['userid'];
1583 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1584 } else {
1585 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1590 * Returns URL of a page that is supposed to contain detailed grade analysis
1592 * At the moment, only activity modules are supported. The method generates link
1593 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1594 * gradeid and userid. If the grade.php does not exist, null is returned.
1596 * @return moodle_url|null URL or null if unable to construct it
1598 public function get_grade_analysis_url(grade_grade $grade) {
1599 global $CFG;
1600 /** @var array static cache of the grade.php file existence flags */
1601 static $hasgradephp = array();
1603 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1604 throw new coding_exception('Passed grade without the associated grade item');
1606 $item = $grade->grade_item;
1608 if (!$item->is_external_item()) {
1609 // at the moment, only activity modules are supported
1610 return null;
1612 if ($item->itemtype !== 'mod') {
1613 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1615 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1616 return null;
1619 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1620 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1621 $hasgradephp[$item->itemmodule] = true;
1622 } else {
1623 $hasgradephp[$item->itemmodule] = false;
1627 if (!$hasgradephp[$item->itemmodule]) {
1628 return null;
1631 $instances = $this->modinfo->get_instances();
1632 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1633 return null;
1635 $cm = $instances[$item->itemmodule][$item->iteminstance];
1636 if (!$cm->uservisible) {
1637 return null;
1640 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1641 'id' => $cm->id,
1642 'itemid' => $item->id,
1643 'itemnumber' => $item->itemnumber,
1644 'gradeid' => $grade->id,
1645 'userid' => $grade->userid,
1648 return $url;
1652 * Returns an action icon leading to the grade analysis page
1654 * @param grade_grade $grade
1655 * @return string
1657 public function get_grade_analysis_icon(grade_grade $grade) {
1658 global $OUTPUT;
1660 $url = $this->get_grade_analysis_url($grade);
1661 if (is_null($url)) {
1662 return '';
1665 $title = get_string('gradeanalysis', 'core_grades');
1666 return $OUTPUT->action_icon($url, new pix_icon('t/preview', ''), null,
1667 ['title' => $title, 'aria-label' => $title]);
1671 * Returns the grade eid - the grade may not exist yet.
1673 * @param grade_grade $grade_grade A grade_grade object
1675 * @return string eid
1677 public function get_grade_eid($grade_grade) {
1678 if (empty($grade_grade->id)) {
1679 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1680 } else {
1681 return 'g'.$grade_grade->id;
1686 * Returns the grade_item eid
1687 * @param grade_item $grade_item A grade_item object
1688 * @return string eid
1690 public function get_item_eid($grade_item) {
1691 return 'ig'.$grade_item->id;
1695 * Given a grade_tree element, returns an array of parameters
1696 * used to build an icon for that element.
1698 * @param array $element An array representing an element in the grade_tree
1700 * @return array
1702 public function get_params_for_iconstr($element) {
1703 $strparams = new stdClass();
1704 $strparams->category = '';
1705 $strparams->itemname = '';
1706 $strparams->itemmodule = '';
1708 if (!method_exists($element['object'], 'get_name')) {
1709 return $strparams;
1712 $strparams->itemname = html_to_text($element['object']->get_name());
1714 // If element name is categorytotal, get the name of the parent category
1715 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1716 $parent = $element['object']->get_parent_category();
1717 $strparams->category = $parent->get_name() . ' ';
1718 } else {
1719 $strparams->category = '';
1722 $strparams->itemmodule = null;
1723 if (isset($element['object']->itemmodule)) {
1724 $strparams->itemmodule = $element['object']->itemmodule;
1726 return $strparams;
1730 * Return a reset icon for the given element.
1732 * @param array $element An array representing an element in the grade_tree
1733 * @param object $gpr A grade_plugin_return object
1734 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1735 * @return string|action_menu_link
1737 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1738 global $CFG, $OUTPUT;
1740 // Limit to category items set to use the natural weights aggregation method, and users
1741 // with the capability to manage grades.
1742 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1743 !has_capability('moodle/grade:manage', $this->context)) {
1744 return $returnactionmenulink ? null : '';
1747 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1748 $url = new moodle_url('/grade/edit/tree/action.php', array(
1749 'id' => $this->courseid,
1750 'action' => 'resetweights',
1751 'eid' => $element['eid'],
1752 'sesskey' => sesskey(),
1755 if ($returnactionmenulink) {
1756 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1757 get_string('resetweightsshort', 'grades'));
1758 } else {
1759 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1764 * Return edit icon for give element
1766 * @param array $element An array representing an element in the grade_tree
1767 * @param object $gpr A grade_plugin_return object
1768 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1769 * @return string|action_menu_link
1771 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1772 global $CFG, $OUTPUT;
1774 if (!has_capability('moodle/grade:manage', $this->context)) {
1775 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1776 // oki - let them override grade
1777 } else {
1778 return $returnactionmenulink ? null : '';
1782 static $strfeedback = null;
1783 static $streditgrade = null;
1784 if (is_null($streditgrade)) {
1785 $streditgrade = get_string('editgrade', 'grades');
1786 $strfeedback = get_string('feedback');
1789 $strparams = $this->get_params_for_iconstr($element);
1791 $object = $element['object'];
1793 switch ($element['type']) {
1794 case 'item':
1795 case 'categoryitem':
1796 case 'courseitem':
1797 $stredit = get_string('editverbose', 'grades', $strparams);
1798 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1799 $url = new moodle_url('/grade/edit/tree/item.php',
1800 array('courseid' => $this->courseid, 'id' => $object->id));
1801 } else {
1802 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1803 array('courseid' => $this->courseid, 'id' => $object->id));
1805 break;
1807 case 'category':
1808 $stredit = get_string('editverbose', 'grades', $strparams);
1809 $url = new moodle_url('/grade/edit/tree/category.php',
1810 array('courseid' => $this->courseid, 'id' => $object->id));
1811 break;
1813 case 'grade':
1814 $stredit = $streditgrade;
1815 if (empty($object->id)) {
1816 $url = new moodle_url('/grade/edit/tree/grade.php',
1817 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1818 } else {
1819 $url = new moodle_url('/grade/edit/tree/grade.php',
1820 array('courseid' => $this->courseid, 'id' => $object->id));
1822 if (!empty($object->feedback)) {
1823 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1825 break;
1827 default:
1828 $url = null;
1831 if ($url) {
1832 if ($returnactionmenulink) {
1833 return new action_menu_link_secondary($gpr->add_url_params($url),
1834 new pix_icon('t/edit', $stredit),
1835 get_string('editsettings'));
1836 } else {
1837 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1840 } else {
1841 return $returnactionmenulink ? null : '';
1846 * Return hiding icon for give element
1848 * @param array $element An array representing an element in the grade_tree
1849 * @param object $gpr A grade_plugin_return object
1850 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1851 * @return string|action_menu_link
1853 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1854 global $CFG, $OUTPUT;
1856 if (!$element['object']->can_control_visibility()) {
1857 return $returnactionmenulink ? null : '';
1860 if (!has_capability('moodle/grade:manage', $this->context) and
1861 !has_capability('moodle/grade:hide', $this->context)) {
1862 return $returnactionmenulink ? null : '';
1865 $strparams = $this->get_params_for_iconstr($element);
1866 $strshow = get_string('showverbose', 'grades', $strparams);
1867 $strhide = get_string('hideverbose', 'grades', $strparams);
1869 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1870 $url = $gpr->add_url_params($url);
1872 if ($element['object']->is_hidden()) {
1873 $type = 'show';
1874 $tooltip = $strshow;
1876 // Change the icon and add a tooltip showing the date
1877 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1878 $type = 'hiddenuntil';
1879 $tooltip = get_string('hiddenuntildate', 'grades',
1880 userdate($element['object']->get_hidden()));
1883 $url->param('action', 'show');
1885 if ($returnactionmenulink) {
1886 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1887 } else {
1888 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1891 } else {
1892 $url->param('action', 'hide');
1893 if ($returnactionmenulink) {
1894 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1895 } else {
1896 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1900 return $hideicon;
1904 * Return locking icon for given element
1906 * @param array $element An array representing an element in the grade_tree
1907 * @param object $gpr A grade_plugin_return object
1909 * @return string
1911 public function get_locking_icon($element, $gpr) {
1912 global $CFG, $OUTPUT;
1914 $strparams = $this->get_params_for_iconstr($element);
1915 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1916 $strlock = get_string('lockverbose', 'grades', $strparams);
1918 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1919 $url = $gpr->add_url_params($url);
1921 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1922 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1923 $strparamobj = new stdClass();
1924 $strparamobj->itemname = $element['object']->grade_item->itemname;
1925 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1927 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1928 array('class' => 'action-icon'));
1930 } else if ($element['object']->is_locked()) {
1931 $type = 'unlock';
1932 $tooltip = $strunlock;
1934 // Change the icon and add a tooltip showing the date
1935 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1936 $type = 'locktime';
1937 $tooltip = get_string('locktimedate', 'grades',
1938 userdate($element['object']->get_locktime()));
1941 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1942 $action = '';
1943 } else {
1944 $url->param('action', 'unlock');
1945 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1948 } else {
1949 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1950 $action = '';
1951 } else {
1952 $url->param('action', 'lock');
1953 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1957 return $action;
1961 * Return calculation icon for given element
1963 * @param array $element An array representing an element in the grade_tree
1964 * @param object $gpr A grade_plugin_return object
1965 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1966 * @return string|action_menu_link
1968 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1969 global $CFG, $OUTPUT;
1970 if (!has_capability('moodle/grade:manage', $this->context)) {
1971 return $returnactionmenulink ? null : '';
1974 $type = $element['type'];
1975 $object = $element['object'];
1977 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1978 $strparams = $this->get_params_for_iconstr($element);
1979 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1981 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1982 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1984 // show calculation icon only when calculation possible
1985 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1986 if ($object->is_calculated()) {
1987 $icon = 't/calc';
1988 } else {
1989 $icon = 't/calc_off';
1992 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1993 $url = $gpr->add_url_params($url);
1994 if ($returnactionmenulink) {
1995 return new action_menu_link_secondary($url,
1996 new pix_icon($icon, $streditcalculation),
1997 get_string('editcalculation', 'grades'));
1998 } else {
1999 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2004 return $returnactionmenulink ? null : '';
2009 * Flat structure similar to grade tree.
2011 * @uses grade_structure
2012 * @package core_grades
2013 * @copyright 2009 Nicolas Connault
2014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2016 class grade_seq extends grade_structure {
2019 * 1D array of elements
2021 public $elements;
2024 * Constructor, retrieves and stores array of all grade_category and grade_item
2025 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2027 * @param int $courseid The course id
2028 * @param bool $category_grade_last category grade item is the last child
2029 * @param bool $nooutcomes Whether or not outcomes should be included
2031 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2032 global $USER, $CFG;
2034 $this->courseid = $courseid;
2035 $this->context = context_course::instance($courseid);
2037 // get course grade tree
2038 $top_element = grade_category::fetch_course_tree($courseid, true);
2040 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2042 foreach ($this->elements as $key=>$unused) {
2043 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2048 * Old syntax of class constructor. Deprecated in PHP7.
2050 * @deprecated since Moodle 3.1
2052 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2053 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2054 self::__construct($courseid, $category_grade_last, $nooutcomes);
2058 * Static recursive helper - makes the grade_item for category the last children
2060 * @param array &$element The seed of the recursion
2061 * @param bool $category_grade_last category grade item is the last child
2062 * @param bool $nooutcomes Whether or not outcomes should be included
2064 * @return array
2066 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2067 if (empty($element['children'])) {
2068 return array();
2070 $children = array();
2072 foreach ($element['children'] as $sortorder=>$unused) {
2073 if ($nooutcomes and $element['type'] != 'category' and
2074 $element['children'][$sortorder]['object']->is_outcome_item()) {
2075 continue;
2077 $children[] = $element['children'][$sortorder];
2079 unset($element['children']);
2081 if ($category_grade_last and count($children) > 1 and
2083 $children[0]['type'] === 'courseitem' or
2084 $children[0]['type'] === 'categoryitem'
2087 $cat_item = array_shift($children);
2088 array_push($children, $cat_item);
2091 $result = array();
2092 foreach ($children as $child) {
2093 if ($child['type'] == 'category') {
2094 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2095 } else {
2096 $child['eid'] = 'i'.$child['object']->id;
2097 $result[$child['object']->id] = $child;
2101 return $result;
2105 * Parses the array in search of a given eid and returns a element object with
2106 * information about the element it has found.
2108 * @param int $eid Gradetree Element ID
2110 * @return object element
2112 public function locate_element($eid) {
2113 // it is a grade - construct a new object
2114 if (strpos($eid, 'n') === 0) {
2115 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2116 return null;
2119 $itemid = $matches[1];
2120 $userid = $matches[2];
2122 //extra security check - the grade item must be in this tree
2123 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2124 return null;
2127 // $gradea->id may be null - means does not exist yet
2128 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2130 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2131 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2133 } else if (strpos($eid, 'g') === 0) {
2134 $id = (int) substr($eid, 1);
2135 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2136 return null;
2138 //extra security check - the grade item must be in this tree
2139 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2140 return null;
2142 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2143 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2146 // it is a category or item
2147 foreach ($this->elements as $element) {
2148 if ($element['eid'] == $eid) {
2149 return $element;
2153 return null;
2158 * This class represents a complete tree of categories, grade_items and final grades,
2159 * organises as an array primarily, but which can also be converted to other formats.
2160 * It has simple method calls with complex implementations, allowing for easy insertion,
2161 * deletion and moving of items and categories within the tree.
2163 * @uses grade_structure
2164 * @package core_grades
2165 * @copyright 2009 Nicolas Connault
2166 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2168 class grade_tree extends grade_structure {
2171 * The basic representation of the tree as a hierarchical, 3-tiered array.
2172 * @var object $top_element
2174 public $top_element;
2177 * 2D array of grade items and categories
2178 * @var array $levels
2180 public $levels;
2183 * Grade items
2184 * @var array $items
2186 public $items;
2189 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2190 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2192 * @param int $courseid The Course ID
2193 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2194 * @param bool $category_grade_last category grade item is the last child
2195 * @param array $collapsed array of collapsed categories
2196 * @param bool $nooutcomes Whether or not outcomes should be included
2198 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2199 $collapsed=null, $nooutcomes=false) {
2200 global $USER, $CFG, $COURSE, $DB;
2202 $this->courseid = $courseid;
2203 $this->levels = array();
2204 $this->context = context_course::instance($courseid);
2206 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2207 $course = $COURSE;
2208 } else {
2209 $course = $DB->get_record('course', array('id' => $this->courseid));
2211 $this->modinfo = get_fast_modinfo($course);
2213 // get course grade tree
2214 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2216 // collapse the categories if requested
2217 if (!empty($collapsed)) {
2218 grade_tree::category_collapse($this->top_element, $collapsed);
2221 // no otucomes if requested
2222 if (!empty($nooutcomes)) {
2223 grade_tree::no_outcomes($this->top_element);
2226 // move category item to last position in category
2227 if ($category_grade_last) {
2228 grade_tree::category_grade_last($this->top_element);
2231 if ($fillers) {
2232 // inject fake categories == fillers
2233 grade_tree::inject_fillers($this->top_element, 0);
2234 // add colspans to categories and fillers
2235 grade_tree::inject_colspans($this->top_element);
2238 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2243 * Old syntax of class constructor. Deprecated in PHP7.
2245 * @deprecated since Moodle 3.1
2247 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2248 $collapsed=null, $nooutcomes=false) {
2249 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2250 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2254 * Static recursive helper - removes items from collapsed categories
2256 * @param array &$element The seed of the recursion
2257 * @param array $collapsed array of collapsed categories
2259 * @return void
2261 public function category_collapse(&$element, $collapsed) {
2262 if ($element['type'] != 'category') {
2263 return;
2265 if (empty($element['children']) or count($element['children']) < 2) {
2266 return;
2269 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2270 $category_item = reset($element['children']); //keep only category item
2271 $element['children'] = array(key($element['children'])=>$category_item);
2273 } else {
2274 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2275 reset($element['children']);
2276 $first_key = key($element['children']);
2277 unset($element['children'][$first_key]);
2279 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2280 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2286 * Static recursive helper - removes all outcomes
2288 * @param array &$element The seed of the recursion
2290 * @return void
2292 public function no_outcomes(&$element) {
2293 if ($element['type'] != 'category') {
2294 return;
2296 foreach ($element['children'] as $sortorder=>$child) {
2297 if ($element['children'][$sortorder]['type'] == 'item'
2298 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2299 unset($element['children'][$sortorder]);
2301 } else if ($element['children'][$sortorder]['type'] == 'category') {
2302 grade_tree::no_outcomes($element['children'][$sortorder]);
2308 * Static recursive helper - makes the grade_item for category the last children
2310 * @param array &$element The seed of the recursion
2312 * @return void
2314 public function category_grade_last(&$element) {
2315 if (empty($element['children'])) {
2316 return;
2318 if (count($element['children']) < 2) {
2319 return;
2321 $first_item = reset($element['children']);
2322 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2323 // the category item might have been already removed
2324 $order = key($element['children']);
2325 unset($element['children'][$order]);
2326 $element['children'][$order] =& $first_item;
2328 foreach ($element['children'] as $sortorder => $child) {
2329 grade_tree::category_grade_last($element['children'][$sortorder]);
2334 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2336 * @param array &$levels The levels of the grade tree through which to recurse
2337 * @param array &$element The seed of the recursion
2338 * @param int $depth How deep are we?
2339 * @return void
2341 public function fill_levels(&$levels, &$element, $depth) {
2342 if (!array_key_exists($depth, $levels)) {
2343 $levels[$depth] = array();
2346 // prepare unique identifier
2347 if ($element['type'] == 'category') {
2348 $element['eid'] = 'cg'.$element['object']->id;
2349 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2350 $element['eid'] = 'ig'.$element['object']->id;
2351 $this->items[$element['object']->id] =& $element['object'];
2354 $levels[$depth][] =& $element;
2355 $depth++;
2356 if (empty($element['children'])) {
2357 return;
2359 $prev = 0;
2360 foreach ($element['children'] as $sortorder=>$child) {
2361 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2362 $element['children'][$sortorder]['prev'] = $prev;
2363 $element['children'][$sortorder]['next'] = 0;
2364 if ($prev) {
2365 $element['children'][$prev]['next'] = $sortorder;
2367 $prev = $sortorder;
2372 * Determines whether the grade tree item can be displayed.
2373 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2374 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2375 * can be output.
2377 * @param array $element The grade category element.
2378 * @return bool True if the grade tree item can be displayed. False, otherwise.
2380 public static function can_output_item($element) {
2381 $canoutput = true;
2383 if ($element['type'] === 'category') {
2384 $object = $element['object'];
2385 $category = grade_category::fetch(array('id' => $object->id));
2386 // Category has total, we can output this.
2387 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2388 return true;
2391 // Category has no total and has no children, no need to output this.
2392 if (empty($element['children'])) {
2393 return false;
2396 $canoutput = false;
2397 // Loop over children and make sure at least one child can be output.
2398 foreach ($element['children'] as $child) {
2399 $canoutput = self::can_output_item($child);
2400 if ($canoutput) {
2401 break;
2406 return $canoutput;
2410 * Static recursive helper - makes full tree (all leafes are at the same level)
2412 * @param array &$element The seed of the recursion
2413 * @param int $depth How deep are we?
2415 * @return int
2417 public function inject_fillers(&$element, $depth) {
2418 $depth++;
2420 if (empty($element['children'])) {
2421 return $depth;
2423 $chdepths = array();
2424 $chids = array_keys($element['children']);
2425 $last_child = end($chids);
2426 $first_child = reset($chids);
2428 foreach ($chids as $chid) {
2429 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2431 arsort($chdepths);
2433 $maxdepth = reset($chdepths);
2434 foreach ($chdepths as $chid=>$chd) {
2435 if ($chd == $maxdepth) {
2436 continue;
2438 if (!self::can_output_item($element['children'][$chid])) {
2439 continue;
2441 for ($i=0; $i < $maxdepth-$chd; $i++) {
2442 if ($chid == $first_child) {
2443 $type = 'fillerfirst';
2444 } else if ($chid == $last_child) {
2445 $type = 'fillerlast';
2446 } else {
2447 $type = 'filler';
2449 $oldchild =& $element['children'][$chid];
2450 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2451 'eid'=>'', 'depth'=>$element['object']->depth,
2452 'children'=>array($oldchild));
2456 return $maxdepth;
2460 * Static recursive helper - add colspan information into categories
2462 * @param array &$element The seed of the recursion
2464 * @return int
2466 public function inject_colspans(&$element) {
2467 if (empty($element['children'])) {
2468 return 1;
2470 $count = 0;
2471 foreach ($element['children'] as $key=>$child) {
2472 if (!self::can_output_item($child)) {
2473 continue;
2475 $count += grade_tree::inject_colspans($element['children'][$key]);
2477 $element['colspan'] = $count;
2478 return $count;
2482 * Parses the array in search of a given eid and returns a element object with
2483 * information about the element it has found.
2484 * @param int $eid Gradetree Element ID
2485 * @return object element
2487 public function locate_element($eid) {
2488 // it is a grade - construct a new object
2489 if (strpos($eid, 'n') === 0) {
2490 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2491 return null;
2494 $itemid = $matches[1];
2495 $userid = $matches[2];
2497 //extra security check - the grade item must be in this tree
2498 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2499 return null;
2502 // $gradea->id may be null - means does not exist yet
2503 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2505 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2506 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2508 } else if (strpos($eid, 'g') === 0) {
2509 $id = (int) substr($eid, 1);
2510 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2511 return null;
2513 //extra security check - the grade item must be in this tree
2514 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2515 return null;
2517 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2518 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2521 // it is a category or item
2522 foreach ($this->levels as $row) {
2523 foreach ($row as $element) {
2524 if ($element['type'] == 'filler') {
2525 continue;
2527 if ($element['eid'] == $eid) {
2528 return $element;
2533 return null;
2537 * Returns a well-formed XML representation of the grade-tree using recursion.
2539 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2540 * @param string $tabs The control character to use for tabs
2542 * @return string $xml
2544 public function exporttoxml($root=null, $tabs="\t") {
2545 $xml = null;
2546 $first = false;
2547 if (is_null($root)) {
2548 $root = $this->top_element;
2549 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2550 $xml .= "<gradetree>\n";
2551 $first = true;
2554 $type = 'undefined';
2555 if (strpos($root['object']->table, 'grade_categories') !== false) {
2556 $type = 'category';
2557 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2558 $type = 'item';
2559 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2560 $type = 'outcome';
2563 $xml .= "$tabs<element type=\"$type\">\n";
2564 foreach ($root['object'] as $var => $value) {
2565 if (!is_object($value) && !is_array($value) && !empty($value)) {
2566 $xml .= "$tabs\t<$var>$value</$var>\n";
2570 if (!empty($root['children'])) {
2571 $xml .= "$tabs\t<children>\n";
2572 foreach ($root['children'] as $sortorder => $child) {
2573 $xml .= $this->exportToXML($child, $tabs."\t\t");
2575 $xml .= "$tabs\t</children>\n";
2578 $xml .= "$tabs</element>\n";
2580 if ($first) {
2581 $xml .= "</gradetree>";
2584 return $xml;
2588 * Returns a JSON representation of the grade-tree using recursion.
2590 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2591 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2593 * @return string
2595 public function exporttojson($root=null, $tabs="\t") {
2596 $json = null;
2597 $first = false;
2598 if (is_null($root)) {
2599 $root = $this->top_element;
2600 $first = true;
2603 $name = '';
2606 if (strpos($root['object']->table, 'grade_categories') !== false) {
2607 $name = $root['object']->fullname;
2608 if ($name == '?') {
2609 $name = $root['object']->get_name();
2611 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2612 $name = $root['object']->itemname;
2613 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2614 $name = $root['object']->itemname;
2617 $json .= "$tabs {\n";
2618 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2619 $json .= "$tabs\t \"name\": \"$name\",\n";
2621 foreach ($root['object'] as $var => $value) {
2622 if (!is_object($value) && !is_array($value) && !empty($value)) {
2623 $json .= "$tabs\t \"$var\": \"$value\",\n";
2627 $json = substr($json, 0, strrpos($json, ','));
2629 if (!empty($root['children'])) {
2630 $json .= ",\n$tabs\t\"children\": [\n";
2631 foreach ($root['children'] as $sortorder => $child) {
2632 $json .= $this->exportToJSON($child, $tabs."\t\t");
2634 $json = substr($json, 0, strrpos($json, ','));
2635 $json .= "\n$tabs\t]\n";
2638 if ($first) {
2639 $json .= "\n}";
2640 } else {
2641 $json .= "\n$tabs},\n";
2644 return $json;
2648 * Returns the array of levels
2650 * @return array
2652 public function get_levels() {
2653 return $this->levels;
2657 * Returns the array of grade items
2659 * @return array
2661 public function get_items() {
2662 return $this->items;
2666 * Returns a specific Grade Item
2668 * @param int $itemid The ID of the grade_item object
2670 * @return grade_item
2672 public function get_item($itemid) {
2673 if (array_key_exists($itemid, $this->items)) {
2674 return $this->items[$itemid];
2675 } else {
2676 return false;
2682 * Local shortcut function for creating an edit/delete button for a grade_* object.
2683 * @param string $type 'edit' or 'delete'
2684 * @param int $courseid The Course ID
2685 * @param grade_* $object The grade_* object
2686 * @return string html
2688 function grade_button($type, $courseid, $object) {
2689 global $CFG, $OUTPUT;
2690 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2691 $objectidstring = $matches[1] . 'id';
2692 } else {
2693 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2696 $strdelete = get_string('delete');
2697 $stredit = get_string('edit');
2699 if ($type == 'delete') {
2700 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2701 } else if ($type == 'edit') {
2702 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2705 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2710 * This method adds settings to the settings block for the grade system and its
2711 * plugins
2713 * @global moodle_page $PAGE
2715 function grade_extend_settings($plugininfo, $courseid) {
2716 global $PAGE;
2718 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER,
2719 null, 'gradeadmin');
2721 $strings = array_shift($plugininfo);
2723 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2724 foreach ($reports as $report) {
2725 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2729 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2730 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2731 foreach ($settings as $setting) {
2732 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2736 if ($imports = grade_helper::get_plugins_import($courseid)) {
2737 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2738 foreach ($imports as $import) {
2739 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2743 if ($exports = grade_helper::get_plugins_export($courseid)) {
2744 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2745 foreach ($exports as $export) {
2746 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2750 if ($letters = grade_helper::get_info_letters($courseid)) {
2751 $letters = array_shift($letters);
2752 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2755 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2756 $outcomes = array_shift($outcomes);
2757 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2760 if ($scales = grade_helper::get_info_scales($courseid)) {
2761 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2764 if ($gradenode->contains_active_node()) {
2765 // If the gradenode is active include the settings base node (gradeadministration) in
2766 // the navbar, typcially this is ignored.
2767 $PAGE->navbar->includesettingsbase = true;
2769 // If we can get the course admin node make sure it is closed by default
2770 // as in this case the gradenode will be opened
2771 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2772 $coursenode->make_inactive();
2773 $coursenode->forceopen = false;
2779 * Grade helper class
2781 * This class provides several helpful functions that work irrespective of any
2782 * current state.
2784 * @copyright 2010 Sam Hemelryk
2785 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2787 abstract class grade_helper {
2789 * Cached manage settings info {@see get_info_settings}
2790 * @var grade_plugin_info|false
2792 protected static $managesetting = null;
2794 * Cached grade report plugins {@see get_plugins_reports}
2795 * @var array|false
2797 protected static $gradereports = null;
2799 * Cached grade report plugins preferences {@see get_info_scales}
2800 * @var array|false
2802 protected static $gradereportpreferences = null;
2804 * Cached scale info {@see get_info_scales}
2805 * @var grade_plugin_info|false
2807 protected static $scaleinfo = null;
2809 * Cached outcome info {@see get_info_outcomes}
2810 * @var grade_plugin_info|false
2812 protected static $outcomeinfo = null;
2814 * Cached leftter info {@see get_info_letters}
2815 * @var grade_plugin_info|false
2817 protected static $letterinfo = null;
2819 * Cached grade import plugins {@see get_plugins_import}
2820 * @var array|false
2822 protected static $importplugins = null;
2824 * Cached grade export plugins {@see get_plugins_export}
2825 * @var array|false
2827 protected static $exportplugins = null;
2829 * Cached grade plugin strings
2830 * @var array
2832 protected static $pluginstrings = null;
2834 * Cached grade aggregation strings
2835 * @var array
2837 protected static $aggregationstrings = null;
2840 * Gets strings commonly used by the describe plugins
2842 * report => get_string('view'),
2843 * scale => get_string('scales'),
2844 * outcome => get_string('outcomes', 'grades'),
2845 * letter => get_string('letters', 'grades'),
2846 * export => get_string('export', 'grades'),
2847 * import => get_string('import'),
2848 * settings => get_string('settings')
2850 * @return array
2852 public static function get_plugin_strings() {
2853 if (self::$pluginstrings === null) {
2854 self::$pluginstrings = array(
2855 'report' => get_string('view'),
2856 'scale' => get_string('scales'),
2857 'outcome' => get_string('outcomes', 'grades'),
2858 'letter' => get_string('letters', 'grades'),
2859 'export' => get_string('export', 'grades'),
2860 'import' => get_string('import'),
2861 'settings' => get_string('edittree', 'grades')
2864 return self::$pluginstrings;
2868 * Gets strings describing the available aggregation methods.
2870 * @return array
2872 public static function get_aggregation_strings() {
2873 if (self::$aggregationstrings === null) {
2874 self::$aggregationstrings = array(
2875 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2876 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2877 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2878 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2879 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2880 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2881 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2882 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2883 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2886 return self::$aggregationstrings;
2890 * Get grade_plugin_info object for managing settings if the user can
2892 * @param int $courseid
2893 * @return grade_plugin_info[]
2895 public static function get_info_manage_settings($courseid) {
2896 if (self::$managesetting !== null) {
2897 return self::$managesetting;
2899 $context = context_course::instance($courseid);
2900 self::$managesetting = array();
2901 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2902 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
2903 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2904 get_string('gradebooksetup', 'grades'));
2905 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2906 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2907 get_string('coursegradesettings', 'grades'));
2909 if (self::$gradereportpreferences === null) {
2910 self::get_plugins_reports($courseid);
2912 if (self::$gradereportpreferences) {
2913 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
2915 return self::$managesetting;
2918 * Returns an array of plugin reports as grade_plugin_info objects
2920 * @param int $courseid
2921 * @return array
2923 public static function get_plugins_reports($courseid) {
2924 global $SITE;
2926 if (self::$gradereports !== null) {
2927 return self::$gradereports;
2929 $context = context_course::instance($courseid);
2930 $gradereports = array();
2931 $gradepreferences = array();
2932 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2933 //some reports make no sense if we're not within a course
2934 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2935 continue;
2938 // Remove ones we can't see
2939 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2940 continue;
2943 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
2944 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
2945 'moodle/grade:edit'), $context)) {
2946 continue;
2949 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2950 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2951 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2953 // Add link to preferences tab if such a page exists
2954 if (file_exists($plugindir.'/preferences.php')) {
2955 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2956 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2957 get_string('preferences', 'grades') . ': ' . $pluginstr);
2960 if (count($gradereports) == 0) {
2961 $gradereports = false;
2962 $gradepreferences = false;
2963 } else if (count($gradepreferences) == 0) {
2964 $gradepreferences = false;
2965 asort($gradereports);
2966 } else {
2967 asort($gradereports);
2968 asort($gradepreferences);
2970 self::$gradereports = $gradereports;
2971 self::$gradereportpreferences = $gradepreferences;
2972 return self::$gradereports;
2976 * Get information on scales
2977 * @param int $courseid
2978 * @return grade_plugin_info
2980 public static function get_info_scales($courseid) {
2981 if (self::$scaleinfo !== null) {
2982 return self::$scaleinfo;
2984 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2985 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2986 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2987 } else {
2988 self::$scaleinfo = false;
2990 return self::$scaleinfo;
2993 * Get information on outcomes
2994 * @param int $courseid
2995 * @return grade_plugin_info
2997 public static function get_info_outcomes($courseid) {
2998 global $CFG, $SITE;
3000 if (self::$outcomeinfo !== null) {
3001 return self::$outcomeinfo;
3003 $context = context_course::instance($courseid);
3004 $canmanage = has_capability('moodle/grade:manage', $context);
3005 $canupdate = has_capability('moodle/course:update', $context);
3006 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3007 $outcomes = array();
3008 if ($canupdate) {
3009 if ($courseid!=$SITE->id) {
3010 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3011 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3013 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3014 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3015 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3016 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3017 } else {
3018 if ($courseid!=$SITE->id) {
3019 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3020 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3023 self::$outcomeinfo = $outcomes;
3024 } else {
3025 self::$outcomeinfo = false;
3027 return self::$outcomeinfo;
3030 * Get information on letters
3031 * @param int $courseid
3032 * @return array
3034 public static function get_info_letters($courseid) {
3035 global $SITE;
3036 if (self::$letterinfo !== null) {
3037 return self::$letterinfo;
3039 $context = context_course::instance($courseid);
3040 $canmanage = has_capability('moodle/grade:manage', $context);
3041 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3042 if ($canmanage || $canmanageletters) {
3043 // Redirect to system context when report is accessed from admin settings MDL-31633
3044 if ($context->instanceid == $SITE->id) {
3045 $param = array('edit' => 1);
3046 } else {
3047 $param = array('edit' => 1,'id' => $context->id);
3049 self::$letterinfo = array(
3050 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3051 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3053 } else {
3054 self::$letterinfo = false;
3056 return self::$letterinfo;
3059 * Get information import plugins
3060 * @param int $courseid
3061 * @return array
3063 public static function get_plugins_import($courseid) {
3064 global $CFG;
3066 if (self::$importplugins !== null) {
3067 return self::$importplugins;
3069 $importplugins = array();
3070 $context = context_course::instance($courseid);
3072 if (has_capability('moodle/grade:import', $context)) {
3073 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3074 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3075 continue;
3077 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3078 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3079 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3082 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3083 // XML is the only grade import plugin that has publishing feature.
3084 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3085 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3086 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3090 if (count($importplugins) > 0) {
3091 asort($importplugins);
3092 self::$importplugins = $importplugins;
3093 } else {
3094 self::$importplugins = false;
3096 return self::$importplugins;
3099 * Get information export plugins
3100 * @param int $courseid
3101 * @return array
3103 public static function get_plugins_export($courseid) {
3104 global $CFG;
3106 if (self::$exportplugins !== null) {
3107 return self::$exportplugins;
3109 $context = context_course::instance($courseid);
3110 $exportplugins = array();
3111 $canpublishgrades = 0;
3112 if (has_capability('moodle/grade:export', $context)) {
3113 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3114 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3115 continue;
3117 // All the grade export plugins has grade publishing capabilities.
3118 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3119 $canpublishgrades++;
3122 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3123 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3124 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3127 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3128 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3129 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3130 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3133 if (count($exportplugins) > 0) {
3134 asort($exportplugins);
3135 self::$exportplugins = $exportplugins;
3136 } else {
3137 self::$exportplugins = false;
3139 return self::$exportplugins;
3143 * Returns the value of a field from a user record
3145 * @param stdClass $user object
3146 * @param stdClass $field object
3147 * @return string value of the field
3149 public static function get_user_field_value($user, $field) {
3150 if (!empty($field->customid)) {
3151 $fieldname = 'customfield_' . $field->customid;
3152 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3153 $fieldvalue = $user->{$fieldname};
3154 } else {
3155 $fieldvalue = $field->default;
3157 } else {
3158 $fieldvalue = $user->{$field->shortname};
3160 return $fieldvalue;
3164 * Returns an array of user profile fields to be included in export
3166 * @param int $courseid
3167 * @param bool $includecustomfields
3168 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3170 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3171 global $CFG, $DB;
3173 // Gets the fields that have to be hidden
3174 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3175 $context = context_course::instance($courseid);
3176 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3177 if ($canseehiddenfields) {
3178 $hiddenfields = array();
3181 $fields = array();
3182 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3183 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3184 $userdefaultfields = user_get_default_fields();
3186 // Sets the list of profile fields
3187 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3188 if (!empty($userprofilefields)) {
3189 foreach ($userprofilefields as $field) {
3190 $field = trim($field);
3191 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3192 continue;
3194 $obj = new stdClass();
3195 $obj->customid = 0;
3196 $obj->shortname = $field;
3197 $obj->fullname = get_string($field);
3198 $fields[] = $obj;
3202 // Sets the list of custom profile fields
3203 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3204 if ($includecustomfields && !empty($customprofilefields)) {
3205 $customfields = profile_get_user_fields_with_data(0);
3207 foreach ($customfields as $fieldobj) {
3208 $field = (object)$fieldobj->get_field_config_for_external();
3209 // Make sure we can display this custom field
3210 if (!in_array($field->shortname, $customprofilefields)) {
3211 continue;
3212 } else if (in_array($field->shortname, $hiddenfields)) {
3213 continue;
3214 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3215 continue;
3218 $obj = new stdClass();
3219 $obj->customid = $field->id;
3220 $obj->shortname = $field->shortname;
3221 $obj->fullname = format_string($field->name);
3222 $obj->datatype = $field->datatype;
3223 $obj->default = $field->defaultdata;
3224 $fields[] = $obj;
3228 return $fields;
3232 * This helper method gets a snapshot of all the weights for a course.
3233 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3234 * @param int $courseid
3235 * @return array of itemid -> aggregationcoef2
3237 public static function fetch_all_natural_weights_for_course($courseid) {
3238 global $DB;
3239 $result = array();
3241 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3242 foreach ($records as $record) {
3243 $result[$record->id] = $record->aggregationcoef2;
3245 return $result;
3249 * Resets all static caches.
3251 * @return void
3253 public static function reset_caches() {
3254 self::$managesetting = null;
3255 self::$gradereports = null;
3256 self::$gradereportpreferences = null;
3257 self::$scaleinfo = null;
3258 self::$outcomeinfo = null;
3259 self::$letterinfo = null;
3260 self::$importplugins = null;
3261 self::$exportplugins = null;
3262 self::$pluginstrings = null;
3263 self::$aggregationstrings = null;