MDL-53758 search: Better results with low hit rates, improve performance
[moodle.git] / grade / lib.php
blob66cf003698bcde20c16e6f02fdb181a7924da96c
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir . '/gradelib.php');
26 require_once($CFG->dirroot . '/grade/export/lib.php');
28 /**
29 * This class iterates over all users that are graded in a course.
30 * Returns detailed info about users and their grades.
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class graded_users_iterator {
37 /**
38 * The couse whose users we are interested in
40 protected $course;
42 /**
43 * An array of grade items or null if only user data was requested
45 protected $grade_items;
47 /**
48 * The group ID we are interested in. 0 means all groups.
50 protected $groupid;
52 /**
53 * A recordset of graded users
55 protected $users_rs;
57 /**
58 * A recordset of user grades (grade_grade instances)
60 protected $grades_rs;
62 /**
63 * Array used when moving to next user while iterating through the grades recordset
65 protected $gradestack;
67 /**
68 * The first field of the users table by which the array of users will be sorted
70 protected $sortfield1;
72 /**
73 * Should sortfield1 be ASC or DESC
75 protected $sortorder1;
77 /**
78 * The second field of the users table by which the array of users will be sorted
80 protected $sortfield2;
82 /**
83 * Should sortfield2 be ASC or DESC
85 protected $sortorder2;
87 /**
88 * Should users whose enrolment has been suspended be ignored?
90 protected $onlyactive = false;
92 /**
93 * Enable user custom fields
95 protected $allowusercustomfields = false;
97 /**
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
101 protected $suspendedusers = array();
104 * Constructor
106 * @param object $course A course object
107 * @param array $grade_items array of grade items, if not specified only user info returned
108 * @param int $groupid iterate only group users if present
109 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
110 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
111 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
112 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
114 public function __construct($course, $grade_items=null, $groupid=0,
115 $sortfield1='lastname', $sortorder1='ASC',
116 $sortfield2='firstname', $sortorder2='ASC') {
117 $this->course = $course;
118 $this->grade_items = $grade_items;
119 $this->groupid = $groupid;
120 $this->sortfield1 = $sortfield1;
121 $this->sortorder1 = $sortorder1;
122 $this->sortfield2 = $sortfield2;
123 $this->sortorder2 = $sortorder2;
125 $this->gradestack = array();
129 * Initialise the iterator
131 * @return boolean success
133 public function init() {
134 global $CFG, $DB;
136 $this->close();
138 export_verify_grades($this->course->id);
139 $course_item = grade_item::fetch_course_item($this->course->id);
140 if ($course_item->needsupdate) {
141 // Can not calculate all final grades - sorry.
142 return false;
145 $coursecontext = context_course::instance($this->course->id);
147 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
148 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
149 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
151 $params = array_merge($params, $enrolledparams, $relatedctxparams);
153 if ($this->groupid) {
154 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
155 $groupwheresql = "AND gm.groupid = :groupid";
156 // $params contents: gradebookroles
157 $params['groupid'] = $this->groupid;
158 } else {
159 $groupsql = "";
160 $groupwheresql = "";
163 if (empty($this->sortfield1)) {
164 // We must do some sorting even if not specified.
165 $ofields = ", u.id AS usrt";
166 $order = "usrt ASC";
168 } else {
169 $ofields = ", u.$this->sortfield1 AS usrt1";
170 $order = "usrt1 $this->sortorder1";
171 if (!empty($this->sortfield2)) {
172 $ofields .= ", u.$this->sortfield2 AS usrt2";
173 $order .= ", usrt2 $this->sortorder2";
175 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
176 // User order MUST be the same in both queries,
177 // must include the only unique user->id if not already present.
178 $ofields .= ", u.id AS usrt";
179 $order .= ", usrt ASC";
183 $userfields = 'u.*';
184 $customfieldssql = '';
185 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
186 $customfieldscount = 0;
187 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
188 foreach ($customfieldsarray as $field) {
189 if (!empty($field->customid)) {
190 $customfieldssql .= "
191 LEFT JOIN (SELECT * FROM {user_info_data}
192 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
193 ON u.id = cf$customfieldscount.userid";
194 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->shortname}";
195 $params['cf'.$customfieldscount] = $field->customid;
196 $customfieldscount++;
201 $users_sql = "SELECT $userfields $ofields
202 FROM {user} u
203 JOIN ($enrolledsql) je ON je.id = u.id
204 $groupsql $customfieldssql
205 JOIN (
206 SELECT DISTINCT ra.userid
207 FROM {role_assignments} ra
208 WHERE ra.roleid $gradebookroles_sql
209 AND ra.contextid $relatedctxsql
210 ) rainner ON rainner.userid = u.id
211 WHERE u.deleted = 0
212 $groupwheresql
213 ORDER BY $order";
214 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
216 if (!$this->onlyactive) {
217 $context = context_course::instance($this->course->id);
218 $this->suspendedusers = get_suspended_userids($context);
219 } else {
220 $this->suspendedusers = array();
223 if (!empty($this->grade_items)) {
224 $itemids = array_keys($this->grade_items);
225 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
226 $params = array_merge($params, $grades_params);
228 $grades_sql = "SELECT g.* $ofields
229 FROM {grade_grades} g
230 JOIN {user} u ON g.userid = u.id
231 JOIN ($enrolledsql) je ON je.id = u.id
232 $groupsql
233 JOIN (
234 SELECT DISTINCT ra.userid
235 FROM {role_assignments} ra
236 WHERE ra.roleid $gradebookroles_sql
237 AND ra.contextid $relatedctxsql
238 ) rainner ON rainner.userid = u.id
239 WHERE u.deleted = 0
240 AND g.itemid $itemidsql
241 $groupwheresql
242 ORDER BY $order, g.itemid ASC";
243 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
244 } else {
245 $this->grades_rs = false;
248 return true;
252 * Returns information about the next user
253 * @return mixed array of user info, all grades and feedback or null when no more users found
255 public function next_user() {
256 if (!$this->users_rs) {
257 return false; // no users present
260 if (!$this->users_rs->valid()) {
261 if ($current = $this->_pop()) {
262 // this is not good - user or grades updated between the two reads above :-(
265 return false; // no more users
266 } else {
267 $user = $this->users_rs->current();
268 $this->users_rs->next();
271 // find grades of this user
272 $grade_records = array();
273 while (true) {
274 if (!$current = $this->_pop()) {
275 break; // no more grades
278 if (empty($current->userid)) {
279 break;
282 if ($current->userid != $user->id) {
283 // grade of the next user, we have all for this user
284 $this->_push($current);
285 break;
288 $grade_records[$current->itemid] = $current;
291 $grades = array();
292 $feedbacks = array();
294 if (!empty($this->grade_items)) {
295 foreach ($this->grade_items as $grade_item) {
296 if (!isset($feedbacks[$grade_item->id])) {
297 $feedbacks[$grade_item->id] = new stdClass();
299 if (array_key_exists($grade_item->id, $grade_records)) {
300 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
301 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
302 unset($grade_records[$grade_item->id]->feedback);
303 unset($grade_records[$grade_item->id]->feedbackformat);
304 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
305 } else {
306 $feedbacks[$grade_item->id]->feedback = '';
307 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
308 $grades[$grade_item->id] =
309 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
311 $grades[$grade_item->id]->grade_item = $grade_item;
315 // Set user suspended status.
316 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
317 $result = new stdClass();
318 $result->user = $user;
319 $result->grades = $grades;
320 $result->feedbacks = $feedbacks;
321 return $result;
325 * Close the iterator, do not forget to call this function
327 public function close() {
328 if ($this->users_rs) {
329 $this->users_rs->close();
330 $this->users_rs = null;
332 if ($this->grades_rs) {
333 $this->grades_rs->close();
334 $this->grades_rs = null;
336 $this->gradestack = array();
340 * Should all enrolled users be exported or just those with an active enrolment?
342 * @param bool $onlyactive True to limit the export to users with an active enrolment
344 public function require_active_enrolment($onlyactive = true) {
345 if (!empty($this->users_rs)) {
346 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
348 $this->onlyactive = $onlyactive;
352 * Allow custom fields to be included
354 * @param bool $allow Whether to allow custom fields or not
355 * @return void
357 public function allow_user_custom_fields($allow = true) {
358 if ($allow) {
359 $this->allowusercustomfields = true;
360 } else {
361 $this->allowusercustomfields = false;
366 * Add a grade_grade instance to the grade stack
368 * @param grade_grade $grade Grade object
370 * @return void
372 private function _push($grade) {
373 array_push($this->gradestack, $grade);
378 * Remove a grade_grade instance from the grade stack
380 * @return grade_grade current grade object
382 private function _pop() {
383 global $DB;
384 if (empty($this->gradestack)) {
385 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
386 return null; // no grades present
389 $current = $this->grades_rs->current();
391 $this->grades_rs->next();
393 return $current;
394 } else {
395 return array_pop($this->gradestack);
401 * Print a selection popup form of the graded users in a course.
403 * @deprecated since 2.0
405 * @param int $course id of the course
406 * @param string $actionpage The page receiving the data from the popoup form
407 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
408 * @param int $groupid id of requested group, 0 means all
409 * @param int $includeall bool include all option
410 * @param bool $return If true, will return the HTML, otherwise, will print directly
411 * @return null
413 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
414 global $CFG, $USER, $OUTPUT;
415 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
418 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
419 global $USER, $CFG;
421 if (is_null($userid)) {
422 $userid = $USER->id;
424 $coursecontext = context_course::instance($course->id);
425 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
426 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
427 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
428 $menu = array(); // Will be a list of userid => user name
429 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
430 $gui = new graded_users_iterator($course, null, $groupid);
431 $gui->require_active_enrolment($showonlyactiveenrol);
432 $gui->init();
433 $label = get_string('selectauser', 'grades');
434 if ($includeall) {
435 $menu[0] = get_string('allusers', 'grades');
436 $label = get_string('selectalloroneuser', 'grades');
438 while ($userdata = $gui->next_user()) {
439 $user = $userdata->user;
440 $userfullname = fullname($user);
441 if ($user->suspendedenrolment) {
442 $menususpendedusers[$user->id] = $userfullname;
443 } else {
444 $menu[$user->id] = $userfullname;
447 $gui->close();
449 if ($includeall) {
450 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
453 if (!empty($menususpendedusers)) {
454 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
456 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
457 $select->label = $label;
458 $select->formid = 'choosegradeuser';
459 return $select;
463 * Hide warning about changed grades during upgrade to 2.8.
465 * @param int $courseid The current course id.
467 function hide_natural_aggregation_upgrade_notice($courseid) {
468 unset_config('show_sumofgrades_upgrade_' . $courseid);
472 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
474 * @param int $courseid The current course id.
476 function grade_hide_min_max_grade_upgrade_notice($courseid) {
477 unset_config('show_min_max_grades_changed_' . $courseid);
481 * Use the grade min and max from the grade_grade.
483 * This is reserved for core use after an upgrade.
485 * @param int $courseid The current course id.
487 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
488 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
490 grade_force_full_regrading($courseid);
491 // Do this now, because it probably happened to late in the page load to be happen automatically.
492 grade_regrade_final_grades($courseid);
496 * Use the grade min and max from the grade_item.
498 * This is reserved for core use after an upgrade.
500 * @param int $courseid The current course id.
502 function grade_upgrade_use_min_max_from_grade_item($courseid) {
503 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
505 grade_force_full_regrading($courseid);
506 // Do this now, because it probably happened to late in the page load to be happen automatically.
507 grade_regrade_final_grades($courseid);
511 * Hide warning about changed grades during upgrade to 2.8.
513 * @param int $courseid The current course id.
515 function hide_aggregatesubcats_upgrade_notice($courseid) {
516 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
520 * Hide warning about changed grades due to bug fixes
522 * @param int $courseid The current course id.
524 function hide_gradebook_calculations_freeze_notice($courseid) {
525 unset_config('gradebook_calculations_freeze_' . $courseid);
529 * Print warning about changed grades during upgrade to 2.8.
531 * @param int $courseid The current course id.
532 * @param context $context The course context.
533 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
534 * @param boolean $return return as string
536 * @return nothing or string if $return true
538 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
539 global $CFG, $OUTPUT;
540 $html = '';
542 // Do not do anything if they cannot manage the grades of this course.
543 if (!has_capability('moodle/grade:manage', $context)) {
544 return $html;
547 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
548 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
549 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
550 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
552 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
553 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
555 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
556 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
558 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
560 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
561 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
563 // Hide the warning if the user told it to go away.
564 if ($hidenaturalwarning) {
565 hide_natural_aggregation_upgrade_notice($courseid);
567 // Hide the warning if the user told it to go away.
568 if ($hidesubcatswarning) {
569 hide_aggregatesubcats_upgrade_notice($courseid);
572 // Hide the min/max warning if the user told it to go away.
573 if ($hideminmaxwarning) {
574 grade_hide_min_max_grade_upgrade_notice($courseid);
575 $showminmaxwarning = false;
578 if ($useminmaxfromgradegrade) {
579 // Revert to the new behaviour, we now use the grade_grade for min/max.
580 grade_upgrade_use_min_max_from_grade_grade($courseid);
581 grade_hide_min_max_grade_upgrade_notice($courseid);
582 $showminmaxwarning = false;
584 } else if ($useminmaxfromgradeitem) {
585 // Apply the new logic, we now use the grade_item for min/max.
586 grade_upgrade_use_min_max_from_grade_item($courseid);
587 grade_hide_min_max_grade_upgrade_notice($courseid);
588 $showminmaxwarning = false;
592 if (!$hidenaturalwarning && $shownaturalwarning) {
593 $message = get_string('sumofgradesupgradedgrades', 'grades');
594 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
595 $urlparams = array( 'id' => $courseid,
596 'seensumofgradesupgradedgrades' => true,
597 'sesskey' => sesskey());
598 $goawayurl = new moodle_url($thispage, $urlparams);
599 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
600 $html .= $OUTPUT->notification($message, 'notifysuccess');
601 $html .= $goawaybutton;
604 if (!$hidesubcatswarning && $showsubcatswarning) {
605 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
606 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
607 $urlparams = array( 'id' => $courseid,
608 'seenaggregatesubcatsupgradedgrades' => true,
609 'sesskey' => sesskey());
610 $goawayurl = new moodle_url($thispage, $urlparams);
611 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
612 $html .= $OUTPUT->notification($message, 'notifysuccess');
613 $html .= $goawaybutton;
616 if ($showminmaxwarning) {
617 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
618 $urlparams = array( 'id' => $courseid,
619 'seenminmaxupgradedgrades' => true,
620 'sesskey' => sesskey());
622 $goawayurl = new moodle_url($thispage, $urlparams);
623 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
624 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
625 array('target' => '_blank'));
627 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
628 // Show the message that there were min/max issues that have been resolved.
629 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
631 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
632 $urlparams = array('id' => $courseid,
633 'useminmaxfromgradegrade' => true,
634 'sesskey' => sesskey());
635 $reverturl = new moodle_url($thispage, $urlparams);
636 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
638 $html .= $OUTPUT->notification($message);
639 $html .= $revertbutton . $hideminmaxbutton;
641 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
642 // Show the warning that there are min/max issues that have not be resolved.
643 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
645 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
646 $urlparams = array('id' => $courseid,
647 'useminmaxfromgradeitem' => true,
648 'sesskey' => sesskey());
649 $fixurl = new moodle_url($thispage, $urlparams);
650 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
652 $html .= $OUTPUT->notification($message);
653 $html .= $fixbutton . $hideminmaxbutton;
657 if ($gradebookcalculationsfreeze) {
658 if ($acceptgradebookchanges) {
659 // Accept potential changes in grades caused by extra credit bug MDL-49257.
660 hide_gradebook_calculations_freeze_notice($courseid);
661 $courseitem = grade_item::fetch_course_item($courseid);
662 $courseitem->force_regrading();
663 grade_regrade_final_grades($courseid);
665 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
666 } else {
667 // Show the warning that there may be extra credit weights problems.
668 $a = new stdClass();
669 $a->gradebookversion = $gradebookcalculationsfreeze;
670 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
671 $a->currentversion = $matches[1];
672 } else {
673 $a->currentversion = $CFG->release;
675 $a->url = get_docs_url('Gradebook_calculation_changes');
676 $message = get_string('gradebookcalculationswarning', 'grades', $a);
678 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
679 $urlparams = array('id' => $courseid,
680 'acceptgradebookchanges' => true,
681 'sesskey' => sesskey());
682 $fixurl = new moodle_url($thispage, $urlparams);
683 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
685 $html .= $OUTPUT->notification($message);
686 $html .= $fixbutton;
690 if (!empty($html)) {
691 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
694 if ($return) {
695 return $html;
696 } else {
697 echo $html;
702 * Print grading plugin selection popup form.
704 * @param array $plugin_info An array of plugins containing information for the selector
705 * @param boolean $return return as string
707 * @return nothing or string if $return true
709 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
710 global $CFG, $OUTPUT, $PAGE;
712 $menu = array();
713 $count = 0;
714 $active = '';
716 foreach ($plugin_info as $plugin_type => $plugins) {
717 if ($plugin_type == 'strings') {
718 continue;
721 $first_plugin = reset($plugins);
723 $sectionname = $plugin_info['strings'][$plugin_type];
724 $section = array();
726 foreach ($plugins as $plugin) {
727 $link = $plugin->link->out(false);
728 $section[$link] = $plugin->string;
729 $count++;
730 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
731 $active = $link;
735 if ($section) {
736 $menu[] = array($sectionname=>$section);
740 // finally print/return the popup form
741 if ($count > 1) {
742 $select = new url_select($menu, $active, null, 'choosepluginreport');
743 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
744 if ($return) {
745 return $OUTPUT->render($select);
746 } else {
747 echo $OUTPUT->render($select);
749 } else {
750 // only one option - no plugin selector needed
751 return '';
756 * Print grading plugin selection tab-based navigation.
758 * @param string $active_type type of plugin on current page - import, export, report or edit
759 * @param string $active_plugin active plugin type - grader, user, cvs, ...
760 * @param array $plugin_info Array of plugins
761 * @param boolean $return return as string
763 * @return nothing or string if $return true
765 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
766 global $CFG, $COURSE;
768 if (!isset($currenttab)) { //TODO: this is weird
769 $currenttab = '';
772 $tabs = array();
773 $top_row = array();
774 $bottom_row = array();
775 $inactive = array($active_plugin);
776 $activated = array($active_type);
778 $count = 0;
779 $active = '';
781 foreach ($plugin_info as $plugin_type => $plugins) {
782 if ($plugin_type == 'strings') {
783 continue;
786 // If $plugins is actually the definition of a child-less parent link:
787 if (!empty($plugins->id)) {
788 $string = $plugins->string;
789 if (!empty($plugin_info[$active_type]->parent)) {
790 $string = $plugin_info[$active_type]->parent->string;
793 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
794 continue;
797 $first_plugin = reset($plugins);
798 $url = $first_plugin->link;
800 if ($plugin_type == 'report') {
801 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
804 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
806 if ($active_type == $plugin_type) {
807 foreach ($plugins as $plugin) {
808 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
809 if ($plugin->id == $active_plugin) {
810 $inactive = array($plugin->id);
816 $tabs[] = $top_row;
817 $tabs[] = $bottom_row;
819 if ($return) {
820 return print_tabs($tabs, $active_plugin, $inactive, $activated, true);
821 } else {
822 print_tabs($tabs, $active_plugin, $inactive, $activated);
827 * grade_get_plugin_info
829 * @param int $courseid The course id
830 * @param string $active_type type of plugin on current page - import, export, report or edit
831 * @param string $active_plugin active plugin type - grader, user, cvs, ...
833 * @return array
835 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
836 global $CFG, $SITE;
838 $context = context_course::instance($courseid);
840 $plugin_info = array();
841 $count = 0;
842 $active = '';
843 $url_prefix = $CFG->wwwroot . '/grade/';
845 // Language strings
846 $plugin_info['strings'] = grade_helper::get_plugin_strings();
848 if ($reports = grade_helper::get_plugins_reports($courseid)) {
849 $plugin_info['report'] = $reports;
852 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
853 $plugin_info['settings'] = $settings;
856 if ($scale = grade_helper::get_info_scales($courseid)) {
857 $plugin_info['scale'] = array('view'=>$scale);
860 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
861 $plugin_info['outcome'] = $outcomes;
864 if ($letters = grade_helper::get_info_letters($courseid)) {
865 $plugin_info['letter'] = $letters;
868 if ($imports = grade_helper::get_plugins_import($courseid)) {
869 $plugin_info['import'] = $imports;
872 if ($exports = grade_helper::get_plugins_export($courseid)) {
873 $plugin_info['export'] = $exports;
876 foreach ($plugin_info as $plugin_type => $plugins) {
877 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
878 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
879 break;
881 foreach ($plugins as $plugin) {
882 if (is_a($plugin, 'grade_plugin_info')) {
883 if ($active_plugin == $plugin->id) {
884 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
890 return $plugin_info;
894 * A simple class containing info about grade plugins.
895 * Can be subclassed for special rules
897 * @package core_grades
898 * @copyright 2009 Nicolas Connault
899 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
901 class grade_plugin_info {
903 * A unique id for this plugin
905 * @var mixed
907 public $id;
909 * A URL to access this plugin
911 * @var mixed
913 public $link;
915 * The name of this plugin
917 * @var mixed
919 public $string;
921 * Another grade_plugin_info object, parent of the current one
923 * @var mixed
925 public $parent;
928 * Constructor
930 * @param int $id A unique id for this plugin
931 * @param string $link A URL to access this plugin
932 * @param string $string The name of this plugin
933 * @param object $parent Another grade_plugin_info object, parent of the current one
935 * @return void
937 public function __construct($id, $link, $string, $parent=null) {
938 $this->id = $id;
939 $this->link = $link;
940 $this->string = $string;
941 $this->parent = $parent;
946 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
947 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
948 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
949 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
950 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
952 * @param int $courseid Course id
953 * @param string $active_type The type of the current page (report, settings,
954 * import, export, scales, outcomes, letters)
955 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
956 * @param string $heading The heading of the page. Tries to guess if none is given
957 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
958 * @param string $bodytags Additional attributes that will be added to the <body> tag
959 * @param string $buttons Additional buttons to display on the page
960 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
961 * @param string $headerhelpidentifier The help string identifier if required.
962 * @param string $headerhelpcomponent The component for the help string.
963 * @param stdClass $user The user object for use with the user context header.
965 * @return string HTML code or nothing if $return == false
967 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
968 $heading = false, $return=false,
969 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null,
970 $user = null) {
971 global $CFG, $OUTPUT, $PAGE;
973 if ($active_type === 'preferences') {
974 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
975 $active_type = 'settings';
978 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
980 // Determine the string of the active plugin
981 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
982 $stractive_type = $plugin_info['strings'][$active_type];
984 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
985 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
986 } else {
987 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
990 if ($active_type == 'report') {
991 $PAGE->set_pagelayout('report');
992 } else {
993 $PAGE->set_pagelayout('admin');
995 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
996 $PAGE->set_heading($title);
997 if ($buttons instanceof single_button) {
998 $buttons = $OUTPUT->render($buttons);
1000 $PAGE->set_button($buttons);
1001 if ($courseid != SITEID) {
1002 grade_extend_settings($plugin_info, $courseid);
1005 // Set the current report as active in the breadcrumbs.
1006 if ($active_plugin !== null && $reportnav = $PAGE->settingsnav->find($active_plugin, navigation_node::TYPE_SETTING)) {
1007 $reportnav->make_active();
1010 $returnval = $OUTPUT->header();
1012 if (!$return) {
1013 echo $returnval;
1016 // Guess heading if not given explicitly
1017 if (!$heading) {
1018 $heading = $stractive_plugin;
1021 if ($shownavigation) {
1022 $navselector = null;
1023 if ($courseid != SITEID &&
1024 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
1025 // It's absolutely essential that this grade plugin selector is shown after the user header. Just ask Fred.
1026 $navselector = print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, true);
1027 if ($return) {
1028 $returnval .= $navselector;
1029 } else if (!isset($user)) {
1030 echo $navselector;
1034 $output = '';
1035 // Add a help dialogue box if provided.
1036 if (isset($headerhelpidentifier)) {
1037 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
1038 } else {
1039 if (isset($user)) {
1040 $output = $OUTPUT->context_header(
1041 array(
1042 'heading' => fullname($user),
1043 'user' => $user,
1044 'usercontext' => context_user::instance($user->id)
1045 ), 2
1046 ) . $navselector;
1047 } else {
1048 $output = $OUTPUT->heading($heading);
1052 if ($return) {
1053 $returnval .= $output;
1054 } else {
1055 echo $output;
1058 if ($courseid != SITEID &&
1059 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
1060 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
1064 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
1065 context_course::instance($courseid),
1066 $PAGE->url,
1067 $return);
1069 if ($return) {
1070 return $returnval;
1075 * Utility class used for return tracking when using edit and other forms in grade plugins
1077 * @package core_grades
1078 * @copyright 2009 Nicolas Connault
1079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1081 class grade_plugin_return {
1082 public $type;
1083 public $plugin;
1084 public $courseid;
1085 public $userid;
1086 public $page;
1089 * Constructor
1091 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
1093 public function __construct($params = null) {
1094 if (empty($params)) {
1095 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1096 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1097 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1098 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1099 $this->page = optional_param('gpr_page', null, PARAM_INT);
1101 } else {
1102 foreach ($params as $key=>$value) {
1103 if (property_exists($this, $key)) {
1104 $this->$key = $value;
1111 * Old syntax of class constructor. Deprecated in PHP7.
1113 * @deprecated since Moodle 3.1
1115 public function grade_plugin_return($params = null) {
1116 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
1117 self::__construct($params);
1121 * Returns return parameters as options array suitable for buttons.
1122 * @return array options
1124 public function get_options() {
1125 if (empty($this->type)) {
1126 return array();
1129 $params = array();
1131 if (!empty($this->plugin)) {
1132 $params['plugin'] = $this->plugin;
1135 if (!empty($this->courseid)) {
1136 $params['id'] = $this->courseid;
1139 if (!empty($this->userid)) {
1140 $params['userid'] = $this->userid;
1143 if (!empty($this->page)) {
1144 $params['page'] = $this->page;
1147 return $params;
1151 * Returns return url
1153 * @param string $default default url when params not set
1154 * @param array $extras Extra URL parameters
1156 * @return string url
1158 public function get_return_url($default, $extras=null) {
1159 global $CFG;
1161 if (empty($this->type) or empty($this->plugin)) {
1162 return $default;
1165 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1166 $glue = '?';
1168 if (!empty($this->courseid)) {
1169 $url .= $glue.'id='.$this->courseid;
1170 $glue = '&amp;';
1173 if (!empty($this->userid)) {
1174 $url .= $glue.'userid='.$this->userid;
1175 $glue = '&amp;';
1178 if (!empty($this->page)) {
1179 $url .= $glue.'page='.$this->page;
1180 $glue = '&amp;';
1183 if (!empty($extras)) {
1184 foreach ($extras as $key=>$value) {
1185 $url .= $glue.$key.'='.$value;
1186 $glue = '&amp;';
1190 return $url;
1194 * Returns string with hidden return tracking form elements.
1195 * @return string
1197 public function get_form_fields() {
1198 if (empty($this->type)) {
1199 return '';
1202 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1204 if (!empty($this->plugin)) {
1205 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1208 if (!empty($this->courseid)) {
1209 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1212 if (!empty($this->userid)) {
1213 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1216 if (!empty($this->page)) {
1217 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1222 * Add hidden elements into mform
1224 * @param object &$mform moodle form object
1226 * @return void
1228 public function add_mform_elements(&$mform) {
1229 if (empty($this->type)) {
1230 return;
1233 $mform->addElement('hidden', 'gpr_type', $this->type);
1234 $mform->setType('gpr_type', PARAM_SAFEDIR);
1236 if (!empty($this->plugin)) {
1237 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1238 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1241 if (!empty($this->courseid)) {
1242 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1243 $mform->setType('gpr_courseid', PARAM_INT);
1246 if (!empty($this->userid)) {
1247 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1248 $mform->setType('gpr_userid', PARAM_INT);
1251 if (!empty($this->page)) {
1252 $mform->addElement('hidden', 'gpr_page', $this->page);
1253 $mform->setType('gpr_page', PARAM_INT);
1258 * Add return tracking params into url
1260 * @param moodle_url $url A URL
1262 * @return string $url with return tracking params
1264 public function add_url_params(moodle_url $url) {
1265 if (empty($this->type)) {
1266 return $url;
1269 $url->param('gpr_type', $this->type);
1271 if (!empty($this->plugin)) {
1272 $url->param('gpr_plugin', $this->plugin);
1275 if (!empty($this->courseid)) {
1276 $url->param('gpr_courseid' ,$this->courseid);
1279 if (!empty($this->userid)) {
1280 $url->param('gpr_userid', $this->userid);
1283 if (!empty($this->page)) {
1284 $url->param('gpr_page', $this->page);
1287 return $url;
1292 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1294 * @param string $path The path of the calling script (using __FILE__?)
1295 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1296 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1297 * an array of keys and values (e.g courseid => $courseid, itemid...)
1299 * @return string
1301 function grade_build_nav($path, $pagename=null, $id=null) {
1302 global $CFG, $COURSE, $PAGE;
1304 $strgrades = get_string('grades', 'grades');
1306 // Parse the path and build navlinks from its elements
1307 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1308 $path = substr($path, $dirroot_length);
1309 $path = str_replace('\\', '/', $path);
1311 $path_elements = explode('/', $path);
1313 $path_elements_count = count($path_elements);
1315 // First link is always 'grade'
1316 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1318 $link = null;
1319 $numberofelements = 3;
1321 // Prepare URL params string
1322 $linkparams = array();
1323 if (!is_null($id)) {
1324 if (is_array($id)) {
1325 foreach ($id as $idkey => $idvalue) {
1326 $linkparams[$idkey] = $idvalue;
1328 } else {
1329 $linkparams['id'] = $id;
1333 $navlink4 = null;
1335 // Remove file extensions from filenames
1336 foreach ($path_elements as $key => $filename) {
1337 $path_elements[$key] = str_replace('.php', '', $filename);
1340 // Second level links
1341 switch ($path_elements[1]) {
1342 case 'edit': // No link
1343 if ($path_elements[3] != 'index.php') {
1344 $numberofelements = 4;
1346 break;
1347 case 'import': // No link
1348 break;
1349 case 'export': // No link
1350 break;
1351 case 'report':
1352 // $id is required for this link. Do not print it if $id isn't given
1353 if (!is_null($id)) {
1354 $link = new moodle_url('/grade/report/index.php', $linkparams);
1357 if ($path_elements[2] == 'grader') {
1358 $numberofelements = 4;
1360 break;
1362 default:
1363 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1364 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1365 " as the second path element after 'grade'.");
1366 return false;
1368 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1370 // Third level links
1371 if (empty($pagename)) {
1372 $pagename = get_string($path_elements[2], 'grades');
1375 switch ($numberofelements) {
1376 case 3:
1377 $PAGE->navbar->add($pagename, $link);
1378 break;
1379 case 4:
1380 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1381 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1383 $PAGE->navbar->add($pagename);
1384 break;
1387 return '';
1391 * General structure representing grade items in course
1393 * @package core_grades
1394 * @copyright 2009 Nicolas Connault
1395 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1397 class grade_structure {
1398 public $context;
1400 public $courseid;
1403 * Reference to modinfo for current course (for performance, to save
1404 * retrieving it from courseid every time). Not actually set except for
1405 * the grade_tree type.
1406 * @var course_modinfo
1408 public $modinfo;
1411 * 1D array of grade items only
1413 public $items;
1416 * Returns icon of element
1418 * @param array &$element An array representing an element in the grade_tree
1419 * @param bool $spacerifnone return spacer if no icon found
1421 * @return string icon or spacer
1423 public function get_element_icon(&$element, $spacerifnone=false) {
1424 global $CFG, $OUTPUT;
1425 require_once $CFG->libdir.'/filelib.php';
1427 $outputstr = '';
1429 // Object holding pix_icon information before instantiation.
1430 $icon = new stdClass();
1431 $icon->attributes = array(
1432 'class' => 'icon itemicon'
1434 $icon->component = 'moodle';
1436 $none = true;
1437 switch ($element['type']) {
1438 case 'item':
1439 case 'courseitem':
1440 case 'categoryitem':
1441 $none = false;
1443 $is_course = $element['object']->is_course_item();
1444 $is_category = $element['object']->is_category_item();
1445 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1446 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1447 $is_outcome = !empty($element['object']->outcomeid);
1449 if ($element['object']->is_calculated()) {
1450 $icon->pix = 'i/calc';
1451 $icon->title = s(get_string('calculatedgrade', 'grades'));
1453 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1454 if ($category = $element['object']->get_item_category()) {
1455 $aggrstrings = grade_helper::get_aggregation_strings();
1456 $stragg = $aggrstrings[$category->aggregation];
1458 $icon->pix = 'i/calc';
1459 $icon->title = s($stragg);
1461 switch ($category->aggregation) {
1462 case GRADE_AGGREGATE_MEAN:
1463 case GRADE_AGGREGATE_MEDIAN:
1464 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1465 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1466 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1467 $icon->pix = 'i/agg_mean';
1468 break;
1469 case GRADE_AGGREGATE_SUM:
1470 $icon->pix = 'i/agg_sum';
1471 break;
1475 } else if ($element['object']->itemtype == 'mod') {
1476 // Prevent outcomes displaying the same icon as the activity they are attached to.
1477 if ($is_outcome) {
1478 $icon->pix = 'i/outcomes';
1479 $icon->title = s(get_string('outcome', 'grades'));
1480 } else {
1481 $icon->pix = 'icon';
1482 $icon->component = $element['object']->itemmodule;
1483 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1485 } else if ($element['object']->itemtype == 'manual') {
1486 if ($element['object']->is_outcome_item()) {
1487 $icon->pix = 'i/outcomes';
1488 $icon->title = s(get_string('outcome', 'grades'));
1489 } else {
1490 $icon->pix = 'i/manual_item';
1491 $icon->title = s(get_string('manualitem', 'grades'));
1494 break;
1496 case 'category':
1497 $none = false;
1498 $icon->pix = 'i/folder';
1499 $icon->title = s(get_string('category', 'grades'));
1500 break;
1503 if ($none) {
1504 if ($spacerifnone) {
1505 $outputstr = $OUTPUT->spacer() . ' ';
1507 } else {
1508 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1511 return $outputstr;
1515 * Returns name of element optionally with icon and link
1517 * @param array &$element An array representing an element in the grade_tree
1518 * @param bool $withlink Whether or not this header has a link
1519 * @param bool $icon Whether or not to display an icon with this header
1520 * @param bool $spacerifnone return spacer if no icon found
1521 * @param bool $withdescription Show description if defined by this item.
1522 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1523 * instead of "Category total" or "Course total"
1525 * @return string header
1527 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1528 $withdescription = false, $fulltotal = false) {
1529 $header = '';
1531 if ($icon) {
1532 $header .= $this->get_element_icon($element, $spacerifnone);
1535 $header .= $element['object']->get_name($fulltotal);
1537 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1538 $element['type'] != 'courseitem') {
1539 return $header;
1542 if ($withlink && $url = $this->get_activity_link($element)) {
1543 $a = new stdClass();
1544 $a->name = get_string('modulename', $element['object']->itemmodule);
1545 $title = get_string('linktoactivity', 'grades', $a);
1547 $header = html_writer::link($url, $header, array('title' => $title));
1548 } else {
1549 $header = html_writer::span($header);
1552 if ($withdescription) {
1553 $desc = $element['object']->get_description();
1554 if (!empty($desc)) {
1555 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1559 return $header;
1562 private function get_activity_link($element) {
1563 global $CFG;
1564 /** @var array static cache of the grade.php file existence flags */
1565 static $hasgradephp = array();
1567 $itemtype = $element['object']->itemtype;
1568 $itemmodule = $element['object']->itemmodule;
1569 $iteminstance = $element['object']->iteminstance;
1570 $itemnumber = $element['object']->itemnumber;
1572 // Links only for module items that have valid instance, module and are
1573 // called from grade_tree with valid modinfo
1574 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1575 return null;
1578 // Get $cm efficiently and with visibility information using modinfo
1579 $instances = $this->modinfo->get_instances();
1580 if (empty($instances[$itemmodule][$iteminstance])) {
1581 return null;
1583 $cm = $instances[$itemmodule][$iteminstance];
1585 // Do not add link if activity is not visible to the current user
1586 if (!$cm->uservisible) {
1587 return null;
1590 if (!array_key_exists($itemmodule, $hasgradephp)) {
1591 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1592 $hasgradephp[$itemmodule] = true;
1593 } else {
1594 $hasgradephp[$itemmodule] = false;
1598 // If module has grade.php, link to that, otherwise view.php
1599 if ($hasgradephp[$itemmodule]) {
1600 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1601 if (isset($element['userid'])) {
1602 $args['userid'] = $element['userid'];
1604 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1605 } else {
1606 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1611 * Returns URL of a page that is supposed to contain detailed grade analysis
1613 * At the moment, only activity modules are supported. The method generates link
1614 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1615 * gradeid and userid. If the grade.php does not exist, null is returned.
1617 * @return moodle_url|null URL or null if unable to construct it
1619 public function get_grade_analysis_url(grade_grade $grade) {
1620 global $CFG;
1621 /** @var array static cache of the grade.php file existence flags */
1622 static $hasgradephp = array();
1624 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1625 throw new coding_exception('Passed grade without the associated grade item');
1627 $item = $grade->grade_item;
1629 if (!$item->is_external_item()) {
1630 // at the moment, only activity modules are supported
1631 return null;
1633 if ($item->itemtype !== 'mod') {
1634 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1636 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1637 return null;
1640 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1641 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1642 $hasgradephp[$item->itemmodule] = true;
1643 } else {
1644 $hasgradephp[$item->itemmodule] = false;
1648 if (!$hasgradephp[$item->itemmodule]) {
1649 return null;
1652 $instances = $this->modinfo->get_instances();
1653 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1654 return null;
1656 $cm = $instances[$item->itemmodule][$item->iteminstance];
1657 if (!$cm->uservisible) {
1658 return null;
1661 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1662 'id' => $cm->id,
1663 'itemid' => $item->id,
1664 'itemnumber' => $item->itemnumber,
1665 'gradeid' => $grade->id,
1666 'userid' => $grade->userid,
1669 return $url;
1673 * Returns an action icon leading to the grade analysis page
1675 * @param grade_grade $grade
1676 * @return string
1678 public function get_grade_analysis_icon(grade_grade $grade) {
1679 global $OUTPUT;
1681 $url = $this->get_grade_analysis_url($grade);
1682 if (is_null($url)) {
1683 return '';
1686 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1687 get_string('gradeanalysis', 'core_grades')));
1691 * Returns the grade eid - the grade may not exist yet.
1693 * @param grade_grade $grade_grade A grade_grade object
1695 * @return string eid
1697 public function get_grade_eid($grade_grade) {
1698 if (empty($grade_grade->id)) {
1699 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1700 } else {
1701 return 'g'.$grade_grade->id;
1706 * Returns the grade_item eid
1707 * @param grade_item $grade_item A grade_item object
1708 * @return string eid
1710 public function get_item_eid($grade_item) {
1711 return 'ig'.$grade_item->id;
1715 * Given a grade_tree element, returns an array of parameters
1716 * used to build an icon for that element.
1718 * @param array $element An array representing an element in the grade_tree
1720 * @return array
1722 public function get_params_for_iconstr($element) {
1723 $strparams = new stdClass();
1724 $strparams->category = '';
1725 $strparams->itemname = '';
1726 $strparams->itemmodule = '';
1728 if (!method_exists($element['object'], 'get_name')) {
1729 return $strparams;
1732 $strparams->itemname = html_to_text($element['object']->get_name());
1734 // If element name is categorytotal, get the name of the parent category
1735 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1736 $parent = $element['object']->get_parent_category();
1737 $strparams->category = $parent->get_name() . ' ';
1738 } else {
1739 $strparams->category = '';
1742 $strparams->itemmodule = null;
1743 if (isset($element['object']->itemmodule)) {
1744 $strparams->itemmodule = $element['object']->itemmodule;
1746 return $strparams;
1750 * Return a reset icon for the given element.
1752 * @param array $element An array representing an element in the grade_tree
1753 * @param object $gpr A grade_plugin_return object
1754 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1755 * @return string|action_menu_link
1757 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1758 global $CFG, $OUTPUT;
1760 // Limit to category items set to use the natural weights aggregation method, and users
1761 // with the capability to manage grades.
1762 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1763 !has_capability('moodle/grade:manage', $this->context)) {
1764 return $returnactionmenulink ? null : '';
1767 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1768 $url = new moodle_url('/grade/edit/tree/action.php', array(
1769 'id' => $this->courseid,
1770 'action' => 'resetweights',
1771 'eid' => $element['eid'],
1772 'sesskey' => sesskey(),
1775 if ($returnactionmenulink) {
1776 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1777 get_string('resetweightsshort', 'grades'));
1778 } else {
1779 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1784 * Return edit icon for give element
1786 * @param array $element An array representing an element in the grade_tree
1787 * @param object $gpr A grade_plugin_return object
1788 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1789 * @return string|action_menu_link
1791 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1792 global $CFG, $OUTPUT;
1794 if (!has_capability('moodle/grade:manage', $this->context)) {
1795 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1796 // oki - let them override grade
1797 } else {
1798 return $returnactionmenulink ? null : '';
1802 static $strfeedback = null;
1803 static $streditgrade = null;
1804 if (is_null($streditgrade)) {
1805 $streditgrade = get_string('editgrade', 'grades');
1806 $strfeedback = get_string('feedback');
1809 $strparams = $this->get_params_for_iconstr($element);
1811 $object = $element['object'];
1813 switch ($element['type']) {
1814 case 'item':
1815 case 'categoryitem':
1816 case 'courseitem':
1817 $stredit = get_string('editverbose', 'grades', $strparams);
1818 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1819 $url = new moodle_url('/grade/edit/tree/item.php',
1820 array('courseid' => $this->courseid, 'id' => $object->id));
1821 } else {
1822 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1823 array('courseid' => $this->courseid, 'id' => $object->id));
1825 break;
1827 case 'category':
1828 $stredit = get_string('editverbose', 'grades', $strparams);
1829 $url = new moodle_url('/grade/edit/tree/category.php',
1830 array('courseid' => $this->courseid, 'id' => $object->id));
1831 break;
1833 case 'grade':
1834 $stredit = $streditgrade;
1835 if (empty($object->id)) {
1836 $url = new moodle_url('/grade/edit/tree/grade.php',
1837 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1838 } else {
1839 $url = new moodle_url('/grade/edit/tree/grade.php',
1840 array('courseid' => $this->courseid, 'id' => $object->id));
1842 if (!empty($object->feedback)) {
1843 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1845 break;
1847 default:
1848 $url = null;
1851 if ($url) {
1852 if ($returnactionmenulink) {
1853 return new action_menu_link_secondary($gpr->add_url_params($url),
1854 new pix_icon('t/edit', $stredit),
1855 get_string('editsettings'));
1856 } else {
1857 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1860 } else {
1861 return $returnactionmenulink ? null : '';
1866 * Return hiding icon for give element
1868 * @param array $element An array representing an element in the grade_tree
1869 * @param object $gpr A grade_plugin_return object
1870 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1871 * @return string|action_menu_link
1873 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1874 global $CFG, $OUTPUT;
1876 if (!$element['object']->can_control_visibility()) {
1877 return $returnactionmenulink ? null : '';
1880 if (!has_capability('moodle/grade:manage', $this->context) and
1881 !has_capability('moodle/grade:hide', $this->context)) {
1882 return $returnactionmenulink ? null : '';
1885 $strparams = $this->get_params_for_iconstr($element);
1886 $strshow = get_string('showverbose', 'grades', $strparams);
1887 $strhide = get_string('hideverbose', 'grades', $strparams);
1889 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1890 $url = $gpr->add_url_params($url);
1892 if ($element['object']->is_hidden()) {
1893 $type = 'show';
1894 $tooltip = $strshow;
1896 // Change the icon and add a tooltip showing the date
1897 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1898 $type = 'hiddenuntil';
1899 $tooltip = get_string('hiddenuntildate', 'grades',
1900 userdate($element['object']->get_hidden()));
1903 $url->param('action', 'show');
1905 if ($returnactionmenulink) {
1906 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1907 } else {
1908 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1911 } else {
1912 $url->param('action', 'hide');
1913 if ($returnactionmenulink) {
1914 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1915 } else {
1916 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1920 return $hideicon;
1924 * Return locking icon for given element
1926 * @param array $element An array representing an element in the grade_tree
1927 * @param object $gpr A grade_plugin_return object
1929 * @return string
1931 public function get_locking_icon($element, $gpr) {
1932 global $CFG, $OUTPUT;
1934 $strparams = $this->get_params_for_iconstr($element);
1935 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1936 $strlock = get_string('lockverbose', 'grades', $strparams);
1938 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1939 $url = $gpr->add_url_params($url);
1941 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1942 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1943 $strparamobj = new stdClass();
1944 $strparamobj->itemname = $element['object']->grade_item->itemname;
1945 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1947 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1948 array('class' => 'action-icon'));
1950 } else if ($element['object']->is_locked()) {
1951 $type = 'unlock';
1952 $tooltip = $strunlock;
1954 // Change the icon and add a tooltip showing the date
1955 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1956 $type = 'locktime';
1957 $tooltip = get_string('locktimedate', 'grades',
1958 userdate($element['object']->get_locktime()));
1961 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1962 $action = '';
1963 } else {
1964 $url->param('action', 'unlock');
1965 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1968 } else {
1969 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1970 $action = '';
1971 } else {
1972 $url->param('action', 'lock');
1973 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1977 return $action;
1981 * Return calculation icon for given element
1983 * @param array $element An array representing an element in the grade_tree
1984 * @param object $gpr A grade_plugin_return object
1985 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1986 * @return string|action_menu_link
1988 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1989 global $CFG, $OUTPUT;
1990 if (!has_capability('moodle/grade:manage', $this->context)) {
1991 return $returnactionmenulink ? null : '';
1994 $type = $element['type'];
1995 $object = $element['object'];
1997 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1998 $strparams = $this->get_params_for_iconstr($element);
1999 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2001 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2002 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2004 // show calculation icon only when calculation possible
2005 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2006 if ($object->is_calculated()) {
2007 $icon = 't/calc';
2008 } else {
2009 $icon = 't/calc_off';
2012 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2013 $url = $gpr->add_url_params($url);
2014 if ($returnactionmenulink) {
2015 return new action_menu_link_secondary($url,
2016 new pix_icon($icon, $streditcalculation),
2017 get_string('editcalculation', 'grades'));
2018 } else {
2019 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2024 return $returnactionmenulink ? null : '';
2029 * Flat structure similar to grade tree.
2031 * @uses grade_structure
2032 * @package core_grades
2033 * @copyright 2009 Nicolas Connault
2034 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2036 class grade_seq extends grade_structure {
2039 * 1D array of elements
2041 public $elements;
2044 * Constructor, retrieves and stores array of all grade_category and grade_item
2045 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2047 * @param int $courseid The course id
2048 * @param bool $category_grade_last category grade item is the last child
2049 * @param bool $nooutcomes Whether or not outcomes should be included
2051 public function __construct($courseid, $category_grade_last=false, $nooutcomes=false) {
2052 global $USER, $CFG;
2054 $this->courseid = $courseid;
2055 $this->context = context_course::instance($courseid);
2057 // get course grade tree
2058 $top_element = grade_category::fetch_course_tree($courseid, true);
2060 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2062 foreach ($this->elements as $key=>$unused) {
2063 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2068 * Old syntax of class constructor. Deprecated in PHP7.
2070 * @deprecated since Moodle 3.1
2072 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2073 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2074 self::__construct($courseid, $category_grade_last, $nooutcomes);
2078 * Static recursive helper - makes the grade_item for category the last children
2080 * @param array &$element The seed of the recursion
2081 * @param bool $category_grade_last category grade item is the last child
2082 * @param bool $nooutcomes Whether or not outcomes should be included
2084 * @return array
2086 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2087 if (empty($element['children'])) {
2088 return array();
2090 $children = array();
2092 foreach ($element['children'] as $sortorder=>$unused) {
2093 if ($nooutcomes and $element['type'] != 'category' and
2094 $element['children'][$sortorder]['object']->is_outcome_item()) {
2095 continue;
2097 $children[] = $element['children'][$sortorder];
2099 unset($element['children']);
2101 if ($category_grade_last and count($children) > 1) {
2102 $cat_item = array_shift($children);
2103 array_push($children, $cat_item);
2106 $result = array();
2107 foreach ($children as $child) {
2108 if ($child['type'] == 'category') {
2109 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2110 } else {
2111 $child['eid'] = 'i'.$child['object']->id;
2112 $result[$child['object']->id] = $child;
2116 return $result;
2120 * Parses the array in search of a given eid and returns a element object with
2121 * information about the element it has found.
2123 * @param int $eid Gradetree Element ID
2125 * @return object element
2127 public function locate_element($eid) {
2128 // it is a grade - construct a new object
2129 if (strpos($eid, 'n') === 0) {
2130 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2131 return null;
2134 $itemid = $matches[1];
2135 $userid = $matches[2];
2137 //extra security check - the grade item must be in this tree
2138 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2139 return null;
2142 // $gradea->id may be null - means does not exist yet
2143 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2145 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2146 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2148 } else if (strpos($eid, 'g') === 0) {
2149 $id = (int) substr($eid, 1);
2150 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2151 return null;
2153 //extra security check - the grade item must be in this tree
2154 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2155 return null;
2157 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2158 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2161 // it is a category or item
2162 foreach ($this->elements as $element) {
2163 if ($element['eid'] == $eid) {
2164 return $element;
2168 return null;
2173 * This class represents a complete tree of categories, grade_items and final grades,
2174 * organises as an array primarily, but which can also be converted to other formats.
2175 * It has simple method calls with complex implementations, allowing for easy insertion,
2176 * deletion and moving of items and categories within the tree.
2178 * @uses grade_structure
2179 * @package core_grades
2180 * @copyright 2009 Nicolas Connault
2181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2183 class grade_tree extends grade_structure {
2186 * The basic representation of the tree as a hierarchical, 3-tiered array.
2187 * @var object $top_element
2189 public $top_element;
2192 * 2D array of grade items and categories
2193 * @var array $levels
2195 public $levels;
2198 * Grade items
2199 * @var array $items
2201 public $items;
2204 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2205 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2207 * @param int $courseid The Course ID
2208 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2209 * @param bool $category_grade_last category grade item is the last child
2210 * @param array $collapsed array of collapsed categories
2211 * @param bool $nooutcomes Whether or not outcomes should be included
2213 public function __construct($courseid, $fillers=true, $category_grade_last=false,
2214 $collapsed=null, $nooutcomes=false) {
2215 global $USER, $CFG, $COURSE, $DB;
2217 $this->courseid = $courseid;
2218 $this->levels = array();
2219 $this->context = context_course::instance($courseid);
2221 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2222 $course = $COURSE;
2223 } else {
2224 $course = $DB->get_record('course', array('id' => $this->courseid));
2226 $this->modinfo = get_fast_modinfo($course);
2228 // get course grade tree
2229 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2231 // collapse the categories if requested
2232 if (!empty($collapsed)) {
2233 grade_tree::category_collapse($this->top_element, $collapsed);
2236 // no otucomes if requested
2237 if (!empty($nooutcomes)) {
2238 grade_tree::no_outcomes($this->top_element);
2241 // move category item to last position in category
2242 if ($category_grade_last) {
2243 grade_tree::category_grade_last($this->top_element);
2246 if ($fillers) {
2247 // inject fake categories == fillers
2248 grade_tree::inject_fillers($this->top_element, 0);
2249 // add colspans to categories and fillers
2250 grade_tree::inject_colspans($this->top_element);
2253 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2258 * Old syntax of class constructor. Deprecated in PHP7.
2260 * @deprecated since Moodle 3.1
2262 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2263 $collapsed=null, $nooutcomes=false) {
2264 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
2265 self::__construct($courseid, $fillers, $category_grade_last, $collapsed, $nooutcomes);
2269 * Static recursive helper - removes items from collapsed categories
2271 * @param array &$element The seed of the recursion
2272 * @param array $collapsed array of collapsed categories
2274 * @return void
2276 public function category_collapse(&$element, $collapsed) {
2277 if ($element['type'] != 'category') {
2278 return;
2280 if (empty($element['children']) or count($element['children']) < 2) {
2281 return;
2284 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2285 $category_item = reset($element['children']); //keep only category item
2286 $element['children'] = array(key($element['children'])=>$category_item);
2288 } else {
2289 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2290 reset($element['children']);
2291 $first_key = key($element['children']);
2292 unset($element['children'][$first_key]);
2294 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2295 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2301 * Static recursive helper - removes all outcomes
2303 * @param array &$element The seed of the recursion
2305 * @return void
2307 public function no_outcomes(&$element) {
2308 if ($element['type'] != 'category') {
2309 return;
2311 foreach ($element['children'] as $sortorder=>$child) {
2312 if ($element['children'][$sortorder]['type'] == 'item'
2313 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2314 unset($element['children'][$sortorder]);
2316 } else if ($element['children'][$sortorder]['type'] == 'category') {
2317 grade_tree::no_outcomes($element['children'][$sortorder]);
2323 * Static recursive helper - makes the grade_item for category the last children
2325 * @param array &$element The seed of the recursion
2327 * @return void
2329 public function category_grade_last(&$element) {
2330 if (empty($element['children'])) {
2331 return;
2333 if (count($element['children']) < 2) {
2334 return;
2336 $first_item = reset($element['children']);
2337 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2338 // the category item might have been already removed
2339 $order = key($element['children']);
2340 unset($element['children'][$order]);
2341 $element['children'][$order] =& $first_item;
2343 foreach ($element['children'] as $sortorder => $child) {
2344 grade_tree::category_grade_last($element['children'][$sortorder]);
2349 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2351 * @param array &$levels The levels of the grade tree through which to recurse
2352 * @param array &$element The seed of the recursion
2353 * @param int $depth How deep are we?
2354 * @return void
2356 public function fill_levels(&$levels, &$element, $depth) {
2357 if (!array_key_exists($depth, $levels)) {
2358 $levels[$depth] = array();
2361 // prepare unique identifier
2362 if ($element['type'] == 'category') {
2363 $element['eid'] = 'cg'.$element['object']->id;
2364 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2365 $element['eid'] = 'ig'.$element['object']->id;
2366 $this->items[$element['object']->id] =& $element['object'];
2369 $levels[$depth][] =& $element;
2370 $depth++;
2371 if (empty($element['children'])) {
2372 return;
2374 $prev = 0;
2375 foreach ($element['children'] as $sortorder=>$child) {
2376 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2377 $element['children'][$sortorder]['prev'] = $prev;
2378 $element['children'][$sortorder]['next'] = 0;
2379 if ($prev) {
2380 $element['children'][$prev]['next'] = $sortorder;
2382 $prev = $sortorder;
2387 * Determines whether the grade tree item can be displayed.
2388 * This is particularly targeted for grade categories that have no total (None) when rendering the grade tree.
2389 * It checks if the grade tree item is of type 'category', and makes sure that the category, or at least one of children,
2390 * can be output.
2392 * @param array $element The grade category element.
2393 * @return bool True if the grade tree item can be displayed. False, otherwise.
2395 public static function can_output_item($element) {
2396 $canoutput = true;
2398 if ($element['type'] === 'category') {
2399 $object = $element['object'];
2400 $category = grade_category::fetch(array('id' => $object->id));
2401 // Category has total, we can output this.
2402 if ($category->get_grade_item()->gradetype != GRADE_TYPE_NONE) {
2403 return true;
2406 // Category has no total and has no children, no need to output this.
2407 if (empty($element['children'])) {
2408 return false;
2411 $canoutput = false;
2412 // Loop over children and make sure at least one child can be output.
2413 foreach ($element['children'] as $child) {
2414 $canoutput = self::can_output_item($child);
2415 if ($canoutput) {
2416 break;
2421 return $canoutput;
2425 * Static recursive helper - makes full tree (all leafes are at the same level)
2427 * @param array &$element The seed of the recursion
2428 * @param int $depth How deep are we?
2430 * @return int
2432 public function inject_fillers(&$element, $depth) {
2433 $depth++;
2435 if (empty($element['children'])) {
2436 return $depth;
2438 $chdepths = array();
2439 $chids = array_keys($element['children']);
2440 $last_child = end($chids);
2441 $first_child = reset($chids);
2443 foreach ($chids as $chid) {
2444 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2446 arsort($chdepths);
2448 $maxdepth = reset($chdepths);
2449 foreach ($chdepths as $chid=>$chd) {
2450 if ($chd == $maxdepth) {
2451 continue;
2453 if (!self::can_output_item($element['children'][$chid])) {
2454 continue;
2456 for ($i=0; $i < $maxdepth-$chd; $i++) {
2457 if ($chid == $first_child) {
2458 $type = 'fillerfirst';
2459 } else if ($chid == $last_child) {
2460 $type = 'fillerlast';
2461 } else {
2462 $type = 'filler';
2464 $oldchild =& $element['children'][$chid];
2465 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2466 'eid'=>'', 'depth'=>$element['object']->depth,
2467 'children'=>array($oldchild));
2471 return $maxdepth;
2475 * Static recursive helper - add colspan information into categories
2477 * @param array &$element The seed of the recursion
2479 * @return int
2481 public function inject_colspans(&$element) {
2482 if (empty($element['children'])) {
2483 return 1;
2485 $count = 0;
2486 foreach ($element['children'] as $key=>$child) {
2487 if (!self::can_output_item($child)) {
2488 continue;
2490 $count += grade_tree::inject_colspans($element['children'][$key]);
2492 $element['colspan'] = $count;
2493 return $count;
2497 * Parses the array in search of a given eid and returns a element object with
2498 * information about the element it has found.
2499 * @param int $eid Gradetree Element ID
2500 * @return object element
2502 public function locate_element($eid) {
2503 // it is a grade - construct a new object
2504 if (strpos($eid, 'n') === 0) {
2505 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2506 return null;
2509 $itemid = $matches[1];
2510 $userid = $matches[2];
2512 //extra security check - the grade item must be in this tree
2513 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2514 return null;
2517 // $gradea->id may be null - means does not exist yet
2518 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2520 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2521 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2523 } else if (strpos($eid, 'g') === 0) {
2524 $id = (int) substr($eid, 1);
2525 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2526 return null;
2528 //extra security check - the grade item must be in this tree
2529 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2530 return null;
2532 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2533 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2536 // it is a category or item
2537 foreach ($this->levels as $row) {
2538 foreach ($row as $element) {
2539 if ($element['type'] == 'filler') {
2540 continue;
2542 if ($element['eid'] == $eid) {
2543 return $element;
2548 return null;
2552 * Returns a well-formed XML representation of the grade-tree using recursion.
2554 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2555 * @param string $tabs The control character to use for tabs
2557 * @return string $xml
2559 public function exporttoxml($root=null, $tabs="\t") {
2560 $xml = null;
2561 $first = false;
2562 if (is_null($root)) {
2563 $root = $this->top_element;
2564 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2565 $xml .= "<gradetree>\n";
2566 $first = true;
2569 $type = 'undefined';
2570 if (strpos($root['object']->table, 'grade_categories') !== false) {
2571 $type = 'category';
2572 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2573 $type = 'item';
2574 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2575 $type = 'outcome';
2578 $xml .= "$tabs<element type=\"$type\">\n";
2579 foreach ($root['object'] as $var => $value) {
2580 if (!is_object($value) && !is_array($value) && !empty($value)) {
2581 $xml .= "$tabs\t<$var>$value</$var>\n";
2585 if (!empty($root['children'])) {
2586 $xml .= "$tabs\t<children>\n";
2587 foreach ($root['children'] as $sortorder => $child) {
2588 $xml .= $this->exportToXML($child, $tabs."\t\t");
2590 $xml .= "$tabs\t</children>\n";
2593 $xml .= "$tabs</element>\n";
2595 if ($first) {
2596 $xml .= "</gradetree>";
2599 return $xml;
2603 * Returns a JSON representation of the grade-tree using recursion.
2605 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2606 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2608 * @return string
2610 public function exporttojson($root=null, $tabs="\t") {
2611 $json = null;
2612 $first = false;
2613 if (is_null($root)) {
2614 $root = $this->top_element;
2615 $first = true;
2618 $name = '';
2621 if (strpos($root['object']->table, 'grade_categories') !== false) {
2622 $name = $root['object']->fullname;
2623 if ($name == '?') {
2624 $name = $root['object']->get_name();
2626 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2627 $name = $root['object']->itemname;
2628 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2629 $name = $root['object']->itemname;
2632 $json .= "$tabs {\n";
2633 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2634 $json .= "$tabs\t \"name\": \"$name\",\n";
2636 foreach ($root['object'] as $var => $value) {
2637 if (!is_object($value) && !is_array($value) && !empty($value)) {
2638 $json .= "$tabs\t \"$var\": \"$value\",\n";
2642 $json = substr($json, 0, strrpos($json, ','));
2644 if (!empty($root['children'])) {
2645 $json .= ",\n$tabs\t\"children\": [\n";
2646 foreach ($root['children'] as $sortorder => $child) {
2647 $json .= $this->exportToJSON($child, $tabs."\t\t");
2649 $json = substr($json, 0, strrpos($json, ','));
2650 $json .= "\n$tabs\t]\n";
2653 if ($first) {
2654 $json .= "\n}";
2655 } else {
2656 $json .= "\n$tabs},\n";
2659 return $json;
2663 * Returns the array of levels
2665 * @return array
2667 public function get_levels() {
2668 return $this->levels;
2672 * Returns the array of grade items
2674 * @return array
2676 public function get_items() {
2677 return $this->items;
2681 * Returns a specific Grade Item
2683 * @param int $itemid The ID of the grade_item object
2685 * @return grade_item
2687 public function get_item($itemid) {
2688 if (array_key_exists($itemid, $this->items)) {
2689 return $this->items[$itemid];
2690 } else {
2691 return false;
2697 * Local shortcut function for creating an edit/delete button for a grade_* object.
2698 * @param string $type 'edit' or 'delete'
2699 * @param int $courseid The Course ID
2700 * @param grade_* $object The grade_* object
2701 * @return string html
2703 function grade_button($type, $courseid, $object) {
2704 global $CFG, $OUTPUT;
2705 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2706 $objectidstring = $matches[1] . 'id';
2707 } else {
2708 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2711 $strdelete = get_string('delete');
2712 $stredit = get_string('edit');
2714 if ($type == 'delete') {
2715 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2716 } else if ($type == 'edit') {
2717 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2720 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2725 * This method adds settings to the settings block for the grade system and its
2726 * plugins
2728 * @global moodle_page $PAGE
2730 function grade_extend_settings($plugininfo, $courseid) {
2731 global $PAGE;
2733 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2735 $strings = array_shift($plugininfo);
2737 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2738 foreach ($reports as $report) {
2739 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2743 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2744 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2745 foreach ($settings as $setting) {
2746 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2750 if ($imports = grade_helper::get_plugins_import($courseid)) {
2751 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2752 foreach ($imports as $import) {
2753 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2757 if ($exports = grade_helper::get_plugins_export($courseid)) {
2758 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2759 foreach ($exports as $export) {
2760 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2764 if ($letters = grade_helper::get_info_letters($courseid)) {
2765 $letters = array_shift($letters);
2766 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2769 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2770 $outcomes = array_shift($outcomes);
2771 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2774 if ($scales = grade_helper::get_info_scales($courseid)) {
2775 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2778 if ($gradenode->contains_active_node()) {
2779 // If the gradenode is active include the settings base node (gradeadministration) in
2780 // the navbar, typcially this is ignored.
2781 $PAGE->navbar->includesettingsbase = true;
2783 // If we can get the course admin node make sure it is closed by default
2784 // as in this case the gradenode will be opened
2785 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2786 $coursenode->make_inactive();
2787 $coursenode->forceopen = false;
2793 * Grade helper class
2795 * This class provides several helpful functions that work irrespective of any
2796 * current state.
2798 * @copyright 2010 Sam Hemelryk
2799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2801 abstract class grade_helper {
2803 * Cached manage settings info {@see get_info_settings}
2804 * @var grade_plugin_info|false
2806 protected static $managesetting = null;
2808 * Cached grade report plugins {@see get_plugins_reports}
2809 * @var array|false
2811 protected static $gradereports = null;
2813 * Cached grade report plugins preferences {@see get_info_scales}
2814 * @var array|false
2816 protected static $gradereportpreferences = null;
2818 * Cached scale info {@see get_info_scales}
2819 * @var grade_plugin_info|false
2821 protected static $scaleinfo = null;
2823 * Cached outcome info {@see get_info_outcomes}
2824 * @var grade_plugin_info|false
2826 protected static $outcomeinfo = null;
2828 * Cached leftter info {@see get_info_letters}
2829 * @var grade_plugin_info|false
2831 protected static $letterinfo = null;
2833 * Cached grade import plugins {@see get_plugins_import}
2834 * @var array|false
2836 protected static $importplugins = null;
2838 * Cached grade export plugins {@see get_plugins_export}
2839 * @var array|false
2841 protected static $exportplugins = null;
2843 * Cached grade plugin strings
2844 * @var array
2846 protected static $pluginstrings = null;
2848 * Cached grade aggregation strings
2849 * @var array
2851 protected static $aggregationstrings = null;
2854 * Gets strings commonly used by the describe plugins
2856 * report => get_string('view'),
2857 * scale => get_string('scales'),
2858 * outcome => get_string('outcomes', 'grades'),
2859 * letter => get_string('letters', 'grades'),
2860 * export => get_string('export', 'grades'),
2861 * import => get_string('import'),
2862 * settings => get_string('settings')
2864 * @return array
2866 public static function get_plugin_strings() {
2867 if (self::$pluginstrings === null) {
2868 self::$pluginstrings = array(
2869 'report' => get_string('view'),
2870 'scale' => get_string('scales'),
2871 'outcome' => get_string('outcomes', 'grades'),
2872 'letter' => get_string('letters', 'grades'),
2873 'export' => get_string('export', 'grades'),
2874 'import' => get_string('import'),
2875 'settings' => get_string('edittree', 'grades')
2878 return self::$pluginstrings;
2882 * Gets strings describing the available aggregation methods.
2884 * @return array
2886 public static function get_aggregation_strings() {
2887 if (self::$aggregationstrings === null) {
2888 self::$aggregationstrings = array(
2889 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2890 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2891 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2892 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2893 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2894 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2895 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2896 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2897 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2900 return self::$aggregationstrings;
2904 * Get grade_plugin_info object for managing settings if the user can
2906 * @param int $courseid
2907 * @return grade_plugin_info[]
2909 public static function get_info_manage_settings($courseid) {
2910 if (self::$managesetting !== null) {
2911 return self::$managesetting;
2913 $context = context_course::instance($courseid);
2914 self::$managesetting = array();
2915 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2916 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
2917 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2918 get_string('gradebooksetup', 'grades'));
2919 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2920 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2921 get_string('coursegradesettings', 'grades'));
2923 if (self::$gradereportpreferences === null) {
2924 self::get_plugins_reports($courseid);
2926 if (self::$gradereportpreferences) {
2927 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
2929 return self::$managesetting;
2932 * Returns an array of plugin reports as grade_plugin_info objects
2934 * @param int $courseid
2935 * @return array
2937 public static function get_plugins_reports($courseid) {
2938 global $SITE;
2940 if (self::$gradereports !== null) {
2941 return self::$gradereports;
2943 $context = context_course::instance($courseid);
2944 $gradereports = array();
2945 $gradepreferences = array();
2946 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2947 //some reports make no sense if we're not within a course
2948 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2949 continue;
2952 // Remove ones we can't see
2953 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2954 continue;
2957 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
2958 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
2959 'moodle/grade:edit'), $context)) {
2960 continue;
2963 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2964 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2965 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2967 // Add link to preferences tab if such a page exists
2968 if (file_exists($plugindir.'/preferences.php')) {
2969 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2970 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2971 get_string('preferences', 'grades') . ': ' . $pluginstr);
2974 if (count($gradereports) == 0) {
2975 $gradereports = false;
2976 $gradepreferences = false;
2977 } else if (count($gradepreferences) == 0) {
2978 $gradepreferences = false;
2979 asort($gradereports);
2980 } else {
2981 asort($gradereports);
2982 asort($gradepreferences);
2984 self::$gradereports = $gradereports;
2985 self::$gradereportpreferences = $gradepreferences;
2986 return self::$gradereports;
2990 * Get information on scales
2991 * @param int $courseid
2992 * @return grade_plugin_info
2994 public static function get_info_scales($courseid) {
2995 if (self::$scaleinfo !== null) {
2996 return self::$scaleinfo;
2998 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2999 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
3000 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
3001 } else {
3002 self::$scaleinfo = false;
3004 return self::$scaleinfo;
3007 * Get information on outcomes
3008 * @param int $courseid
3009 * @return grade_plugin_info
3011 public static function get_info_outcomes($courseid) {
3012 global $CFG, $SITE;
3014 if (self::$outcomeinfo !== null) {
3015 return self::$outcomeinfo;
3017 $context = context_course::instance($courseid);
3018 $canmanage = has_capability('moodle/grade:manage', $context);
3019 $canupdate = has_capability('moodle/course:update', $context);
3020 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
3021 $outcomes = array();
3022 if ($canupdate) {
3023 if ($courseid!=$SITE->id) {
3024 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3025 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
3027 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
3028 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
3029 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
3030 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
3031 } else {
3032 if ($courseid!=$SITE->id) {
3033 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
3034 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
3037 self::$outcomeinfo = $outcomes;
3038 } else {
3039 self::$outcomeinfo = false;
3041 return self::$outcomeinfo;
3044 * Get information on letters
3045 * @param int $courseid
3046 * @return array
3048 public static function get_info_letters($courseid) {
3049 global $SITE;
3050 if (self::$letterinfo !== null) {
3051 return self::$letterinfo;
3053 $context = context_course::instance($courseid);
3054 $canmanage = has_capability('moodle/grade:manage', $context);
3055 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
3056 if ($canmanage || $canmanageletters) {
3057 // Redirect to system context when report is accessed from admin settings MDL-31633
3058 if ($context->instanceid == $SITE->id) {
3059 $param = array('edit' => 1);
3060 } else {
3061 $param = array('edit' => 1,'id' => $context->id);
3063 self::$letterinfo = array(
3064 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
3065 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3067 } else {
3068 self::$letterinfo = false;
3070 return self::$letterinfo;
3073 * Get information import plugins
3074 * @param int $courseid
3075 * @return array
3077 public static function get_plugins_import($courseid) {
3078 global $CFG;
3080 if (self::$importplugins !== null) {
3081 return self::$importplugins;
3083 $importplugins = array();
3084 $context = context_course::instance($courseid);
3086 if (has_capability('moodle/grade:import', $context)) {
3087 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3088 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3089 continue;
3091 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3092 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3093 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3096 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3097 // XML is the only grade import plugin that has publishing feature.
3098 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3099 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3100 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3104 if (count($importplugins) > 0) {
3105 asort($importplugins);
3106 self::$importplugins = $importplugins;
3107 } else {
3108 self::$importplugins = false;
3110 return self::$importplugins;
3113 * Get information export plugins
3114 * @param int $courseid
3115 * @return array
3117 public static function get_plugins_export($courseid) {
3118 global $CFG;
3120 if (self::$exportplugins !== null) {
3121 return self::$exportplugins;
3123 $context = context_course::instance($courseid);
3124 $exportplugins = array();
3125 $canpublishgrades = 0;
3126 if (has_capability('moodle/grade:export', $context)) {
3127 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3128 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3129 continue;
3131 // All the grade export plugins has grade publishing capabilities.
3132 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3133 $canpublishgrades++;
3136 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3137 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3138 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3141 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3142 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3143 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3144 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3147 if (count($exportplugins) > 0) {
3148 asort($exportplugins);
3149 self::$exportplugins = $exportplugins;
3150 } else {
3151 self::$exportplugins = false;
3153 return self::$exportplugins;
3157 * Returns the value of a field from a user record
3159 * @param stdClass $user object
3160 * @param stdClass $field object
3161 * @return string value of the field
3163 public static function get_user_field_value($user, $field) {
3164 if (!empty($field->customid)) {
3165 $fieldname = 'customfield_' . $field->shortname;
3166 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3167 $fieldvalue = $user->{$fieldname};
3168 } else {
3169 $fieldvalue = $field->default;
3171 } else {
3172 $fieldvalue = $user->{$field->shortname};
3174 return $fieldvalue;
3178 * Returns an array of user profile fields to be included in export
3180 * @param int $courseid
3181 * @param bool $includecustomfields
3182 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3184 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3185 global $CFG, $DB;
3187 // Gets the fields that have to be hidden
3188 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3189 $context = context_course::instance($courseid);
3190 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3191 if ($canseehiddenfields) {
3192 $hiddenfields = array();
3195 $fields = array();
3196 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3197 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3198 $userdefaultfields = user_get_default_fields();
3200 // Sets the list of profile fields
3201 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3202 if (!empty($userprofilefields)) {
3203 foreach ($userprofilefields as $field) {
3204 $field = trim($field);
3205 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3206 continue;
3208 $obj = new stdClass();
3209 $obj->customid = 0;
3210 $obj->shortname = $field;
3211 $obj->fullname = get_string($field);
3212 $fields[] = $obj;
3216 // Sets the list of custom profile fields
3217 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3218 if ($includecustomfields && !empty($customprofilefields)) {
3219 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
3220 $customfields = $DB->get_records_sql("SELECT f.*
3221 FROM {user_info_field} f
3222 JOIN {user_info_category} c ON f.categoryid=c.id
3223 WHERE f.shortname $wherefields
3224 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
3226 foreach ($customfields as $field) {
3227 // Make sure we can display this custom field
3228 if (!in_array($field->shortname, $customprofilefields)) {
3229 continue;
3230 } else if (in_array($field->shortname, $hiddenfields)) {
3231 continue;
3232 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3233 continue;
3236 $obj = new stdClass();
3237 $obj->customid = $field->id;
3238 $obj->shortname = $field->shortname;
3239 $obj->fullname = format_string($field->name);
3240 $obj->datatype = $field->datatype;
3241 $obj->default = $field->defaultdata;
3242 $fields[] = $obj;
3246 return $fields;
3250 * This helper method gets a snapshot of all the weights for a course.
3251 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3252 * @param int $courseid
3253 * @return array of itemid -> aggregationcoef2
3255 public static function fetch_all_natural_weights_for_course($courseid) {
3256 global $DB;
3257 $result = array();
3259 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3260 foreach ($records as $record) {
3261 $result[$record->id] = $record->aggregationcoef2;
3263 return $result;