Merge branch 'MDL-51312_master' of git://github.com/markn86/moodle
[moodle.git] / grade / lib.php
blob2216d570fb58b4bef48375d3a9f4b55721b677fb
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);
314 // Set user suspended status.
315 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
316 $result = new stdClass();
317 $result->user = $user;
318 $result->grades = $grades;
319 $result->feedbacks = $feedbacks;
320 return $result;
324 * Close the iterator, do not forget to call this function
326 public function close() {
327 if ($this->users_rs) {
328 $this->users_rs->close();
329 $this->users_rs = null;
331 if ($this->grades_rs) {
332 $this->grades_rs->close();
333 $this->grades_rs = null;
335 $this->gradestack = array();
339 * Should all enrolled users be exported or just those with an active enrolment?
341 * @param bool $onlyactive True to limit the export to users with an active enrolment
343 public function require_active_enrolment($onlyactive = true) {
344 if (!empty($this->users_rs)) {
345 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
347 $this->onlyactive = $onlyactive;
351 * Allow custom fields to be included
353 * @param bool $allow Whether to allow custom fields or not
354 * @return void
356 public function allow_user_custom_fields($allow = true) {
357 if ($allow) {
358 $this->allowusercustomfields = true;
359 } else {
360 $this->allowusercustomfields = false;
365 * Add a grade_grade instance to the grade stack
367 * @param grade_grade $grade Grade object
369 * @return void
371 private function _push($grade) {
372 array_push($this->gradestack, $grade);
377 * Remove a grade_grade instance from the grade stack
379 * @return grade_grade current grade object
381 private function _pop() {
382 global $DB;
383 if (empty($this->gradestack)) {
384 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
385 return null; // no grades present
388 $current = $this->grades_rs->current();
390 $this->grades_rs->next();
392 return $current;
393 } else {
394 return array_pop($this->gradestack);
400 * Print a selection popup form of the graded users in a course.
402 * @deprecated since 2.0
404 * @param int $course id of the course
405 * @param string $actionpage The page receiving the data from the popoup form
406 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
407 * @param int $groupid id of requested group, 0 means all
408 * @param int $includeall bool include all option
409 * @param bool $return If true, will return the HTML, otherwise, will print directly
410 * @return null
412 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
413 global $CFG, $USER, $OUTPUT;
414 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
417 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
418 global $USER, $CFG;
420 if (is_null($userid)) {
421 $userid = $USER->id;
423 $coursecontext = context_course::instance($course->id);
424 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
425 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
426 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
427 $menu = array(); // Will be a list of userid => user name
428 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
429 $gui = new graded_users_iterator($course, null, $groupid);
430 $gui->require_active_enrolment($showonlyactiveenrol);
431 $gui->init();
432 $label = get_string('selectauser', 'grades');
433 if ($includeall) {
434 $menu[0] = get_string('allusers', 'grades');
435 $label = get_string('selectalloroneuser', 'grades');
437 while ($userdata = $gui->next_user()) {
438 $user = $userdata->user;
439 $userfullname = fullname($user);
440 if ($user->suspendedenrolment) {
441 $menususpendedusers[$user->id] = $userfullname;
442 } else {
443 $menu[$user->id] = $userfullname;
446 $gui->close();
448 if ($includeall) {
449 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
452 if (!empty($menususpendedusers)) {
453 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
455 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
456 $select->label = $label;
457 $select->formid = 'choosegradeuser';
458 return $select;
462 * Hide warning about changed grades during upgrade to 2.8.
464 * @param int $courseid The current course id.
466 function hide_natural_aggregation_upgrade_notice($courseid) {
467 unset_config('show_sumofgrades_upgrade_' . $courseid);
471 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
473 * @param int $courseid The current course id.
475 function grade_hide_min_max_grade_upgrade_notice($courseid) {
476 unset_config('show_min_max_grades_changed_' . $courseid);
480 * Use the grade min and max from the grade_grade.
482 * This is reserved for core use after an upgrade.
484 * @param int $courseid The current course id.
486 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
487 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
489 grade_force_full_regrading($courseid);
490 // Do this now, because it probably happened to late in the page load to be happen automatically.
491 grade_regrade_final_grades($courseid);
495 * Use the grade min and max from the grade_item.
497 * This is reserved for core use after an upgrade.
499 * @param int $courseid The current course id.
501 function grade_upgrade_use_min_max_from_grade_item($courseid) {
502 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
504 grade_force_full_regrading($courseid);
505 // Do this now, because it probably happened to late in the page load to be happen automatically.
506 grade_regrade_final_grades($courseid);
510 * Hide warning about changed grades during upgrade to 2.8.
512 * @param int $courseid The current course id.
514 function hide_aggregatesubcats_upgrade_notice($courseid) {
515 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
519 * Hide warning about changed grades due to bug fixes
521 * @param int $courseid The current course id.
523 function hide_gradebook_calculations_freeze_notice($courseid) {
524 unset_config('gradebook_calculations_freeze_' . $courseid);
528 * Print warning about changed grades during upgrade to 2.8.
530 * @param int $courseid The current course id.
531 * @param context $context The course context.
532 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
533 * @param boolean $return return as string
535 * @return nothing or string if $return true
537 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
538 global $CFG, $OUTPUT;
539 $html = '';
541 // Do not do anything if they cannot manage the grades of this course.
542 if (!has_capability('moodle/grade:manage', $context)) {
543 return $html;
546 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
547 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
548 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
549 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
551 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
552 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
554 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
555 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
557 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
559 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
560 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
562 // Hide the warning if the user told it to go away.
563 if ($hidenaturalwarning) {
564 hide_natural_aggregation_upgrade_notice($courseid);
566 // Hide the warning if the user told it to go away.
567 if ($hidesubcatswarning) {
568 hide_aggregatesubcats_upgrade_notice($courseid);
571 // Hide the min/max warning if the user told it to go away.
572 if ($hideminmaxwarning) {
573 grade_hide_min_max_grade_upgrade_notice($courseid);
574 $showminmaxwarning = false;
577 if ($useminmaxfromgradegrade) {
578 // Revert to the new behaviour, we now use the grade_grade for min/max.
579 grade_upgrade_use_min_max_from_grade_grade($courseid);
580 grade_hide_min_max_grade_upgrade_notice($courseid);
581 $showminmaxwarning = false;
583 } else if ($useminmaxfromgradeitem) {
584 // Apply the new logic, we now use the grade_item for min/max.
585 grade_upgrade_use_min_max_from_grade_item($courseid);
586 grade_hide_min_max_grade_upgrade_notice($courseid);
587 $showminmaxwarning = false;
591 if (!$hidenaturalwarning && $shownaturalwarning) {
592 $message = get_string('sumofgradesupgradedgrades', 'grades');
593 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
594 $urlparams = array( 'id' => $courseid,
595 'seensumofgradesupgradedgrades' => true,
596 'sesskey' => sesskey());
597 $goawayurl = new moodle_url($thispage, $urlparams);
598 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
599 $html .= $OUTPUT->notification($message, 'notifysuccess');
600 $html .= $goawaybutton;
603 if (!$hidesubcatswarning && $showsubcatswarning) {
604 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
605 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
606 $urlparams = array( 'id' => $courseid,
607 'seenaggregatesubcatsupgradedgrades' => true,
608 'sesskey' => sesskey());
609 $goawayurl = new moodle_url($thispage, $urlparams);
610 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
611 $html .= $OUTPUT->notification($message, 'notifysuccess');
612 $html .= $goawaybutton;
615 if ($showminmaxwarning) {
616 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
617 $urlparams = array( 'id' => $courseid,
618 'seenminmaxupgradedgrades' => true,
619 'sesskey' => sesskey());
621 $goawayurl = new moodle_url($thispage, $urlparams);
622 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
623 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
624 array('target' => '_blank'));
626 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
627 // Show the message that there were min/max issues that have been resolved.
628 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
630 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
631 $urlparams = array('id' => $courseid,
632 'useminmaxfromgradegrade' => true,
633 'sesskey' => sesskey());
634 $reverturl = new moodle_url($thispage, $urlparams);
635 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
637 $html .= $OUTPUT->notification($message);
638 $html .= $revertbutton . $hideminmaxbutton;
640 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
641 // Show the warning that there are min/max issues that have not be resolved.
642 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
644 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
645 $urlparams = array('id' => $courseid,
646 'useminmaxfromgradeitem' => true,
647 'sesskey' => sesskey());
648 $fixurl = new moodle_url($thispage, $urlparams);
649 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
651 $html .= $OUTPUT->notification($message);
652 $html .= $fixbutton . $hideminmaxbutton;
656 if ($gradebookcalculationsfreeze) {
657 if ($acceptgradebookchanges) {
658 // Accept potential changes in grades caused by extra credit bug MDL-49257.
659 hide_gradebook_calculations_freeze_notice($courseid);
660 $courseitem = grade_item::fetch_course_item($courseid);
661 $courseitem->force_regrading();
662 grade_regrade_final_grades($courseid);
664 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
665 } else {
666 // Show the warning that there may be extra credit weights problems.
667 $a = new stdClass();
668 $a->gradebookversion = $gradebookcalculationsfreeze;
669 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
670 $a->currentversion = $matches[1];
671 } else {
672 $a->currentversion = $CFG->release;
674 $a->url = get_docs_url('Gradebook_calculation_changes');
675 $message = get_string('gradebookcalculationswarning', 'grades', $a);
677 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
678 $urlparams = array('id' => $courseid,
679 'acceptgradebookchanges' => true,
680 'sesskey' => sesskey());
681 $fixurl = new moodle_url($thispage, $urlparams);
682 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
684 $html .= $OUTPUT->notification($message);
685 $html .= $fixbutton;
689 if (!empty($html)) {
690 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
693 if ($return) {
694 return $html;
695 } else {
696 echo $html;
701 * Print grading plugin selection popup form.
703 * @param array $plugin_info An array of plugins containing information for the selector
704 * @param boolean $return return as string
706 * @return nothing or string if $return true
708 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
709 global $CFG, $OUTPUT, $PAGE;
711 $menu = array();
712 $count = 0;
713 $active = '';
715 foreach ($plugin_info as $plugin_type => $plugins) {
716 if ($plugin_type == 'strings') {
717 continue;
720 $first_plugin = reset($plugins);
722 $sectionname = $plugin_info['strings'][$plugin_type];
723 $section = array();
725 foreach ($plugins as $plugin) {
726 $link = $plugin->link->out(false);
727 $section[$link] = $plugin->string;
728 $count++;
729 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
730 $active = $link;
734 if ($section) {
735 $menu[] = array($sectionname=>$section);
739 // finally print/return the popup form
740 if ($count > 1) {
741 $select = new url_select($menu, $active, null, 'choosepluginreport');
742 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
743 if ($return) {
744 return $OUTPUT->render($select);
745 } else {
746 echo $OUTPUT->render($select);
748 } else {
749 // only one option - no plugin selector needed
750 return '';
755 * Print grading plugin selection tab-based navigation.
757 * @param string $active_type type of plugin on current page - import, export, report or edit
758 * @param string $active_plugin active plugin type - grader, user, cvs, ...
759 * @param array $plugin_info Array of plugins
760 * @param boolean $return return as string
762 * @return nothing or string if $return true
764 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
765 global $CFG, $COURSE;
767 if (!isset($currenttab)) { //TODO: this is weird
768 $currenttab = '';
771 $tabs = array();
772 $top_row = array();
773 $bottom_row = array();
774 $inactive = array($active_plugin);
775 $activated = array($active_type);
777 $count = 0;
778 $active = '';
780 foreach ($plugin_info as $plugin_type => $plugins) {
781 if ($plugin_type == 'strings') {
782 continue;
785 // If $plugins is actually the definition of a child-less parent link:
786 if (!empty($plugins->id)) {
787 $string = $plugins->string;
788 if (!empty($plugin_info[$active_type]->parent)) {
789 $string = $plugin_info[$active_type]->parent->string;
792 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
793 continue;
796 $first_plugin = reset($plugins);
797 $url = $first_plugin->link;
799 if ($plugin_type == 'report') {
800 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
803 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
805 if ($active_type == $plugin_type) {
806 foreach ($plugins as $plugin) {
807 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
808 if ($plugin->id == $active_plugin) {
809 $inactive = array($plugin->id);
815 $tabs[] = $top_row;
816 $tabs[] = $bottom_row;
818 if ($return) {
819 return print_tabs($tabs, $active_plugin, $inactive, $activated, true);
820 } else {
821 print_tabs($tabs, $active_plugin, $inactive, $activated);
826 * grade_get_plugin_info
828 * @param int $courseid The course id
829 * @param string $active_type type of plugin on current page - import, export, report or edit
830 * @param string $active_plugin active plugin type - grader, user, cvs, ...
832 * @return array
834 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
835 global $CFG, $SITE;
837 $context = context_course::instance($courseid);
839 $plugin_info = array();
840 $count = 0;
841 $active = '';
842 $url_prefix = $CFG->wwwroot . '/grade/';
844 // Language strings
845 $plugin_info['strings'] = grade_helper::get_plugin_strings();
847 if ($reports = grade_helper::get_plugins_reports($courseid)) {
848 $plugin_info['report'] = $reports;
851 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
852 $plugin_info['settings'] = $settings;
855 if ($scale = grade_helper::get_info_scales($courseid)) {
856 $plugin_info['scale'] = array('view'=>$scale);
859 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
860 $plugin_info['outcome'] = $outcomes;
863 if ($letters = grade_helper::get_info_letters($courseid)) {
864 $plugin_info['letter'] = $letters;
867 if ($imports = grade_helper::get_plugins_import($courseid)) {
868 $plugin_info['import'] = $imports;
871 if ($exports = grade_helper::get_plugins_export($courseid)) {
872 $plugin_info['export'] = $exports;
875 foreach ($plugin_info as $plugin_type => $plugins) {
876 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
877 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
878 break;
880 foreach ($plugins as $plugin) {
881 if (is_a($plugin, 'grade_plugin_info')) {
882 if ($active_plugin == $plugin->id) {
883 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
889 return $plugin_info;
893 * A simple class containing info about grade plugins.
894 * Can be subclassed for special rules
896 * @package core_grades
897 * @copyright 2009 Nicolas Connault
898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
900 class grade_plugin_info {
902 * A unique id for this plugin
904 * @var mixed
906 public $id;
908 * A URL to access this plugin
910 * @var mixed
912 public $link;
914 * The name of this plugin
916 * @var mixed
918 public $string;
920 * Another grade_plugin_info object, parent of the current one
922 * @var mixed
924 public $parent;
927 * Constructor
929 * @param int $id A unique id for this plugin
930 * @param string $link A URL to access this plugin
931 * @param string $string The name of this plugin
932 * @param object $parent Another grade_plugin_info object, parent of the current one
934 * @return void
936 public function __construct($id, $link, $string, $parent=null) {
937 $this->id = $id;
938 $this->link = $link;
939 $this->string = $string;
940 $this->parent = $parent;
945 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
946 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
947 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
948 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
949 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
951 * @param int $courseid Course id
952 * @param string $active_type The type of the current page (report, settings,
953 * import, export, scales, outcomes, letters)
954 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
955 * @param string $heading The heading of the page. Tries to guess if none is given
956 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
957 * @param string $bodytags Additional attributes that will be added to the <body> tag
958 * @param string $buttons Additional buttons to display on the page
959 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
960 * @param string $headerhelpidentifier The help string identifier if required.
961 * @param string $headerhelpcomponent The component for the help string.
962 * @param stdClass $user The user object for use with the user context header.
964 * @return string HTML code or nothing if $return == false
966 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
967 $heading = false, $return=false,
968 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null,
969 $user = null) {
970 global $CFG, $OUTPUT, $PAGE;
972 if ($active_type === 'preferences') {
973 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
974 $active_type = 'settings';
977 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
979 // Determine the string of the active plugin
980 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
981 $stractive_type = $plugin_info['strings'][$active_type];
983 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
984 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
985 } else {
986 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
989 if ($active_type == 'report') {
990 $PAGE->set_pagelayout('report');
991 } else {
992 $PAGE->set_pagelayout('admin');
994 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
995 $PAGE->set_heading($title);
996 if ($buttons instanceof single_button) {
997 $buttons = $OUTPUT->render($buttons);
999 $PAGE->set_button($buttons);
1000 if ($courseid != SITEID) {
1001 grade_extend_settings($plugin_info, $courseid);
1004 $returnval = $OUTPUT->header();
1006 if (!$return) {
1007 echo $returnval;
1010 // Guess heading if not given explicitly
1011 if (!$heading) {
1012 $heading = $stractive_plugin;
1015 if ($shownavigation) {
1016 $navselector = null;
1017 if ($courseid != SITEID &&
1018 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
1019 // It's absolutely essential that this grade plugin selector is shown after the user header. Just ask Fred.
1020 $navselector = print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, true);
1021 if ($return) {
1022 $returnval .= $navselector;
1023 } else if (!isset($user)) {
1024 echo $navselector;
1028 $output = '';
1029 // Add a help dialogue box if provided.
1030 if (isset($headerhelpidentifier)) {
1031 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
1032 } else {
1033 if (isset($user)) {
1034 $output = $OUTPUT->context_header(
1035 array(
1036 'heading' => fullname($user),
1037 'user' => $user,
1038 'usercontext' => context_user::instance($user->id)
1039 ), 2
1040 ) . $navselector;
1041 } else {
1042 $output = $OUTPUT->heading($heading);
1046 if ($return) {
1047 $returnval .= $output;
1048 } else {
1049 echo $output;
1052 if ($courseid != SITEID &&
1053 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
1054 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
1058 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
1059 context_course::instance($courseid),
1060 $PAGE->url,
1061 $return);
1063 if ($return) {
1064 return $returnval;
1069 * Utility class used for return tracking when using edit and other forms in grade plugins
1071 * @package core_grades
1072 * @copyright 2009 Nicolas Connault
1073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1075 class grade_plugin_return {
1076 public $type;
1077 public $plugin;
1078 public $courseid;
1079 public $userid;
1080 public $page;
1083 * Constructor
1085 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
1087 public function grade_plugin_return($params = null) {
1088 if (empty($params)) {
1089 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1090 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1091 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1092 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1093 $this->page = optional_param('gpr_page', null, PARAM_INT);
1095 } else {
1096 foreach ($params as $key=>$value) {
1097 if (property_exists($this, $key)) {
1098 $this->$key = $value;
1105 * Returns return parameters as options array suitable for buttons.
1106 * @return array options
1108 public function get_options() {
1109 if (empty($this->type)) {
1110 return array();
1113 $params = array();
1115 if (!empty($this->plugin)) {
1116 $params['plugin'] = $this->plugin;
1119 if (!empty($this->courseid)) {
1120 $params['id'] = $this->courseid;
1123 if (!empty($this->userid)) {
1124 $params['userid'] = $this->userid;
1127 if (!empty($this->page)) {
1128 $params['page'] = $this->page;
1131 return $params;
1135 * Returns return url
1137 * @param string $default default url when params not set
1138 * @param array $extras Extra URL parameters
1140 * @return string url
1142 public function get_return_url($default, $extras=null) {
1143 global $CFG;
1145 if (empty($this->type) or empty($this->plugin)) {
1146 return $default;
1149 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1150 $glue = '?';
1152 if (!empty($this->courseid)) {
1153 $url .= $glue.'id='.$this->courseid;
1154 $glue = '&amp;';
1157 if (!empty($this->userid)) {
1158 $url .= $glue.'userid='.$this->userid;
1159 $glue = '&amp;';
1162 if (!empty($this->page)) {
1163 $url .= $glue.'page='.$this->page;
1164 $glue = '&amp;';
1167 if (!empty($extras)) {
1168 foreach ($extras as $key=>$value) {
1169 $url .= $glue.$key.'='.$value;
1170 $glue = '&amp;';
1174 return $url;
1178 * Returns string with hidden return tracking form elements.
1179 * @return string
1181 public function get_form_fields() {
1182 if (empty($this->type)) {
1183 return '';
1186 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1188 if (!empty($this->plugin)) {
1189 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1192 if (!empty($this->courseid)) {
1193 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1196 if (!empty($this->userid)) {
1197 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1200 if (!empty($this->page)) {
1201 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1206 * Add hidden elements into mform
1208 * @param object &$mform moodle form object
1210 * @return void
1212 public function add_mform_elements(&$mform) {
1213 if (empty($this->type)) {
1214 return;
1217 $mform->addElement('hidden', 'gpr_type', $this->type);
1218 $mform->setType('gpr_type', PARAM_SAFEDIR);
1220 if (!empty($this->plugin)) {
1221 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1222 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1225 if (!empty($this->courseid)) {
1226 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1227 $mform->setType('gpr_courseid', PARAM_INT);
1230 if (!empty($this->userid)) {
1231 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1232 $mform->setType('gpr_userid', PARAM_INT);
1235 if (!empty($this->page)) {
1236 $mform->addElement('hidden', 'gpr_page', $this->page);
1237 $mform->setType('gpr_page', PARAM_INT);
1242 * Add return tracking params into url
1244 * @param moodle_url $url A URL
1246 * @return string $url with return tracking params
1248 public function add_url_params(moodle_url $url) {
1249 if (empty($this->type)) {
1250 return $url;
1253 $url->param('gpr_type', $this->type);
1255 if (!empty($this->plugin)) {
1256 $url->param('gpr_plugin', $this->plugin);
1259 if (!empty($this->courseid)) {
1260 $url->param('gpr_courseid' ,$this->courseid);
1263 if (!empty($this->userid)) {
1264 $url->param('gpr_userid', $this->userid);
1267 if (!empty($this->page)) {
1268 $url->param('gpr_page', $this->page);
1271 return $url;
1276 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1278 * @param string $path The path of the calling script (using __FILE__?)
1279 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1280 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1281 * an array of keys and values (e.g courseid => $courseid, itemid...)
1283 * @return string
1285 function grade_build_nav($path, $pagename=null, $id=null) {
1286 global $CFG, $COURSE, $PAGE;
1288 $strgrades = get_string('grades', 'grades');
1290 // Parse the path and build navlinks from its elements
1291 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1292 $path = substr($path, $dirroot_length);
1293 $path = str_replace('\\', '/', $path);
1295 $path_elements = explode('/', $path);
1297 $path_elements_count = count($path_elements);
1299 // First link is always 'grade'
1300 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1302 $link = null;
1303 $numberofelements = 3;
1305 // Prepare URL params string
1306 $linkparams = array();
1307 if (!is_null($id)) {
1308 if (is_array($id)) {
1309 foreach ($id as $idkey => $idvalue) {
1310 $linkparams[$idkey] = $idvalue;
1312 } else {
1313 $linkparams['id'] = $id;
1317 $navlink4 = null;
1319 // Remove file extensions from filenames
1320 foreach ($path_elements as $key => $filename) {
1321 $path_elements[$key] = str_replace('.php', '', $filename);
1324 // Second level links
1325 switch ($path_elements[1]) {
1326 case 'edit': // No link
1327 if ($path_elements[3] != 'index.php') {
1328 $numberofelements = 4;
1330 break;
1331 case 'import': // No link
1332 break;
1333 case 'export': // No link
1334 break;
1335 case 'report':
1336 // $id is required for this link. Do not print it if $id isn't given
1337 if (!is_null($id)) {
1338 $link = new moodle_url('/grade/report/index.php', $linkparams);
1341 if ($path_elements[2] == 'grader') {
1342 $numberofelements = 4;
1344 break;
1346 default:
1347 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1348 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1349 " as the second path element after 'grade'.");
1350 return false;
1352 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1354 // Third level links
1355 if (empty($pagename)) {
1356 $pagename = get_string($path_elements[2], 'grades');
1359 switch ($numberofelements) {
1360 case 3:
1361 $PAGE->navbar->add($pagename, $link);
1362 break;
1363 case 4:
1364 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1365 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1367 $PAGE->navbar->add($pagename);
1368 break;
1371 return '';
1375 * General structure representing grade items in course
1377 * @package core_grades
1378 * @copyright 2009 Nicolas Connault
1379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1381 class grade_structure {
1382 public $context;
1384 public $courseid;
1387 * Reference to modinfo for current course (for performance, to save
1388 * retrieving it from courseid every time). Not actually set except for
1389 * the grade_tree type.
1390 * @var course_modinfo
1392 public $modinfo;
1395 * 1D array of grade items only
1397 public $items;
1400 * Returns icon of element
1402 * @param array &$element An array representing an element in the grade_tree
1403 * @param bool $spacerifnone return spacer if no icon found
1405 * @return string icon or spacer
1407 public function get_element_icon(&$element, $spacerifnone=false) {
1408 global $CFG, $OUTPUT;
1409 require_once $CFG->libdir.'/filelib.php';
1411 $outputstr = '';
1413 // Object holding pix_icon information before instantiation.
1414 $icon = new stdClass();
1415 $icon->attributes = array(
1416 'class' => 'icon itemicon'
1418 $icon->component = 'moodle';
1420 $none = true;
1421 switch ($element['type']) {
1422 case 'item':
1423 case 'courseitem':
1424 case 'categoryitem':
1425 $none = false;
1427 $is_course = $element['object']->is_course_item();
1428 $is_category = $element['object']->is_category_item();
1429 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1430 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1431 $is_outcome = !empty($element['object']->outcomeid);
1433 if ($element['object']->is_calculated()) {
1434 $icon->pix = 'i/calc';
1435 $icon->title = s(get_string('calculatedgrade', 'grades'));
1437 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1438 if ($category = $element['object']->get_item_category()) {
1439 $aggrstrings = grade_helper::get_aggregation_strings();
1440 $stragg = $aggrstrings[$category->aggregation];
1442 $icon->pix = 'i/calc';
1443 $icon->title = s($stragg);
1445 switch ($category->aggregation) {
1446 case GRADE_AGGREGATE_MEAN:
1447 case GRADE_AGGREGATE_MEDIAN:
1448 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1449 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1450 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1451 $icon->pix = 'i/agg_mean';
1452 break;
1453 case GRADE_AGGREGATE_SUM:
1454 $icon->pix = 'i/agg_sum';
1455 break;
1459 } else if ($element['object']->itemtype == 'mod') {
1460 // Prevent outcomes displaying the same icon as the activity they are attached to.
1461 if ($is_outcome) {
1462 $icon->pix = 'i/outcomes';
1463 $icon->title = s(get_string('outcome', 'grades'));
1464 } else {
1465 $icon->pix = 'icon';
1466 $icon->component = $element['object']->itemmodule;
1467 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1469 } else if ($element['object']->itemtype == 'manual') {
1470 if ($element['object']->is_outcome_item()) {
1471 $icon->pix = 'i/outcomes';
1472 $icon->title = s(get_string('outcome', 'grades'));
1473 } else {
1474 $icon->pix = 'i/manual_item';
1475 $icon->title = s(get_string('manualitem', 'grades'));
1478 break;
1480 case 'category':
1481 $none = false;
1482 $icon->pix = 'i/folder';
1483 $icon->title = s(get_string('category', 'grades'));
1484 break;
1487 if ($none) {
1488 if ($spacerifnone) {
1489 $outputstr = $OUTPUT->spacer() . ' ';
1491 } else {
1492 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1495 return $outputstr;
1499 * Returns name of element optionally with icon and link
1501 * @param array &$element An array representing an element in the grade_tree
1502 * @param bool $withlink Whether or not this header has a link
1503 * @param bool $icon Whether or not to display an icon with this header
1504 * @param bool $spacerifnone return spacer if no icon found
1505 * @param bool $withdescription Show description if defined by this item.
1506 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1507 * instead of "Category total" or "Course total"
1509 * @return string header
1511 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1512 $withdescription = false, $fulltotal = false) {
1513 $header = '';
1515 if ($icon) {
1516 $header .= $this->get_element_icon($element, $spacerifnone);
1519 $header .= $element['object']->get_name($fulltotal);
1521 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1522 $element['type'] != 'courseitem') {
1523 return $header;
1526 if ($withlink && $url = $this->get_activity_link($element)) {
1527 $a = new stdClass();
1528 $a->name = get_string('modulename', $element['object']->itemmodule);
1529 $title = get_string('linktoactivity', 'grades', $a);
1531 $header = html_writer::link($url, $header, array('title' => $title));
1532 } else {
1533 $header = html_writer::span($header);
1536 if ($withdescription) {
1537 $desc = $element['object']->get_description();
1538 if (!empty($desc)) {
1539 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1543 return $header;
1546 private function get_activity_link($element) {
1547 global $CFG;
1548 /** @var array static cache of the grade.php file existence flags */
1549 static $hasgradephp = array();
1551 $itemtype = $element['object']->itemtype;
1552 $itemmodule = $element['object']->itemmodule;
1553 $iteminstance = $element['object']->iteminstance;
1554 $itemnumber = $element['object']->itemnumber;
1556 // Links only for module items that have valid instance, module and are
1557 // called from grade_tree with valid modinfo
1558 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1559 return null;
1562 // Get $cm efficiently and with visibility information using modinfo
1563 $instances = $this->modinfo->get_instances();
1564 if (empty($instances[$itemmodule][$iteminstance])) {
1565 return null;
1567 $cm = $instances[$itemmodule][$iteminstance];
1569 // Do not add link if activity is not visible to the current user
1570 if (!$cm->uservisible) {
1571 return null;
1574 if (!array_key_exists($itemmodule, $hasgradephp)) {
1575 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1576 $hasgradephp[$itemmodule] = true;
1577 } else {
1578 $hasgradephp[$itemmodule] = false;
1582 // If module has grade.php, link to that, otherwise view.php
1583 if ($hasgradephp[$itemmodule]) {
1584 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1585 if (isset($element['userid'])) {
1586 $args['userid'] = $element['userid'];
1588 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1589 } else {
1590 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1595 * Returns URL of a page that is supposed to contain detailed grade analysis
1597 * At the moment, only activity modules are supported. The method generates link
1598 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1599 * gradeid and userid. If the grade.php does not exist, null is returned.
1601 * @return moodle_url|null URL or null if unable to construct it
1603 public function get_grade_analysis_url(grade_grade $grade) {
1604 global $CFG;
1605 /** @var array static cache of the grade.php file existence flags */
1606 static $hasgradephp = array();
1608 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1609 throw new coding_exception('Passed grade without the associated grade item');
1611 $item = $grade->grade_item;
1613 if (!$item->is_external_item()) {
1614 // at the moment, only activity modules are supported
1615 return null;
1617 if ($item->itemtype !== 'mod') {
1618 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1620 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1621 return null;
1624 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1625 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1626 $hasgradephp[$item->itemmodule] = true;
1627 } else {
1628 $hasgradephp[$item->itemmodule] = false;
1632 if (!$hasgradephp[$item->itemmodule]) {
1633 return null;
1636 $instances = $this->modinfo->get_instances();
1637 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1638 return null;
1640 $cm = $instances[$item->itemmodule][$item->iteminstance];
1641 if (!$cm->uservisible) {
1642 return null;
1645 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1646 'id' => $cm->id,
1647 'itemid' => $item->id,
1648 'itemnumber' => $item->itemnumber,
1649 'gradeid' => $grade->id,
1650 'userid' => $grade->userid,
1653 return $url;
1657 * Returns an action icon leading to the grade analysis page
1659 * @param grade_grade $grade
1660 * @return string
1662 public function get_grade_analysis_icon(grade_grade $grade) {
1663 global $OUTPUT;
1665 $url = $this->get_grade_analysis_url($grade);
1666 if (is_null($url)) {
1667 return '';
1670 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1671 get_string('gradeanalysis', 'core_grades')));
1675 * Returns the grade eid - the grade may not exist yet.
1677 * @param grade_grade $grade_grade A grade_grade object
1679 * @return string eid
1681 public function get_grade_eid($grade_grade) {
1682 if (empty($grade_grade->id)) {
1683 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1684 } else {
1685 return 'g'.$grade_grade->id;
1690 * Returns the grade_item eid
1691 * @param grade_item $grade_item A grade_item object
1692 * @return string eid
1694 public function get_item_eid($grade_item) {
1695 return 'ig'.$grade_item->id;
1699 * Given a grade_tree element, returns an array of parameters
1700 * used to build an icon for that element.
1702 * @param array $element An array representing an element in the grade_tree
1704 * @return array
1706 public function get_params_for_iconstr($element) {
1707 $strparams = new stdClass();
1708 $strparams->category = '';
1709 $strparams->itemname = '';
1710 $strparams->itemmodule = '';
1712 if (!method_exists($element['object'], 'get_name')) {
1713 return $strparams;
1716 $strparams->itemname = html_to_text($element['object']->get_name());
1718 // If element name is categorytotal, get the name of the parent category
1719 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1720 $parent = $element['object']->get_parent_category();
1721 $strparams->category = $parent->get_name() . ' ';
1722 } else {
1723 $strparams->category = '';
1726 $strparams->itemmodule = null;
1727 if (isset($element['object']->itemmodule)) {
1728 $strparams->itemmodule = $element['object']->itemmodule;
1730 return $strparams;
1734 * Return a reset icon for the given element.
1736 * @param array $element An array representing an element in the grade_tree
1737 * @param object $gpr A grade_plugin_return object
1738 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1739 * @return string|action_menu_link
1741 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1742 global $CFG, $OUTPUT;
1744 // Limit to category items set to use the natural weights aggregation method, and users
1745 // with the capability to manage grades.
1746 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1747 !has_capability('moodle/grade:manage', $this->context)) {
1748 return $returnactionmenulink ? null : '';
1751 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1752 $url = new moodle_url('/grade/edit/tree/action.php', array(
1753 'id' => $this->courseid,
1754 'action' => 'resetweights',
1755 'eid' => $element['eid'],
1756 'sesskey' => sesskey(),
1759 if ($returnactionmenulink) {
1760 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1761 get_string('resetweightsshort', 'grades'));
1762 } else {
1763 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1768 * Return edit icon for give element
1770 * @param array $element An array representing an element in the grade_tree
1771 * @param object $gpr A grade_plugin_return object
1772 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1773 * @return string|action_menu_link
1775 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1776 global $CFG, $OUTPUT;
1778 if (!has_capability('moodle/grade:manage', $this->context)) {
1779 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1780 // oki - let them override grade
1781 } else {
1782 return $returnactionmenulink ? null : '';
1786 static $strfeedback = null;
1787 static $streditgrade = null;
1788 if (is_null($streditgrade)) {
1789 $streditgrade = get_string('editgrade', 'grades');
1790 $strfeedback = get_string('feedback');
1793 $strparams = $this->get_params_for_iconstr($element);
1795 $object = $element['object'];
1797 switch ($element['type']) {
1798 case 'item':
1799 case 'categoryitem':
1800 case 'courseitem':
1801 $stredit = get_string('editverbose', 'grades', $strparams);
1802 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1803 $url = new moodle_url('/grade/edit/tree/item.php',
1804 array('courseid' => $this->courseid, 'id' => $object->id));
1805 } else {
1806 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1807 array('courseid' => $this->courseid, 'id' => $object->id));
1809 break;
1811 case 'category':
1812 $stredit = get_string('editverbose', 'grades', $strparams);
1813 $url = new moodle_url('/grade/edit/tree/category.php',
1814 array('courseid' => $this->courseid, 'id' => $object->id));
1815 break;
1817 case 'grade':
1818 $stredit = $streditgrade;
1819 if (empty($object->id)) {
1820 $url = new moodle_url('/grade/edit/tree/grade.php',
1821 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1822 } else {
1823 $url = new moodle_url('/grade/edit/tree/grade.php',
1824 array('courseid' => $this->courseid, 'id' => $object->id));
1826 if (!empty($object->feedback)) {
1827 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1829 break;
1831 default:
1832 $url = null;
1835 if ($url) {
1836 if ($returnactionmenulink) {
1837 return new action_menu_link_secondary($gpr->add_url_params($url),
1838 new pix_icon('t/edit', $stredit),
1839 get_string('editsettings'));
1840 } else {
1841 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1844 } else {
1845 return $returnactionmenulink ? null : '';
1850 * Return hiding icon for give element
1852 * @param array $element An array representing an element in the grade_tree
1853 * @param object $gpr A grade_plugin_return object
1854 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1855 * @return string|action_menu_link
1857 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1858 global $CFG, $OUTPUT;
1860 if (!$element['object']->can_control_visibility()) {
1861 return $returnactionmenulink ? null : '';
1864 if (!has_capability('moodle/grade:manage', $this->context) and
1865 !has_capability('moodle/grade:hide', $this->context)) {
1866 return $returnactionmenulink ? null : '';
1869 $strparams = $this->get_params_for_iconstr($element);
1870 $strshow = get_string('showverbose', 'grades', $strparams);
1871 $strhide = get_string('hideverbose', 'grades', $strparams);
1873 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1874 $url = $gpr->add_url_params($url);
1876 if ($element['object']->is_hidden()) {
1877 $type = 'show';
1878 $tooltip = $strshow;
1880 // Change the icon and add a tooltip showing the date
1881 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1882 $type = 'hiddenuntil';
1883 $tooltip = get_string('hiddenuntildate', 'grades',
1884 userdate($element['object']->get_hidden()));
1887 $url->param('action', 'show');
1889 if ($returnactionmenulink) {
1890 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1891 } else {
1892 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1895 } else {
1896 $url->param('action', 'hide');
1897 if ($returnactionmenulink) {
1898 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1899 } else {
1900 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1904 return $hideicon;
1908 * Return locking icon for given element
1910 * @param array $element An array representing an element in the grade_tree
1911 * @param object $gpr A grade_plugin_return object
1913 * @return string
1915 public function get_locking_icon($element, $gpr) {
1916 global $CFG, $OUTPUT;
1918 $strparams = $this->get_params_for_iconstr($element);
1919 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1920 $strlock = get_string('lockverbose', 'grades', $strparams);
1922 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1923 $url = $gpr->add_url_params($url);
1925 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1926 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1927 $strparamobj = new stdClass();
1928 $strparamobj->itemname = $element['object']->grade_item->itemname;
1929 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1931 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1932 array('class' => 'action-icon'));
1934 } else if ($element['object']->is_locked()) {
1935 $type = 'unlock';
1936 $tooltip = $strunlock;
1938 // Change the icon and add a tooltip showing the date
1939 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1940 $type = 'locktime';
1941 $tooltip = get_string('locktimedate', 'grades',
1942 userdate($element['object']->get_locktime()));
1945 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1946 $action = '';
1947 } else {
1948 $url->param('action', 'unlock');
1949 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1952 } else {
1953 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1954 $action = '';
1955 } else {
1956 $url->param('action', 'lock');
1957 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1961 return $action;
1965 * Return calculation icon for given element
1967 * @param array $element An array representing an element in the grade_tree
1968 * @param object $gpr A grade_plugin_return object
1969 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1970 * @return string|action_menu_link
1972 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1973 global $CFG, $OUTPUT;
1974 if (!has_capability('moodle/grade:manage', $this->context)) {
1975 return $returnactionmenulink ? null : '';
1978 $type = $element['type'];
1979 $object = $element['object'];
1981 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1982 $strparams = $this->get_params_for_iconstr($element);
1983 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1985 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1986 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1988 // show calculation icon only when calculation possible
1989 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1990 if ($object->is_calculated()) {
1991 $icon = 't/calc';
1992 } else {
1993 $icon = 't/calc_off';
1996 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1997 $url = $gpr->add_url_params($url);
1998 if ($returnactionmenulink) {
1999 return new action_menu_link_secondary($url,
2000 new pix_icon($icon, $streditcalculation),
2001 get_string('editcalculation', 'grades'));
2002 } else {
2003 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2008 return $returnactionmenulink ? null : '';
2013 * Flat structure similar to grade tree.
2015 * @uses grade_structure
2016 * @package core_grades
2017 * @copyright 2009 Nicolas Connault
2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2020 class grade_seq extends grade_structure {
2023 * 1D array of elements
2025 public $elements;
2028 * Constructor, retrieves and stores array of all grade_category and grade_item
2029 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2031 * @param int $courseid The course id
2032 * @param bool $category_grade_last category grade item is the last child
2033 * @param bool $nooutcomes Whether or not outcomes should be included
2035 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2036 global $USER, $CFG;
2038 $this->courseid = $courseid;
2039 $this->context = context_course::instance($courseid);
2041 // get course grade tree
2042 $top_element = grade_category::fetch_course_tree($courseid, true);
2044 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2046 foreach ($this->elements as $key=>$unused) {
2047 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2052 * Static recursive helper - makes the grade_item for category the last children
2054 * @param array &$element The seed of the recursion
2055 * @param bool $category_grade_last category grade item is the last child
2056 * @param bool $nooutcomes Whether or not outcomes should be included
2058 * @return array
2060 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2061 if (empty($element['children'])) {
2062 return array();
2064 $children = array();
2066 foreach ($element['children'] as $sortorder=>$unused) {
2067 if ($nooutcomes and $element['type'] != 'category' and
2068 $element['children'][$sortorder]['object']->is_outcome_item()) {
2069 continue;
2071 $children[] = $element['children'][$sortorder];
2073 unset($element['children']);
2075 if ($category_grade_last and count($children) > 1) {
2076 $cat_item = array_shift($children);
2077 array_push($children, $cat_item);
2080 $result = array();
2081 foreach ($children as $child) {
2082 if ($child['type'] == 'category') {
2083 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2084 } else {
2085 $child['eid'] = 'i'.$child['object']->id;
2086 $result[$child['object']->id] = $child;
2090 return $result;
2094 * Parses the array in search of a given eid and returns a element object with
2095 * information about the element it has found.
2097 * @param int $eid Gradetree Element ID
2099 * @return object element
2101 public function locate_element($eid) {
2102 // it is a grade - construct a new object
2103 if (strpos($eid, 'n') === 0) {
2104 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2105 return null;
2108 $itemid = $matches[1];
2109 $userid = $matches[2];
2111 //extra security check - the grade item must be in this tree
2112 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2113 return null;
2116 // $gradea->id may be null - means does not exist yet
2117 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2119 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2120 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2122 } else if (strpos($eid, 'g') === 0) {
2123 $id = (int) substr($eid, 1);
2124 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2125 return null;
2127 //extra security check - the grade item must be in this tree
2128 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2129 return null;
2131 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2132 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2135 // it is a category or item
2136 foreach ($this->elements as $element) {
2137 if ($element['eid'] == $eid) {
2138 return $element;
2142 return null;
2147 * This class represents a complete tree of categories, grade_items and final grades,
2148 * organises as an array primarily, but which can also be converted to other formats.
2149 * It has simple method calls with complex implementations, allowing for easy insertion,
2150 * deletion and moving of items and categories within the tree.
2152 * @uses grade_structure
2153 * @package core_grades
2154 * @copyright 2009 Nicolas Connault
2155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2157 class grade_tree extends grade_structure {
2160 * The basic representation of the tree as a hierarchical, 3-tiered array.
2161 * @var object $top_element
2163 public $top_element;
2166 * 2D array of grade items and categories
2167 * @var array $levels
2169 public $levels;
2172 * Grade items
2173 * @var array $items
2175 public $items;
2178 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2179 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2181 * @param int $courseid The Course ID
2182 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2183 * @param bool $category_grade_last category grade item is the last child
2184 * @param array $collapsed array of collapsed categories
2185 * @param bool $nooutcomes Whether or not outcomes should be included
2187 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2188 $collapsed=null, $nooutcomes=false) {
2189 global $USER, $CFG, $COURSE, $DB;
2191 $this->courseid = $courseid;
2192 $this->levels = array();
2193 $this->context = context_course::instance($courseid);
2195 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2196 $course = $COURSE;
2197 } else {
2198 $course = $DB->get_record('course', array('id' => $this->courseid));
2200 $this->modinfo = get_fast_modinfo($course);
2202 // get course grade tree
2203 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2205 // collapse the categories if requested
2206 if (!empty($collapsed)) {
2207 grade_tree::category_collapse($this->top_element, $collapsed);
2210 // no otucomes if requested
2211 if (!empty($nooutcomes)) {
2212 grade_tree::no_outcomes($this->top_element);
2215 // move category item to last position in category
2216 if ($category_grade_last) {
2217 grade_tree::category_grade_last($this->top_element);
2220 if ($fillers) {
2221 // inject fake categories == fillers
2222 grade_tree::inject_fillers($this->top_element, 0);
2223 // add colspans to categories and fillers
2224 grade_tree::inject_colspans($this->top_element);
2227 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2232 * Static recursive helper - removes items from collapsed categories
2234 * @param array &$element The seed of the recursion
2235 * @param array $collapsed array of collapsed categories
2237 * @return void
2239 public function category_collapse(&$element, $collapsed) {
2240 if ($element['type'] != 'category') {
2241 return;
2243 if (empty($element['children']) or count($element['children']) < 2) {
2244 return;
2247 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2248 $category_item = reset($element['children']); //keep only category item
2249 $element['children'] = array(key($element['children'])=>$category_item);
2251 } else {
2252 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2253 reset($element['children']);
2254 $first_key = key($element['children']);
2255 unset($element['children'][$first_key]);
2257 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2258 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2264 * Static recursive helper - removes all outcomes
2266 * @param array &$element The seed of the recursion
2268 * @return void
2270 public function no_outcomes(&$element) {
2271 if ($element['type'] != 'category') {
2272 return;
2274 foreach ($element['children'] as $sortorder=>$child) {
2275 if ($element['children'][$sortorder]['type'] == 'item'
2276 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2277 unset($element['children'][$sortorder]);
2279 } else if ($element['children'][$sortorder]['type'] == 'category') {
2280 grade_tree::no_outcomes($element['children'][$sortorder]);
2286 * Static recursive helper - makes the grade_item for category the last children
2288 * @param array &$element The seed of the recursion
2290 * @return void
2292 public function category_grade_last(&$element) {
2293 if (empty($element['children'])) {
2294 return;
2296 if (count($element['children']) < 2) {
2297 return;
2299 $first_item = reset($element['children']);
2300 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2301 // the category item might have been already removed
2302 $order = key($element['children']);
2303 unset($element['children'][$order]);
2304 $element['children'][$order] =& $first_item;
2306 foreach ($element['children'] as $sortorder => $child) {
2307 grade_tree::category_grade_last($element['children'][$sortorder]);
2312 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2314 * @param array &$levels The levels of the grade tree through which to recurse
2315 * @param array &$element The seed of the recursion
2316 * @param int $depth How deep are we?
2317 * @return void
2319 public function fill_levels(&$levels, &$element, $depth) {
2320 if (!array_key_exists($depth, $levels)) {
2321 $levels[$depth] = array();
2324 // prepare unique identifier
2325 if ($element['type'] == 'category') {
2326 $element['eid'] = 'cg'.$element['object']->id;
2327 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2328 $element['eid'] = 'ig'.$element['object']->id;
2329 $this->items[$element['object']->id] =& $element['object'];
2332 $levels[$depth][] =& $element;
2333 $depth++;
2334 if (empty($element['children'])) {
2335 return;
2337 $prev = 0;
2338 foreach ($element['children'] as $sortorder=>$child) {
2339 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2340 $element['children'][$sortorder]['prev'] = $prev;
2341 $element['children'][$sortorder]['next'] = 0;
2342 if ($prev) {
2343 $element['children'][$prev]['next'] = $sortorder;
2345 $prev = $sortorder;
2350 * Static recursive helper - makes full tree (all leafes are at the same level)
2352 * @param array &$element The seed of the recursion
2353 * @param int $depth How deep are we?
2355 * @return int
2357 public function inject_fillers(&$element, $depth) {
2358 $depth++;
2360 if (empty($element['children'])) {
2361 return $depth;
2363 $chdepths = array();
2364 $chids = array_keys($element['children']);
2365 $last_child = end($chids);
2366 $first_child = reset($chids);
2368 foreach ($chids as $chid) {
2369 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2371 arsort($chdepths);
2373 $maxdepth = reset($chdepths);
2374 foreach ($chdepths as $chid=>$chd) {
2375 if ($chd == $maxdepth) {
2376 continue;
2378 for ($i=0; $i < $maxdepth-$chd; $i++) {
2379 if ($chid == $first_child) {
2380 $type = 'fillerfirst';
2381 } else if ($chid == $last_child) {
2382 $type = 'fillerlast';
2383 } else {
2384 $type = 'filler';
2386 $oldchild =& $element['children'][$chid];
2387 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2388 'eid'=>'', 'depth'=>$element['object']->depth,
2389 'children'=>array($oldchild));
2393 return $maxdepth;
2397 * Static recursive helper - add colspan information into categories
2399 * @param array &$element The seed of the recursion
2401 * @return int
2403 public function inject_colspans(&$element) {
2404 if (empty($element['children'])) {
2405 return 1;
2407 $count = 0;
2408 foreach ($element['children'] as $key=>$child) {
2409 $count += grade_tree::inject_colspans($element['children'][$key]);
2411 $element['colspan'] = $count;
2412 return $count;
2416 * Parses the array in search of a given eid and returns a element object with
2417 * information about the element it has found.
2418 * @param int $eid Gradetree Element ID
2419 * @return object element
2421 public function locate_element($eid) {
2422 // it is a grade - construct a new object
2423 if (strpos($eid, 'n') === 0) {
2424 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2425 return null;
2428 $itemid = $matches[1];
2429 $userid = $matches[2];
2431 //extra security check - the grade item must be in this tree
2432 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2433 return null;
2436 // $gradea->id may be null - means does not exist yet
2437 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2439 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2440 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2442 } else if (strpos($eid, 'g') === 0) {
2443 $id = (int) substr($eid, 1);
2444 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2445 return null;
2447 //extra security check - the grade item must be in this tree
2448 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2449 return null;
2451 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2452 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2455 // it is a category or item
2456 foreach ($this->levels as $row) {
2457 foreach ($row as $element) {
2458 if ($element['type'] == 'filler') {
2459 continue;
2461 if ($element['eid'] == $eid) {
2462 return $element;
2467 return null;
2471 * Returns a well-formed XML representation of the grade-tree using recursion.
2473 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2474 * @param string $tabs The control character to use for tabs
2476 * @return string $xml
2478 public function exporttoxml($root=null, $tabs="\t") {
2479 $xml = null;
2480 $first = false;
2481 if (is_null($root)) {
2482 $root = $this->top_element;
2483 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2484 $xml .= "<gradetree>\n";
2485 $first = true;
2488 $type = 'undefined';
2489 if (strpos($root['object']->table, 'grade_categories') !== false) {
2490 $type = 'category';
2491 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2492 $type = 'item';
2493 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2494 $type = 'outcome';
2497 $xml .= "$tabs<element type=\"$type\">\n";
2498 foreach ($root['object'] as $var => $value) {
2499 if (!is_object($value) && !is_array($value) && !empty($value)) {
2500 $xml .= "$tabs\t<$var>$value</$var>\n";
2504 if (!empty($root['children'])) {
2505 $xml .= "$tabs\t<children>\n";
2506 foreach ($root['children'] as $sortorder => $child) {
2507 $xml .= $this->exportToXML($child, $tabs."\t\t");
2509 $xml .= "$tabs\t</children>\n";
2512 $xml .= "$tabs</element>\n";
2514 if ($first) {
2515 $xml .= "</gradetree>";
2518 return $xml;
2522 * Returns a JSON representation of the grade-tree using recursion.
2524 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2525 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2527 * @return string
2529 public function exporttojson($root=null, $tabs="\t") {
2530 $json = null;
2531 $first = false;
2532 if (is_null($root)) {
2533 $root = $this->top_element;
2534 $first = true;
2537 $name = '';
2540 if (strpos($root['object']->table, 'grade_categories') !== false) {
2541 $name = $root['object']->fullname;
2542 if ($name == '?') {
2543 $name = $root['object']->get_name();
2545 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2546 $name = $root['object']->itemname;
2547 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2548 $name = $root['object']->itemname;
2551 $json .= "$tabs {\n";
2552 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2553 $json .= "$tabs\t \"name\": \"$name\",\n";
2555 foreach ($root['object'] as $var => $value) {
2556 if (!is_object($value) && !is_array($value) && !empty($value)) {
2557 $json .= "$tabs\t \"$var\": \"$value\",\n";
2561 $json = substr($json, 0, strrpos($json, ','));
2563 if (!empty($root['children'])) {
2564 $json .= ",\n$tabs\t\"children\": [\n";
2565 foreach ($root['children'] as $sortorder => $child) {
2566 $json .= $this->exportToJSON($child, $tabs."\t\t");
2568 $json = substr($json, 0, strrpos($json, ','));
2569 $json .= "\n$tabs\t]\n";
2572 if ($first) {
2573 $json .= "\n}";
2574 } else {
2575 $json .= "\n$tabs},\n";
2578 return $json;
2582 * Returns the array of levels
2584 * @return array
2586 public function get_levels() {
2587 return $this->levels;
2591 * Returns the array of grade items
2593 * @return array
2595 public function get_items() {
2596 return $this->items;
2600 * Returns a specific Grade Item
2602 * @param int $itemid The ID of the grade_item object
2604 * @return grade_item
2606 public function get_item($itemid) {
2607 if (array_key_exists($itemid, $this->items)) {
2608 return $this->items[$itemid];
2609 } else {
2610 return false;
2616 * Local shortcut function for creating an edit/delete button for a grade_* object.
2617 * @param string $type 'edit' or 'delete'
2618 * @param int $courseid The Course ID
2619 * @param grade_* $object The grade_* object
2620 * @return string html
2622 function grade_button($type, $courseid, $object) {
2623 global $CFG, $OUTPUT;
2624 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2625 $objectidstring = $matches[1] . 'id';
2626 } else {
2627 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2630 $strdelete = get_string('delete');
2631 $stredit = get_string('edit');
2633 if ($type == 'delete') {
2634 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2635 } else if ($type == 'edit') {
2636 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2639 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2644 * This method adds settings to the settings block for the grade system and its
2645 * plugins
2647 * @global moodle_page $PAGE
2649 function grade_extend_settings($plugininfo, $courseid) {
2650 global $PAGE;
2652 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2654 $strings = array_shift($plugininfo);
2656 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2657 foreach ($reports as $report) {
2658 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2662 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2663 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2664 foreach ($settings as $setting) {
2665 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2669 if ($imports = grade_helper::get_plugins_import($courseid)) {
2670 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2671 foreach ($imports as $import) {
2672 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2676 if ($exports = grade_helper::get_plugins_export($courseid)) {
2677 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2678 foreach ($exports as $export) {
2679 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2683 if ($letters = grade_helper::get_info_letters($courseid)) {
2684 $letters = array_shift($letters);
2685 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2688 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2689 $outcomes = array_shift($outcomes);
2690 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2693 if ($scales = grade_helper::get_info_scales($courseid)) {
2694 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2697 if ($gradenode->contains_active_node()) {
2698 // If the gradenode is active include the settings base node (gradeadministration) in
2699 // the navbar, typcially this is ignored.
2700 $PAGE->navbar->includesettingsbase = true;
2702 // If we can get the course admin node make sure it is closed by default
2703 // as in this case the gradenode will be opened
2704 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2705 $coursenode->make_inactive();
2706 $coursenode->forceopen = false;
2712 * Grade helper class
2714 * This class provides several helpful functions that work irrespective of any
2715 * current state.
2717 * @copyright 2010 Sam Hemelryk
2718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2720 abstract class grade_helper {
2722 * Cached manage settings info {@see get_info_settings}
2723 * @var grade_plugin_info|false
2725 protected static $managesetting = null;
2727 * Cached grade report plugins {@see get_plugins_reports}
2728 * @var array|false
2730 protected static $gradereports = null;
2732 * Cached grade report plugins preferences {@see get_info_scales}
2733 * @var array|false
2735 protected static $gradereportpreferences = null;
2737 * Cached scale info {@see get_info_scales}
2738 * @var grade_plugin_info|false
2740 protected static $scaleinfo = null;
2742 * Cached outcome info {@see get_info_outcomes}
2743 * @var grade_plugin_info|false
2745 protected static $outcomeinfo = null;
2747 * Cached leftter info {@see get_info_letters}
2748 * @var grade_plugin_info|false
2750 protected static $letterinfo = null;
2752 * Cached grade import plugins {@see get_plugins_import}
2753 * @var array|false
2755 protected static $importplugins = null;
2757 * Cached grade export plugins {@see get_plugins_export}
2758 * @var array|false
2760 protected static $exportplugins = null;
2762 * Cached grade plugin strings
2763 * @var array
2765 protected static $pluginstrings = null;
2767 * Cached grade aggregation strings
2768 * @var array
2770 protected static $aggregationstrings = null;
2773 * Gets strings commonly used by the describe plugins
2775 * report => get_string('view'),
2776 * scale => get_string('scales'),
2777 * outcome => get_string('outcomes', 'grades'),
2778 * letter => get_string('letters', 'grades'),
2779 * export => get_string('export', 'grades'),
2780 * import => get_string('import'),
2781 * settings => get_string('settings')
2783 * @return array
2785 public static function get_plugin_strings() {
2786 if (self::$pluginstrings === null) {
2787 self::$pluginstrings = array(
2788 'report' => get_string('view'),
2789 'scale' => get_string('scales'),
2790 'outcome' => get_string('outcomes', 'grades'),
2791 'letter' => get_string('letters', 'grades'),
2792 'export' => get_string('export', 'grades'),
2793 'import' => get_string('import'),
2794 'settings' => get_string('edittree', 'grades')
2797 return self::$pluginstrings;
2801 * Gets strings describing the available aggregation methods.
2803 * @return array
2805 public static function get_aggregation_strings() {
2806 if (self::$aggregationstrings === null) {
2807 self::$aggregationstrings = array(
2808 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2809 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2810 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2811 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2812 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2813 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2814 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2815 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2816 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2819 return self::$aggregationstrings;
2823 * Get grade_plugin_info object for managing settings if the user can
2825 * @param int $courseid
2826 * @return grade_plugin_info[]
2828 public static function get_info_manage_settings($courseid) {
2829 if (self::$managesetting !== null) {
2830 return self::$managesetting;
2832 $context = context_course::instance($courseid);
2833 self::$managesetting = array();
2834 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2835 self::$managesetting['gradebooksetup'] = new grade_plugin_info('setup',
2836 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2837 get_string('gradebooksetup', 'grades'));
2838 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2839 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2840 get_string('coursegradesettings', 'grades'));
2842 if (self::$gradereportpreferences === null) {
2843 self::get_plugins_reports($courseid);
2845 if (self::$gradereportpreferences) {
2846 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
2848 return self::$managesetting;
2851 * Returns an array of plugin reports as grade_plugin_info objects
2853 * @param int $courseid
2854 * @return array
2856 public static function get_plugins_reports($courseid) {
2857 global $SITE;
2859 if (self::$gradereports !== null) {
2860 return self::$gradereports;
2862 $context = context_course::instance($courseid);
2863 $gradereports = array();
2864 $gradepreferences = array();
2865 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2866 //some reports make no sense if we're not within a course
2867 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2868 continue;
2871 // Remove ones we can't see
2872 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2873 continue;
2876 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
2877 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
2878 'moodle/grade:edit'), $context)) {
2879 continue;
2882 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2883 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2884 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2886 // Add link to preferences tab if such a page exists
2887 if (file_exists($plugindir.'/preferences.php')) {
2888 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2889 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2890 get_string('preferences', 'grades') . ': ' . $pluginstr);
2893 if (count($gradereports) == 0) {
2894 $gradereports = false;
2895 $gradepreferences = false;
2896 } else if (count($gradepreferences) == 0) {
2897 $gradepreferences = false;
2898 asort($gradereports);
2899 } else {
2900 asort($gradereports);
2901 asort($gradepreferences);
2903 self::$gradereports = $gradereports;
2904 self::$gradereportpreferences = $gradepreferences;
2905 return self::$gradereports;
2909 * Get information on scales
2910 * @param int $courseid
2911 * @return grade_plugin_info
2913 public static function get_info_scales($courseid) {
2914 if (self::$scaleinfo !== null) {
2915 return self::$scaleinfo;
2917 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2918 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2919 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2920 } else {
2921 self::$scaleinfo = false;
2923 return self::$scaleinfo;
2926 * Get information on outcomes
2927 * @param int $courseid
2928 * @return grade_plugin_info
2930 public static function get_info_outcomes($courseid) {
2931 global $CFG, $SITE;
2933 if (self::$outcomeinfo !== null) {
2934 return self::$outcomeinfo;
2936 $context = context_course::instance($courseid);
2937 $canmanage = has_capability('moodle/grade:manage', $context);
2938 $canupdate = has_capability('moodle/course:update', $context);
2939 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2940 $outcomes = array();
2941 if ($canupdate) {
2942 if ($courseid!=$SITE->id) {
2943 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2944 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2946 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2947 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2948 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2949 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2950 } else {
2951 if ($courseid!=$SITE->id) {
2952 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2953 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2956 self::$outcomeinfo = $outcomes;
2957 } else {
2958 self::$outcomeinfo = false;
2960 return self::$outcomeinfo;
2963 * Get information on letters
2964 * @param int $courseid
2965 * @return array
2967 public static function get_info_letters($courseid) {
2968 global $SITE;
2969 if (self::$letterinfo !== null) {
2970 return self::$letterinfo;
2972 $context = context_course::instance($courseid);
2973 $canmanage = has_capability('moodle/grade:manage', $context);
2974 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2975 if ($canmanage || $canmanageletters) {
2976 // Redirect to system context when report is accessed from admin settings MDL-31633
2977 if ($context->instanceid == $SITE->id) {
2978 $param = array('edit' => 1);
2979 } else {
2980 $param = array('edit' => 1,'id' => $context->id);
2982 self::$letterinfo = array(
2983 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2984 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
2986 } else {
2987 self::$letterinfo = false;
2989 return self::$letterinfo;
2992 * Get information import plugins
2993 * @param int $courseid
2994 * @return array
2996 public static function get_plugins_import($courseid) {
2997 global $CFG;
2999 if (self::$importplugins !== null) {
3000 return self::$importplugins;
3002 $importplugins = array();
3003 $context = context_course::instance($courseid);
3005 if (has_capability('moodle/grade:import', $context)) {
3006 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3007 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3008 continue;
3010 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3011 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3012 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3015 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3016 // XML is the only grade import plugin that has publishing feature.
3017 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3018 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3019 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3023 if (count($importplugins) > 0) {
3024 asort($importplugins);
3025 self::$importplugins = $importplugins;
3026 } else {
3027 self::$importplugins = false;
3029 return self::$importplugins;
3032 * Get information export plugins
3033 * @param int $courseid
3034 * @return array
3036 public static function get_plugins_export($courseid) {
3037 global $CFG;
3039 if (self::$exportplugins !== null) {
3040 return self::$exportplugins;
3042 $context = context_course::instance($courseid);
3043 $exportplugins = array();
3044 $canpublishgrades = 0;
3045 if (has_capability('moodle/grade:export', $context)) {
3046 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3047 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3048 continue;
3050 // All the grade export plugins has grade publishing capabilities.
3051 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3052 $canpublishgrades++;
3055 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3056 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3057 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3060 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3061 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3062 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3063 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3066 if (count($exportplugins) > 0) {
3067 asort($exportplugins);
3068 self::$exportplugins = $exportplugins;
3069 } else {
3070 self::$exportplugins = false;
3072 return self::$exportplugins;
3076 * Returns the value of a field from a user record
3078 * @param stdClass $user object
3079 * @param stdClass $field object
3080 * @return string value of the field
3082 public static function get_user_field_value($user, $field) {
3083 if (!empty($field->customid)) {
3084 $fieldname = 'customfield_' . $field->shortname;
3085 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3086 $fieldvalue = $user->{$fieldname};
3087 } else {
3088 $fieldvalue = $field->default;
3090 } else {
3091 $fieldvalue = $user->{$field->shortname};
3093 return $fieldvalue;
3097 * Returns an array of user profile fields to be included in export
3099 * @param int $courseid
3100 * @param bool $includecustomfields
3101 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3103 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3104 global $CFG, $DB;
3106 // Gets the fields that have to be hidden
3107 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3108 $context = context_course::instance($courseid);
3109 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3110 if ($canseehiddenfields) {
3111 $hiddenfields = array();
3114 $fields = array();
3115 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3116 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3117 $userdefaultfields = user_get_default_fields();
3119 // Sets the list of profile fields
3120 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3121 if (!empty($userprofilefields)) {
3122 foreach ($userprofilefields as $field) {
3123 $field = trim($field);
3124 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3125 continue;
3127 $obj = new stdClass();
3128 $obj->customid = 0;
3129 $obj->shortname = $field;
3130 $obj->fullname = get_string($field);
3131 $fields[] = $obj;
3135 // Sets the list of custom profile fields
3136 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3137 if ($includecustomfields && !empty($customprofilefields)) {
3138 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
3139 $customfields = $DB->get_records_sql("SELECT f.*
3140 FROM {user_info_field} f
3141 JOIN {user_info_category} c ON f.categoryid=c.id
3142 WHERE f.shortname $wherefields
3143 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
3144 if (!is_array($customfields)) {
3145 continue;
3148 foreach ($customfields as $field) {
3149 // Make sure we can display this custom field
3150 if (!in_array($field->shortname, $customprofilefields)) {
3151 continue;
3152 } else if (in_array($field->shortname, $hiddenfields)) {
3153 continue;
3154 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3155 continue;
3158 $obj = new stdClass();
3159 $obj->customid = $field->id;
3160 $obj->shortname = $field->shortname;
3161 $obj->fullname = format_string($field->name);
3162 $obj->datatype = $field->datatype;
3163 $obj->default = $field->defaultdata;
3164 $fields[] = $obj;
3168 return $fields;
3172 * This helper method gets a snapshot of all the weights for a course.
3173 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3174 * @param int $courseid
3175 * @return array of itemid -> aggregationcoef2
3177 public static function fetch_all_natural_weights_for_course($courseid) {
3178 global $DB;
3179 $result = array();
3181 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3182 foreach ($records as $record) {
3183 $result[$record->id] = $record->aggregationcoef2;
3185 return $result;