MDL-48239 grades: fix notification class
[moodle.git] / grade / lib.php
blob0af91133ecd2b8806e1f6459ec2f0b7d089b84e2
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_calculations_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 foreach ($plugin_info as $plugin_type => $plugins) {
890 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
891 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
892 break;
894 foreach ($plugins as $plugin) {
895 if (is_a($plugin, 'grade_plugin_info')) {
896 if ($active_plugin == $plugin->id) {
897 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
903 return $plugin_info;
907 * A simple class containing info about grade plugins.
908 * Can be subclassed for special rules
910 * @package core_grades
911 * @copyright 2009 Nicolas Connault
912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
914 class grade_plugin_info {
916 * A unique id for this plugin
918 * @var mixed
920 public $id;
922 * A URL to access this plugin
924 * @var mixed
926 public $link;
928 * The name of this plugin
930 * @var mixed
932 public $string;
934 * Another grade_plugin_info object, parent of the current one
936 * @var mixed
938 public $parent;
941 * Constructor
943 * @param int $id A unique id for this plugin
944 * @param string $link A URL to access this plugin
945 * @param string $string The name of this plugin
946 * @param object $parent Another grade_plugin_info object, parent of the current one
948 * @return void
950 public function __construct($id, $link, $string, $parent=null) {
951 $this->id = $id;
952 $this->link = $link;
953 $this->string = $string;
954 $this->parent = $parent;
959 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
960 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
961 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
962 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
963 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
965 * @param int $courseid Course id
966 * @param string $active_type The type of the current page (report, settings,
967 * import, export, scales, outcomes, letters)
968 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
969 * @param string $heading The heading of the page. Tries to guess if none is given
970 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
971 * @param string $bodytags Additional attributes that will be added to the <body> tag
972 * @param string $buttons Additional buttons to display on the page
973 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
974 * @param string $headerhelpidentifier The help string identifier if required.
975 * @param string $headerhelpcomponent The component for the help string.
977 * @return string HTML code or nothing if $return == false
979 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
980 $heading = false, $return=false,
981 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null) {
982 global $CFG, $OUTPUT, $PAGE;
984 if ($active_type === 'preferences') {
985 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
986 $active_type = 'settings';
989 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
991 // Determine the string of the active plugin
992 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
993 $stractive_type = $plugin_info['strings'][$active_type];
995 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
996 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
997 } else {
998 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
1001 if ($active_type == 'report') {
1002 $PAGE->set_pagelayout('report');
1003 } else {
1004 $PAGE->set_pagelayout('admin');
1006 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
1007 $PAGE->set_heading($title);
1008 if ($buttons instanceof single_button) {
1009 $buttons = $OUTPUT->render($buttons);
1011 $PAGE->set_button($buttons);
1012 if ($courseid != SITEID) {
1013 grade_extend_settings($plugin_info, $courseid);
1016 $returnval = $OUTPUT->header();
1018 if (!$return) {
1019 echo $returnval;
1022 // Guess heading if not given explicitly
1023 if (!$heading) {
1024 $heading = $stractive_plugin;
1027 if ($shownavigation) {
1028 if ($courseid != SITEID &&
1029 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
1030 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
1033 $output = '';
1034 // Add a help dialogue box if provided.
1035 if (isset($headerhelpidentifier)) {
1036 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
1037 } else {
1038 $output = $OUTPUT->heading($heading);
1041 if ($return) {
1042 $returnval .= $output;
1043 } else {
1044 echo $output;
1047 if ($courseid != SITEID &&
1048 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
1049 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
1053 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
1054 context_course::instance($courseid),
1055 $PAGE->url,
1056 $return);
1058 if ($return) {
1059 return $returnval;
1064 * Utility class used for return tracking when using edit and other forms in grade plugins
1066 * @package core_grades
1067 * @copyright 2009 Nicolas Connault
1068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1070 class grade_plugin_return {
1071 public $type;
1072 public $plugin;
1073 public $courseid;
1074 public $userid;
1075 public $page;
1078 * Constructor
1080 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
1082 public function grade_plugin_return($params = null) {
1083 if (empty($params)) {
1084 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1085 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1086 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1087 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1088 $this->page = optional_param('gpr_page', null, PARAM_INT);
1090 } else {
1091 foreach ($params as $key=>$value) {
1092 if (property_exists($this, $key)) {
1093 $this->$key = $value;
1100 * Returns return parameters as options array suitable for buttons.
1101 * @return array options
1103 public function get_options() {
1104 if (empty($this->type)) {
1105 return array();
1108 $params = array();
1110 if (!empty($this->plugin)) {
1111 $params['plugin'] = $this->plugin;
1114 if (!empty($this->courseid)) {
1115 $params['id'] = $this->courseid;
1118 if (!empty($this->userid)) {
1119 $params['userid'] = $this->userid;
1122 if (!empty($this->page)) {
1123 $params['page'] = $this->page;
1126 return $params;
1130 * Returns return url
1132 * @param string $default default url when params not set
1133 * @param array $extras Extra URL parameters
1135 * @return string url
1137 public function get_return_url($default, $extras=null) {
1138 global $CFG;
1140 if (empty($this->type) or empty($this->plugin)) {
1141 return $default;
1144 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1145 $glue = '?';
1147 if (!empty($this->courseid)) {
1148 $url .= $glue.'id='.$this->courseid;
1149 $glue = '&amp;';
1152 if (!empty($this->userid)) {
1153 $url .= $glue.'userid='.$this->userid;
1154 $glue = '&amp;';
1157 if (!empty($this->page)) {
1158 $url .= $glue.'page='.$this->page;
1159 $glue = '&amp;';
1162 if (!empty($extras)) {
1163 foreach ($extras as $key=>$value) {
1164 $url .= $glue.$key.'='.$value;
1165 $glue = '&amp;';
1169 return $url;
1173 * Returns string with hidden return tracking form elements.
1174 * @return string
1176 public function get_form_fields() {
1177 if (empty($this->type)) {
1178 return '';
1181 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1183 if (!empty($this->plugin)) {
1184 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1187 if (!empty($this->courseid)) {
1188 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1191 if (!empty($this->userid)) {
1192 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1195 if (!empty($this->page)) {
1196 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1201 * Add hidden elements into mform
1203 * @param object &$mform moodle form object
1205 * @return void
1207 public function add_mform_elements(&$mform) {
1208 if (empty($this->type)) {
1209 return;
1212 $mform->addElement('hidden', 'gpr_type', $this->type);
1213 $mform->setType('gpr_type', PARAM_SAFEDIR);
1215 if (!empty($this->plugin)) {
1216 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1217 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1220 if (!empty($this->courseid)) {
1221 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1222 $mform->setType('gpr_courseid', PARAM_INT);
1225 if (!empty($this->userid)) {
1226 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1227 $mform->setType('gpr_userid', PARAM_INT);
1230 if (!empty($this->page)) {
1231 $mform->addElement('hidden', 'gpr_page', $this->page);
1232 $mform->setType('gpr_page', PARAM_INT);
1237 * Add return tracking params into url
1239 * @param moodle_url $url A URL
1241 * @return string $url with return tracking params
1243 public function add_url_params(moodle_url $url) {
1244 if (empty($this->type)) {
1245 return $url;
1248 $url->param('gpr_type', $this->type);
1250 if (!empty($this->plugin)) {
1251 $url->param('gpr_plugin', $this->plugin);
1254 if (!empty($this->courseid)) {
1255 $url->param('gpr_courseid' ,$this->courseid);
1258 if (!empty($this->userid)) {
1259 $url->param('gpr_userid', $this->userid);
1262 if (!empty($this->page)) {
1263 $url->param('gpr_page', $this->page);
1266 return $url;
1271 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1273 * @param string $path The path of the calling script (using __FILE__?)
1274 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1275 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1276 * an array of keys and values (e.g courseid => $courseid, itemid...)
1278 * @return string
1280 function grade_build_nav($path, $pagename=null, $id=null) {
1281 global $CFG, $COURSE, $PAGE;
1283 $strgrades = get_string('grades', 'grades');
1285 // Parse the path and build navlinks from its elements
1286 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1287 $path = substr($path, $dirroot_length);
1288 $path = str_replace('\\', '/', $path);
1290 $path_elements = explode('/', $path);
1292 $path_elements_count = count($path_elements);
1294 // First link is always 'grade'
1295 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1297 $link = null;
1298 $numberofelements = 3;
1300 // Prepare URL params string
1301 $linkparams = array();
1302 if (!is_null($id)) {
1303 if (is_array($id)) {
1304 foreach ($id as $idkey => $idvalue) {
1305 $linkparams[$idkey] = $idvalue;
1307 } else {
1308 $linkparams['id'] = $id;
1312 $navlink4 = null;
1314 // Remove file extensions from filenames
1315 foreach ($path_elements as $key => $filename) {
1316 $path_elements[$key] = str_replace('.php', '', $filename);
1319 // Second level links
1320 switch ($path_elements[1]) {
1321 case 'edit': // No link
1322 if ($path_elements[3] != 'index.php') {
1323 $numberofelements = 4;
1325 break;
1326 case 'import': // No link
1327 break;
1328 case 'export': // No link
1329 break;
1330 case 'report':
1331 // $id is required for this link. Do not print it if $id isn't given
1332 if (!is_null($id)) {
1333 $link = new moodle_url('/grade/report/index.php', $linkparams);
1336 if ($path_elements[2] == 'grader') {
1337 $numberofelements = 4;
1339 break;
1341 default:
1342 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1343 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1344 " as the second path element after 'grade'.");
1345 return false;
1347 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1349 // Third level links
1350 if (empty($pagename)) {
1351 $pagename = get_string($path_elements[2], 'grades');
1354 switch ($numberofelements) {
1355 case 3:
1356 $PAGE->navbar->add($pagename, $link);
1357 break;
1358 case 4:
1359 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1360 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1362 $PAGE->navbar->add($pagename);
1363 break;
1366 return '';
1370 * General structure representing grade items in course
1372 * @package core_grades
1373 * @copyright 2009 Nicolas Connault
1374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1376 class grade_structure {
1377 public $context;
1379 public $courseid;
1382 * Reference to modinfo for current course (for performance, to save
1383 * retrieving it from courseid every time). Not actually set except for
1384 * the grade_tree type.
1385 * @var course_modinfo
1387 public $modinfo;
1390 * 1D array of grade items only
1392 public $items;
1395 * Returns icon of element
1397 * @param array &$element An array representing an element in the grade_tree
1398 * @param bool $spacerifnone return spacer if no icon found
1400 * @return string icon or spacer
1402 public function get_element_icon(&$element, $spacerifnone=false) {
1403 global $CFG, $OUTPUT;
1404 require_once $CFG->libdir.'/filelib.php';
1406 switch ($element['type']) {
1407 case 'item':
1408 case 'courseitem':
1409 case 'categoryitem':
1410 $is_course = $element['object']->is_course_item();
1411 $is_category = $element['object']->is_category_item();
1412 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1413 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1414 $is_outcome = !empty($element['object']->outcomeid);
1416 if ($element['object']->is_calculated()) {
1417 $strcalc = get_string('calculatedgrade', 'grades');
1418 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
1419 s($strcalc).'" alt="'.s($strcalc).'"/>';
1421 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1422 if ($category = $element['object']->get_item_category()) {
1423 $aggrstrings = grade_helper::get_aggregation_strings();
1424 $stragg = $aggrstrings[$category->aggregation];
1425 switch ($category->aggregation) {
1426 case GRADE_AGGREGATE_MEAN:
1427 case GRADE_AGGREGATE_MEDIAN:
1428 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1429 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1430 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1431 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
1432 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1433 case GRADE_AGGREGATE_SUM:
1434 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
1435 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1436 default:
1437 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" ' .
1438 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
1442 } else if ($element['object']->itemtype == 'mod') {
1443 //prevent outcomes being displaying the same icon as the activity they are attached to
1444 if ($is_outcome) {
1445 $stroutcome = s(get_string('outcome', 'grades'));
1446 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1447 'class="icon itemicon" title="'.$stroutcome.
1448 '" alt="'.$stroutcome.'"/>';
1449 } else {
1450 $strmodname = get_string('modulename', $element['object']->itemmodule);
1451 return '<img src="'.$OUTPUT->pix_url('icon',
1452 $element['object']->itemmodule) . '" ' .
1453 'class="icon itemicon" title="' .s($strmodname).
1454 '" alt="' .s($strmodname).'"/>';
1456 } else if ($element['object']->itemtype == 'manual') {
1457 if ($element['object']->is_outcome_item()) {
1458 $stroutcome = get_string('outcome', 'grades');
1459 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1460 'class="icon itemicon" title="'.s($stroutcome).
1461 '" alt="'.s($stroutcome).'"/>';
1462 } else {
1463 $strmanual = get_string('manualitem', 'grades');
1464 return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
1465 'class="icon itemicon" title="'.s($strmanual).
1466 '" alt="'.s($strmanual).'"/>';
1469 break;
1471 case 'category':
1472 $strcat = get_string('category', 'grades');
1473 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
1474 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
1477 if ($spacerifnone) {
1478 return $OUTPUT->spacer().' ';
1479 } else {
1480 return '';
1485 * Returns name of element optionally with icon and link
1487 * @param array &$element An array representing an element in the grade_tree
1488 * @param bool $withlink Whether or not this header has a link
1489 * @param bool $icon Whether or not to display an icon with this header
1490 * @param bool $spacerifnone return spacer if no icon found
1491 * @param bool $withdescription Show description if defined by this item.
1492 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1493 * instead of "Category total" or "Course total"
1495 * @return string header
1497 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1498 $withdescription = false, $fulltotal = false) {
1499 $header = '';
1501 if ($icon) {
1502 $header .= $this->get_element_icon($element, $spacerifnone);
1505 $header .= $element['object']->get_name($fulltotal);
1507 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1508 $element['type'] != 'courseitem') {
1509 return $header;
1512 if ($withlink && $url = $this->get_activity_link($element)) {
1513 $a = new stdClass();
1514 $a->name = get_string('modulename', $element['object']->itemmodule);
1515 $title = get_string('linktoactivity', 'grades', $a);
1517 $header = html_writer::link($url, $header, array('title' => $title));
1518 } else {
1519 $header = html_writer::span($header);
1522 if ($withdescription) {
1523 $desc = $element['object']->get_description();
1524 if (!empty($desc)) {
1525 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1529 return $header;
1532 private function get_activity_link($element) {
1533 global $CFG;
1534 /** @var array static cache of the grade.php file existence flags */
1535 static $hasgradephp = array();
1537 $itemtype = $element['object']->itemtype;
1538 $itemmodule = $element['object']->itemmodule;
1539 $iteminstance = $element['object']->iteminstance;
1540 $itemnumber = $element['object']->itemnumber;
1542 // Links only for module items that have valid instance, module and are
1543 // called from grade_tree with valid modinfo
1544 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1545 return null;
1548 // Get $cm efficiently and with visibility information using modinfo
1549 $instances = $this->modinfo->get_instances();
1550 if (empty($instances[$itemmodule][$iteminstance])) {
1551 return null;
1553 $cm = $instances[$itemmodule][$iteminstance];
1555 // Do not add link if activity is not visible to the current user
1556 if (!$cm->uservisible) {
1557 return null;
1560 if (!array_key_exists($itemmodule, $hasgradephp)) {
1561 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1562 $hasgradephp[$itemmodule] = true;
1563 } else {
1564 $hasgradephp[$itemmodule] = false;
1568 // If module has grade.php, link to that, otherwise view.php
1569 if ($hasgradephp[$itemmodule]) {
1570 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1571 if (isset($element['userid'])) {
1572 $args['userid'] = $element['userid'];
1574 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1575 } else {
1576 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1581 * Returns URL of a page that is supposed to contain detailed grade analysis
1583 * At the moment, only activity modules are supported. The method generates link
1584 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1585 * gradeid and userid. If the grade.php does not exist, null is returned.
1587 * @return moodle_url|null URL or null if unable to construct it
1589 public function get_grade_analysis_url(grade_grade $grade) {
1590 global $CFG;
1591 /** @var array static cache of the grade.php file existence flags */
1592 static $hasgradephp = array();
1594 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1595 throw new coding_exception('Passed grade without the associated grade item');
1597 $item = $grade->grade_item;
1599 if (!$item->is_external_item()) {
1600 // at the moment, only activity modules are supported
1601 return null;
1603 if ($item->itemtype !== 'mod') {
1604 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1606 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1607 return null;
1610 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1611 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1612 $hasgradephp[$item->itemmodule] = true;
1613 } else {
1614 $hasgradephp[$item->itemmodule] = false;
1618 if (!$hasgradephp[$item->itemmodule]) {
1619 return null;
1622 $instances = $this->modinfo->get_instances();
1623 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1624 return null;
1626 $cm = $instances[$item->itemmodule][$item->iteminstance];
1627 if (!$cm->uservisible) {
1628 return null;
1631 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1632 'id' => $cm->id,
1633 'itemid' => $item->id,
1634 'itemnumber' => $item->itemnumber,
1635 'gradeid' => $grade->id,
1636 'userid' => $grade->userid,
1639 return $url;
1643 * Returns an action icon leading to the grade analysis page
1645 * @param grade_grade $grade
1646 * @return string
1648 public function get_grade_analysis_icon(grade_grade $grade) {
1649 global $OUTPUT;
1651 $url = $this->get_grade_analysis_url($grade);
1652 if (is_null($url)) {
1653 return '';
1656 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1657 get_string('gradeanalysis', 'core_grades')));
1661 * Returns the grade eid - the grade may not exist yet.
1663 * @param grade_grade $grade_grade A grade_grade object
1665 * @return string eid
1667 public function get_grade_eid($grade_grade) {
1668 if (empty($grade_grade->id)) {
1669 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1670 } else {
1671 return 'g'.$grade_grade->id;
1676 * Returns the grade_item eid
1677 * @param grade_item $grade_item A grade_item object
1678 * @return string eid
1680 public function get_item_eid($grade_item) {
1681 return 'ig'.$grade_item->id;
1685 * Given a grade_tree element, returns an array of parameters
1686 * used to build an icon for that element.
1688 * @param array $element An array representing an element in the grade_tree
1690 * @return array
1692 public function get_params_for_iconstr($element) {
1693 $strparams = new stdClass();
1694 $strparams->category = '';
1695 $strparams->itemname = '';
1696 $strparams->itemmodule = '';
1698 if (!method_exists($element['object'], 'get_name')) {
1699 return $strparams;
1702 $strparams->itemname = html_to_text($element['object']->get_name());
1704 // If element name is categorytotal, get the name of the parent category
1705 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1706 $parent = $element['object']->get_parent_category();
1707 $strparams->category = $parent->get_name() . ' ';
1708 } else {
1709 $strparams->category = '';
1712 $strparams->itemmodule = null;
1713 if (isset($element['object']->itemmodule)) {
1714 $strparams->itemmodule = $element['object']->itemmodule;
1716 return $strparams;
1720 * Return a reset icon for the given element.
1722 * @param array $element An array representing an element in the grade_tree
1723 * @param object $gpr A grade_plugin_return object
1724 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1725 * @return string|action_menu_link
1727 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1728 global $CFG, $OUTPUT;
1730 // Limit to category items set to use the natural weights aggregation method, and users
1731 // with the capability to manage grades.
1732 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1733 !has_capability('moodle/grade:manage', $this->context)) {
1734 return $returnactionmenulink ? null : '';
1737 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1738 $url = new moodle_url('/grade/edit/tree/action.php', array(
1739 'id' => $this->courseid,
1740 'action' => 'resetweights',
1741 'eid' => $element['eid'],
1742 'sesskey' => sesskey(),
1745 if ($returnactionmenulink) {
1746 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1747 get_string('resetweightsshort', 'grades'));
1748 } else {
1749 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1754 * Return edit icon for give element
1756 * @param array $element An array representing an element in the grade_tree
1757 * @param object $gpr A grade_plugin_return object
1758 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1759 * @return string|action_menu_link
1761 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1762 global $CFG, $OUTPUT;
1764 if (!has_capability('moodle/grade:manage', $this->context)) {
1765 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1766 // oki - let them override grade
1767 } else {
1768 return $returnactionmenulink ? null : '';
1772 static $strfeedback = null;
1773 static $streditgrade = null;
1774 if (is_null($streditgrade)) {
1775 $streditgrade = get_string('editgrade', 'grades');
1776 $strfeedback = get_string('feedback');
1779 $strparams = $this->get_params_for_iconstr($element);
1781 $object = $element['object'];
1783 switch ($element['type']) {
1784 case 'item':
1785 case 'categoryitem':
1786 case 'courseitem':
1787 $stredit = get_string('editverbose', 'grades', $strparams);
1788 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1789 $url = new moodle_url('/grade/edit/tree/item.php',
1790 array('courseid' => $this->courseid, 'id' => $object->id));
1791 } else {
1792 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1793 array('courseid' => $this->courseid, 'id' => $object->id));
1795 break;
1797 case 'category':
1798 $stredit = get_string('editverbose', 'grades', $strparams);
1799 $url = new moodle_url('/grade/edit/tree/category.php',
1800 array('courseid' => $this->courseid, 'id' => $object->id));
1801 break;
1803 case 'grade':
1804 $stredit = $streditgrade;
1805 if (empty($object->id)) {
1806 $url = new moodle_url('/grade/edit/tree/grade.php',
1807 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1808 } else {
1809 $url = new moodle_url('/grade/edit/tree/grade.php',
1810 array('courseid' => $this->courseid, 'id' => $object->id));
1812 if (!empty($object->feedback)) {
1813 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1815 break;
1817 default:
1818 $url = null;
1821 if ($url) {
1822 if ($returnactionmenulink) {
1823 return new action_menu_link_secondary($gpr->add_url_params($url),
1824 new pix_icon('t/edit', $stredit),
1825 get_string('editsettings'));
1826 } else {
1827 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1830 } else {
1831 return $returnactionmenulink ? null : '';
1836 * Return hiding icon for give element
1838 * @param array $element An array representing an element in the grade_tree
1839 * @param object $gpr A grade_plugin_return object
1840 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1841 * @return string|action_menu_link
1843 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1844 global $CFG, $OUTPUT;
1846 if (!$element['object']->can_control_visibility()) {
1847 return $returnactionmenulink ? null : '';
1850 if (!has_capability('moodle/grade:manage', $this->context) and
1851 !has_capability('moodle/grade:hide', $this->context)) {
1852 return $returnactionmenulink ? null : '';
1855 $strparams = $this->get_params_for_iconstr($element);
1856 $strshow = get_string('showverbose', 'grades', $strparams);
1857 $strhide = get_string('hideverbose', 'grades', $strparams);
1859 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1860 $url = $gpr->add_url_params($url);
1862 if ($element['object']->is_hidden()) {
1863 $type = 'show';
1864 $tooltip = $strshow;
1866 // Change the icon and add a tooltip showing the date
1867 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1868 $type = 'hiddenuntil';
1869 $tooltip = get_string('hiddenuntildate', 'grades',
1870 userdate($element['object']->get_hidden()));
1873 $url->param('action', 'show');
1875 if ($returnactionmenulink) {
1876 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1877 } else {
1878 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1881 } else {
1882 $url->param('action', 'hide');
1883 if ($returnactionmenulink) {
1884 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1885 } else {
1886 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1890 return $hideicon;
1894 * Return locking icon for given element
1896 * @param array $element An array representing an element in the grade_tree
1897 * @param object $gpr A grade_plugin_return object
1899 * @return string
1901 public function get_locking_icon($element, $gpr) {
1902 global $CFG, $OUTPUT;
1904 $strparams = $this->get_params_for_iconstr($element);
1905 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1906 $strlock = get_string('lockverbose', 'grades', $strparams);
1908 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1909 $url = $gpr->add_url_params($url);
1911 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1912 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1913 $strparamobj = new stdClass();
1914 $strparamobj->itemname = $element['object']->grade_item->itemname;
1915 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1917 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1918 array('class' => 'action-icon'));
1920 } else if ($element['object']->is_locked()) {
1921 $type = 'unlock';
1922 $tooltip = $strunlock;
1924 // Change the icon and add a tooltip showing the date
1925 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1926 $type = 'locktime';
1927 $tooltip = get_string('locktimedate', 'grades',
1928 userdate($element['object']->get_locktime()));
1931 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1932 $action = '';
1933 } else {
1934 $url->param('action', 'unlock');
1935 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1938 } else {
1939 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1940 $action = '';
1941 } else {
1942 $url->param('action', 'lock');
1943 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1947 return $action;
1951 * Return calculation icon for given element
1953 * @param array $element An array representing an element in the grade_tree
1954 * @param object $gpr A grade_plugin_return object
1955 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1956 * @return string|action_menu_link
1958 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1959 global $CFG, $OUTPUT;
1960 if (!has_capability('moodle/grade:manage', $this->context)) {
1961 return $returnactionmenulink ? null : '';
1964 $type = $element['type'];
1965 $object = $element['object'];
1967 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1968 $strparams = $this->get_params_for_iconstr($element);
1969 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
1971 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1972 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1974 // show calculation icon only when calculation possible
1975 if (!$object->is_external_item() and ($is_scale or $is_value)) {
1976 if ($object->is_calculated()) {
1977 $icon = 't/calc';
1978 } else {
1979 $icon = 't/calc_off';
1982 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
1983 $url = $gpr->add_url_params($url);
1984 if ($returnactionmenulink) {
1985 return new action_menu_link_secondary($url,
1986 new pix_icon($icon, $streditcalculation),
1987 get_string('editcalculation', 'grades'));
1988 } else {
1989 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
1994 return $returnactionmenulink ? null : '';
1999 * Flat structure similar to grade tree.
2001 * @uses grade_structure
2002 * @package core_grades
2003 * @copyright 2009 Nicolas Connault
2004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2006 class grade_seq extends grade_structure {
2009 * 1D array of elements
2011 public $elements;
2014 * Constructor, retrieves and stores array of all grade_category and grade_item
2015 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2017 * @param int $courseid The course id
2018 * @param bool $category_grade_last category grade item is the last child
2019 * @param bool $nooutcomes Whether or not outcomes should be included
2021 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2022 global $USER, $CFG;
2024 $this->courseid = $courseid;
2025 $this->context = context_course::instance($courseid);
2027 // get course grade tree
2028 $top_element = grade_category::fetch_course_tree($courseid, true);
2030 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2032 foreach ($this->elements as $key=>$unused) {
2033 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2038 * Static recursive helper - makes the grade_item for category the last children
2040 * @param array &$element The seed of the recursion
2041 * @param bool $category_grade_last category grade item is the last child
2042 * @param bool $nooutcomes Whether or not outcomes should be included
2044 * @return array
2046 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2047 if (empty($element['children'])) {
2048 return array();
2050 $children = array();
2052 foreach ($element['children'] as $sortorder=>$unused) {
2053 if ($nooutcomes and $element['type'] != 'category' and
2054 $element['children'][$sortorder]['object']->is_outcome_item()) {
2055 continue;
2057 $children[] = $element['children'][$sortorder];
2059 unset($element['children']);
2061 if ($category_grade_last and count($children) > 1) {
2062 $cat_item = array_shift($children);
2063 array_push($children, $cat_item);
2066 $result = array();
2067 foreach ($children as $child) {
2068 if ($child['type'] == 'category') {
2069 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2070 } else {
2071 $child['eid'] = 'i'.$child['object']->id;
2072 $result[$child['object']->id] = $child;
2076 return $result;
2080 * Parses the array in search of a given eid and returns a element object with
2081 * information about the element it has found.
2083 * @param int $eid Gradetree Element ID
2085 * @return object element
2087 public function locate_element($eid) {
2088 // it is a grade - construct a new object
2089 if (strpos($eid, 'n') === 0) {
2090 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2091 return null;
2094 $itemid = $matches[1];
2095 $userid = $matches[2];
2097 //extra security check - the grade item must be in this tree
2098 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2099 return null;
2102 // $gradea->id may be null - means does not exist yet
2103 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2105 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2106 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2108 } else if (strpos($eid, 'g') === 0) {
2109 $id = (int) substr($eid, 1);
2110 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2111 return null;
2113 //extra security check - the grade item must be in this tree
2114 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2115 return null;
2117 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2118 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2121 // it is a category or item
2122 foreach ($this->elements as $element) {
2123 if ($element['eid'] == $eid) {
2124 return $element;
2128 return null;
2133 * This class represents a complete tree of categories, grade_items and final grades,
2134 * organises as an array primarily, but which can also be converted to other formats.
2135 * It has simple method calls with complex implementations, allowing for easy insertion,
2136 * deletion and moving of items and categories within the tree.
2138 * @uses grade_structure
2139 * @package core_grades
2140 * @copyright 2009 Nicolas Connault
2141 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2143 class grade_tree extends grade_structure {
2146 * The basic representation of the tree as a hierarchical, 3-tiered array.
2147 * @var object $top_element
2149 public $top_element;
2152 * 2D array of grade items and categories
2153 * @var array $levels
2155 public $levels;
2158 * Grade items
2159 * @var array $items
2161 public $items;
2164 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2165 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2167 * @param int $courseid The Course ID
2168 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2169 * @param bool $category_grade_last category grade item is the last child
2170 * @param array $collapsed array of collapsed categories
2171 * @param bool $nooutcomes Whether or not outcomes should be included
2173 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2174 $collapsed=null, $nooutcomes=false) {
2175 global $USER, $CFG, $COURSE, $DB;
2177 $this->courseid = $courseid;
2178 $this->levels = array();
2179 $this->context = context_course::instance($courseid);
2181 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2182 $course = $COURSE;
2183 } else {
2184 $course = $DB->get_record('course', array('id' => $this->courseid));
2186 $this->modinfo = get_fast_modinfo($course);
2188 // get course grade tree
2189 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2191 // collapse the categories if requested
2192 if (!empty($collapsed)) {
2193 grade_tree::category_collapse($this->top_element, $collapsed);
2196 // no otucomes if requested
2197 if (!empty($nooutcomes)) {
2198 grade_tree::no_outcomes($this->top_element);
2201 // move category item to last position in category
2202 if ($category_grade_last) {
2203 grade_tree::category_grade_last($this->top_element);
2206 if ($fillers) {
2207 // inject fake categories == fillers
2208 grade_tree::inject_fillers($this->top_element, 0);
2209 // add colspans to categories and fillers
2210 grade_tree::inject_colspans($this->top_element);
2213 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2218 * Static recursive helper - removes items from collapsed categories
2220 * @param array &$element The seed of the recursion
2221 * @param array $collapsed array of collapsed categories
2223 * @return void
2225 public function category_collapse(&$element, $collapsed) {
2226 if ($element['type'] != 'category') {
2227 return;
2229 if (empty($element['children']) or count($element['children']) < 2) {
2230 return;
2233 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2234 $category_item = reset($element['children']); //keep only category item
2235 $element['children'] = array(key($element['children'])=>$category_item);
2237 } else {
2238 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2239 reset($element['children']);
2240 $first_key = key($element['children']);
2241 unset($element['children'][$first_key]);
2243 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2244 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2250 * Static recursive helper - removes all outcomes
2252 * @param array &$element The seed of the recursion
2254 * @return void
2256 public function no_outcomes(&$element) {
2257 if ($element['type'] != 'category') {
2258 return;
2260 foreach ($element['children'] as $sortorder=>$child) {
2261 if ($element['children'][$sortorder]['type'] == 'item'
2262 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2263 unset($element['children'][$sortorder]);
2265 } else if ($element['children'][$sortorder]['type'] == 'category') {
2266 grade_tree::no_outcomes($element['children'][$sortorder]);
2272 * Static recursive helper - makes the grade_item for category the last children
2274 * @param array &$element The seed of the recursion
2276 * @return void
2278 public function category_grade_last(&$element) {
2279 if (empty($element['children'])) {
2280 return;
2282 if (count($element['children']) < 2) {
2283 return;
2285 $first_item = reset($element['children']);
2286 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2287 // the category item might have been already removed
2288 $order = key($element['children']);
2289 unset($element['children'][$order]);
2290 $element['children'][$order] =& $first_item;
2292 foreach ($element['children'] as $sortorder => $child) {
2293 grade_tree::category_grade_last($element['children'][$sortorder]);
2298 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2300 * @param array &$levels The levels of the grade tree through which to recurse
2301 * @param array &$element The seed of the recursion
2302 * @param int $depth How deep are we?
2303 * @return void
2305 public function fill_levels(&$levels, &$element, $depth) {
2306 if (!array_key_exists($depth, $levels)) {
2307 $levels[$depth] = array();
2310 // prepare unique identifier
2311 if ($element['type'] == 'category') {
2312 $element['eid'] = 'cg'.$element['object']->id;
2313 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2314 $element['eid'] = 'ig'.$element['object']->id;
2315 $this->items[$element['object']->id] =& $element['object'];
2318 $levels[$depth][] =& $element;
2319 $depth++;
2320 if (empty($element['children'])) {
2321 return;
2323 $prev = 0;
2324 foreach ($element['children'] as $sortorder=>$child) {
2325 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2326 $element['children'][$sortorder]['prev'] = $prev;
2327 $element['children'][$sortorder]['next'] = 0;
2328 if ($prev) {
2329 $element['children'][$prev]['next'] = $sortorder;
2331 $prev = $sortorder;
2336 * Static recursive helper - makes full tree (all leafes are at the same level)
2338 * @param array &$element The seed of the recursion
2339 * @param int $depth How deep are we?
2341 * @return int
2343 public function inject_fillers(&$element, $depth) {
2344 $depth++;
2346 if (empty($element['children'])) {
2347 return $depth;
2349 $chdepths = array();
2350 $chids = array_keys($element['children']);
2351 $last_child = end($chids);
2352 $first_child = reset($chids);
2354 foreach ($chids as $chid) {
2355 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2357 arsort($chdepths);
2359 $maxdepth = reset($chdepths);
2360 foreach ($chdepths as $chid=>$chd) {
2361 if ($chd == $maxdepth) {
2362 continue;
2364 for ($i=0; $i < $maxdepth-$chd; $i++) {
2365 if ($chid == $first_child) {
2366 $type = 'fillerfirst';
2367 } else if ($chid == $last_child) {
2368 $type = 'fillerlast';
2369 } else {
2370 $type = 'filler';
2372 $oldchild =& $element['children'][$chid];
2373 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2374 'eid'=>'', 'depth'=>$element['object']->depth,
2375 'children'=>array($oldchild));
2379 return $maxdepth;
2383 * Static recursive helper - add colspan information into categories
2385 * @param array &$element The seed of the recursion
2387 * @return int
2389 public function inject_colspans(&$element) {
2390 if (empty($element['children'])) {
2391 return 1;
2393 $count = 0;
2394 foreach ($element['children'] as $key=>$child) {
2395 $count += grade_tree::inject_colspans($element['children'][$key]);
2397 $element['colspan'] = $count;
2398 return $count;
2402 * Parses the array in search of a given eid and returns a element object with
2403 * information about the element it has found.
2404 * @param int $eid Gradetree Element ID
2405 * @return object element
2407 public function locate_element($eid) {
2408 // it is a grade - construct a new object
2409 if (strpos($eid, 'n') === 0) {
2410 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2411 return null;
2414 $itemid = $matches[1];
2415 $userid = $matches[2];
2417 //extra security check - the grade item must be in this tree
2418 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2419 return null;
2422 // $gradea->id may be null - means does not exist yet
2423 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2425 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2426 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2428 } else if (strpos($eid, 'g') === 0) {
2429 $id = (int) substr($eid, 1);
2430 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2431 return null;
2433 //extra security check - the grade item must be in this tree
2434 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2435 return null;
2437 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2438 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2441 // it is a category or item
2442 foreach ($this->levels as $row) {
2443 foreach ($row as $element) {
2444 if ($element['type'] == 'filler') {
2445 continue;
2447 if ($element['eid'] == $eid) {
2448 return $element;
2453 return null;
2457 * Returns a well-formed XML representation of the grade-tree using recursion.
2459 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2460 * @param string $tabs The control character to use for tabs
2462 * @return string $xml
2464 public function exporttoxml($root=null, $tabs="\t") {
2465 $xml = null;
2466 $first = false;
2467 if (is_null($root)) {
2468 $root = $this->top_element;
2469 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2470 $xml .= "<gradetree>\n";
2471 $first = true;
2474 $type = 'undefined';
2475 if (strpos($root['object']->table, 'grade_categories') !== false) {
2476 $type = 'category';
2477 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2478 $type = 'item';
2479 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2480 $type = 'outcome';
2483 $xml .= "$tabs<element type=\"$type\">\n";
2484 foreach ($root['object'] as $var => $value) {
2485 if (!is_object($value) && !is_array($value) && !empty($value)) {
2486 $xml .= "$tabs\t<$var>$value</$var>\n";
2490 if (!empty($root['children'])) {
2491 $xml .= "$tabs\t<children>\n";
2492 foreach ($root['children'] as $sortorder => $child) {
2493 $xml .= $this->exportToXML($child, $tabs."\t\t");
2495 $xml .= "$tabs\t</children>\n";
2498 $xml .= "$tabs</element>\n";
2500 if ($first) {
2501 $xml .= "</gradetree>";
2504 return $xml;
2508 * Returns a JSON representation of the grade-tree using recursion.
2510 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2511 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2513 * @return string
2515 public function exporttojson($root=null, $tabs="\t") {
2516 $json = null;
2517 $first = false;
2518 if (is_null($root)) {
2519 $root = $this->top_element;
2520 $first = true;
2523 $name = '';
2526 if (strpos($root['object']->table, 'grade_categories') !== false) {
2527 $name = $root['object']->fullname;
2528 if ($name == '?') {
2529 $name = $root['object']->get_name();
2531 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2532 $name = $root['object']->itemname;
2533 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2534 $name = $root['object']->itemname;
2537 $json .= "$tabs {\n";
2538 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2539 $json .= "$tabs\t \"name\": \"$name\",\n";
2541 foreach ($root['object'] as $var => $value) {
2542 if (!is_object($value) && !is_array($value) && !empty($value)) {
2543 $json .= "$tabs\t \"$var\": \"$value\",\n";
2547 $json = substr($json, 0, strrpos($json, ','));
2549 if (!empty($root['children'])) {
2550 $json .= ",\n$tabs\t\"children\": [\n";
2551 foreach ($root['children'] as $sortorder => $child) {
2552 $json .= $this->exportToJSON($child, $tabs."\t\t");
2554 $json = substr($json, 0, strrpos($json, ','));
2555 $json .= "\n$tabs\t]\n";
2558 if ($first) {
2559 $json .= "\n}";
2560 } else {
2561 $json .= "\n$tabs},\n";
2564 return $json;
2568 * Returns the array of levels
2570 * @return array
2572 public function get_levels() {
2573 return $this->levels;
2577 * Returns the array of grade items
2579 * @return array
2581 public function get_items() {
2582 return $this->items;
2586 * Returns a specific Grade Item
2588 * @param int $itemid The ID of the grade_item object
2590 * @return grade_item
2592 public function get_item($itemid) {
2593 if (array_key_exists($itemid, $this->items)) {
2594 return $this->items[$itemid];
2595 } else {
2596 return false;
2602 * Local shortcut function for creating an edit/delete button for a grade_* object.
2603 * @param string $type 'edit' or 'delete'
2604 * @param int $courseid The Course ID
2605 * @param grade_* $object The grade_* object
2606 * @return string html
2608 function grade_button($type, $courseid, $object) {
2609 global $CFG, $OUTPUT;
2610 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2611 $objectidstring = $matches[1] . 'id';
2612 } else {
2613 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2616 $strdelete = get_string('delete');
2617 $stredit = get_string('edit');
2619 if ($type == 'delete') {
2620 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2621 } else if ($type == 'edit') {
2622 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2625 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2630 * This method adds settings to the settings block for the grade system and its
2631 * plugins
2633 * @global moodle_page $PAGE
2635 function grade_extend_settings($plugininfo, $courseid) {
2636 global $PAGE;
2638 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2640 $strings = array_shift($plugininfo);
2642 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2643 foreach ($reports as $report) {
2644 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2648 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2649 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2650 foreach ($settings as $setting) {
2651 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2655 if ($imports = grade_helper::get_plugins_import($courseid)) {
2656 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2657 foreach ($imports as $import) {
2658 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2662 if ($exports = grade_helper::get_plugins_export($courseid)) {
2663 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2664 foreach ($exports as $export) {
2665 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2669 if ($letters = grade_helper::get_info_letters($courseid)) {
2670 $letters = array_shift($letters);
2671 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2674 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2675 $outcomes = array_shift($outcomes);
2676 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2679 if ($scales = grade_helper::get_info_scales($courseid)) {
2680 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2683 if ($gradenode->contains_active_node()) {
2684 // If the gradenode is active include the settings base node (gradeadministration) in
2685 // the navbar, typcially this is ignored.
2686 $PAGE->navbar->includesettingsbase = true;
2688 // If we can get the course admin node make sure it is closed by default
2689 // as in this case the gradenode will be opened
2690 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2691 $coursenode->make_inactive();
2692 $coursenode->forceopen = false;
2698 * Grade helper class
2700 * This class provides several helpful functions that work irrespective of any
2701 * current state.
2703 * @copyright 2010 Sam Hemelryk
2704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2706 abstract class grade_helper {
2708 * Cached manage settings info {@see get_info_settings}
2709 * @var grade_plugin_info|false
2711 protected static $managesetting = null;
2713 * Cached grade report plugins {@see get_plugins_reports}
2714 * @var array|false
2716 protected static $gradereports = null;
2718 * Cached grade report plugins preferences {@see get_info_scales}
2719 * @var array|false
2721 protected static $gradereportpreferences = null;
2723 * Cached scale info {@see get_info_scales}
2724 * @var grade_plugin_info|false
2726 protected static $scaleinfo = null;
2728 * Cached outcome info {@see get_info_outcomes}
2729 * @var grade_plugin_info|false
2731 protected static $outcomeinfo = null;
2733 * Cached leftter info {@see get_info_letters}
2734 * @var grade_plugin_info|false
2736 protected static $letterinfo = null;
2738 * Cached grade import plugins {@see get_plugins_import}
2739 * @var array|false
2741 protected static $importplugins = null;
2743 * Cached grade export plugins {@see get_plugins_export}
2744 * @var array|false
2746 protected static $exportplugins = null;
2748 * Cached grade plugin strings
2749 * @var array
2751 protected static $pluginstrings = null;
2753 * Cached grade aggregation strings
2754 * @var array
2756 protected static $aggregationstrings = null;
2759 * Gets strings commonly used by the describe plugins
2761 * report => get_string('view'),
2762 * scale => get_string('scales'),
2763 * outcome => get_string('outcomes', 'grades'),
2764 * letter => get_string('letters', 'grades'),
2765 * export => get_string('export', 'grades'),
2766 * import => get_string('import'),
2767 * preferences => get_string('mypreferences', 'grades'),
2768 * settings => get_string('settings')
2770 * @return array
2772 public static function get_plugin_strings() {
2773 if (self::$pluginstrings === null) {
2774 self::$pluginstrings = array(
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('edittree', 'grades')
2784 return self::$pluginstrings;
2788 * Gets strings describing the available aggregation methods.
2790 * @return array
2792 public static function get_aggregation_strings() {
2793 if (self::$aggregationstrings === null) {
2794 self::$aggregationstrings = array(
2795 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2796 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2797 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2798 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2799 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2800 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2801 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2802 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2803 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2806 return self::$aggregationstrings;
2810 * Get grade_plugin_info object for managing settings if the user can
2812 * @param int $courseid
2813 * @return grade_plugin_info[]
2815 public static function get_info_manage_settings($courseid) {
2816 if (self::$managesetting !== null) {
2817 return self::$managesetting;
2819 $context = context_course::instance($courseid);
2820 self::$managesetting = array();
2821 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2822 self::$managesetting['categoriesanditems'] = new grade_plugin_info('setup',
2823 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2824 get_string('categoriesanditems', 'grades'));
2825 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2826 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2827 get_string('coursegradesettings', 'grades'));
2829 if (self::$gradereportpreferences === null) {
2830 self::get_plugins_reports($courseid);
2832 if (self::$gradereportpreferences) {
2833 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
2835 return self::$managesetting;
2838 * Returns an array of plugin reports as grade_plugin_info objects
2840 * @param int $courseid
2841 * @return array
2843 public static function get_plugins_reports($courseid) {
2844 global $SITE;
2846 if (self::$gradereports !== null) {
2847 return self::$gradereports;
2849 $context = context_course::instance($courseid);
2850 $gradereports = array();
2851 $gradepreferences = array();
2852 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2853 //some reports make no sense if we're not within a course
2854 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2855 continue;
2858 // Remove ones we can't see
2859 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2860 continue;
2863 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2864 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2865 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2867 // Add link to preferences tab if such a page exists
2868 if (file_exists($plugindir.'/preferences.php')) {
2869 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2870 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2871 get_string('mypreferences', 'grades') . ': ' . $pluginstr);
2874 if (count($gradereports) == 0) {
2875 $gradereports = false;
2876 $gradepreferences = false;
2877 } else if (count($gradepreferences) == 0) {
2878 $gradepreferences = false;
2879 asort($gradereports);
2880 } else {
2881 asort($gradereports);
2882 asort($gradepreferences);
2884 self::$gradereports = $gradereports;
2885 self::$gradereportpreferences = $gradepreferences;
2886 return self::$gradereports;
2890 * Get information on scales
2891 * @param int $courseid
2892 * @return grade_plugin_info
2894 public static function get_info_scales($courseid) {
2895 if (self::$scaleinfo !== null) {
2896 return self::$scaleinfo;
2898 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2899 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2900 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2901 } else {
2902 self::$scaleinfo = false;
2904 return self::$scaleinfo;
2907 * Get information on outcomes
2908 * @param int $courseid
2909 * @return grade_plugin_info
2911 public static function get_info_outcomes($courseid) {
2912 global $CFG, $SITE;
2914 if (self::$outcomeinfo !== null) {
2915 return self::$outcomeinfo;
2917 $context = context_course::instance($courseid);
2918 $canmanage = has_capability('moodle/grade:manage', $context);
2919 $canupdate = has_capability('moodle/course:update', $context);
2920 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2921 $outcomes = array();
2922 if ($canupdate) {
2923 if ($courseid!=$SITE->id) {
2924 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2925 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2927 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2928 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2929 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2930 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2931 } else {
2932 if ($courseid!=$SITE->id) {
2933 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2934 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2937 self::$outcomeinfo = $outcomes;
2938 } else {
2939 self::$outcomeinfo = false;
2941 return self::$outcomeinfo;
2944 * Get information on letters
2945 * @param int $courseid
2946 * @return array
2948 public static function get_info_letters($courseid) {
2949 global $SITE;
2950 if (self::$letterinfo !== null) {
2951 return self::$letterinfo;
2953 $context = context_course::instance($courseid);
2954 $canmanage = has_capability('moodle/grade:manage', $context);
2955 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2956 if ($canmanage || $canmanageletters) {
2957 // Redirect to system context when report is accessed from admin settings MDL-31633
2958 if ($context->instanceid == $SITE->id) {
2959 $param = array('edit' => 1);
2960 } else {
2961 $param = array('edit' => 1,'id' => $context->id);
2963 self::$letterinfo = array(
2964 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2965 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
2967 } else {
2968 self::$letterinfo = false;
2970 return self::$letterinfo;
2973 * Get information import plugins
2974 * @param int $courseid
2975 * @return array
2977 public static function get_plugins_import($courseid) {
2978 global $CFG;
2980 if (self::$importplugins !== null) {
2981 return self::$importplugins;
2983 $importplugins = array();
2984 $context = context_course::instance($courseid);
2986 if (has_capability('moodle/grade:import', $context)) {
2987 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
2988 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2989 continue;
2991 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
2992 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2993 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2997 if ($CFG->gradepublishing) {
2998 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2999 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3003 if (count($importplugins) > 0) {
3004 asort($importplugins);
3005 self::$importplugins = $importplugins;
3006 } else {
3007 self::$importplugins = false;
3009 return self::$importplugins;
3012 * Get information export plugins
3013 * @param int $courseid
3014 * @return array
3016 public static function get_plugins_export($courseid) {
3017 global $CFG;
3019 if (self::$exportplugins !== null) {
3020 return self::$exportplugins;
3022 $context = context_course::instance($courseid);
3023 $exportplugins = array();
3024 if (has_capability('moodle/grade:export', $context)) {
3025 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3026 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3027 continue;
3029 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3030 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3031 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3034 if ($CFG->gradepublishing) {
3035 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3036 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3039 if (count($exportplugins) > 0) {
3040 asort($exportplugins);
3041 self::$exportplugins = $exportplugins;
3042 } else {
3043 self::$exportplugins = false;
3045 return self::$exportplugins;
3049 * Returns the value of a field from a user record
3051 * @param stdClass $user object
3052 * @param stdClass $field object
3053 * @return string value of the field
3055 public static function get_user_field_value($user, $field) {
3056 if (!empty($field->customid)) {
3057 $fieldname = 'customfield_' . $field->shortname;
3058 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3059 $fieldvalue = $user->{$fieldname};
3060 } else {
3061 $fieldvalue = $field->default;
3063 } else {
3064 $fieldvalue = $user->{$field->shortname};
3066 return $fieldvalue;
3070 * Returns an array of user profile fields to be included in export
3072 * @param int $courseid
3073 * @param bool $includecustomfields
3074 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3076 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3077 global $CFG, $DB;
3079 // Gets the fields that have to be hidden
3080 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3081 $context = context_course::instance($courseid);
3082 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3083 if ($canseehiddenfields) {
3084 $hiddenfields = array();
3087 $fields = array();
3088 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3089 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3090 $userdefaultfields = user_get_default_fields();
3092 // Sets the list of profile fields
3093 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3094 if (!empty($userprofilefields)) {
3095 foreach ($userprofilefields as $field) {
3096 $field = trim($field);
3097 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3098 continue;
3100 $obj = new stdClass();
3101 $obj->customid = 0;
3102 $obj->shortname = $field;
3103 $obj->fullname = get_string($field);
3104 $fields[] = $obj;
3108 // Sets the list of custom profile fields
3109 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3110 if ($includecustomfields && !empty($customprofilefields)) {
3111 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
3112 $customfields = $DB->get_records_sql("SELECT f.*
3113 FROM {user_info_field} f
3114 JOIN {user_info_category} c ON f.categoryid=c.id
3115 WHERE f.shortname $wherefields
3116 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
3117 if (!is_array($customfields)) {
3118 continue;
3121 foreach ($customfields as $field) {
3122 // Make sure we can display this custom field
3123 if (!in_array($field->shortname, $customprofilefields)) {
3124 continue;
3125 } else if (in_array($field->shortname, $hiddenfields)) {
3126 continue;
3127 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3128 continue;
3131 $obj = new stdClass();
3132 $obj->customid = $field->id;
3133 $obj->shortname = $field->shortname;
3134 $obj->fullname = format_string($field->name);
3135 $obj->datatype = $field->datatype;
3136 $obj->default = $field->defaultdata;
3137 $fields[] = $obj;
3141 return $fields;
3145 * This helper method gets a snapshot of all the weights for a course.
3146 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3147 * @param int $courseid
3148 * @return array of itemid -> aggregationcoef2
3150 public static function fetch_all_natural_weights_for_course($courseid) {
3151 global $DB;
3152 $result = array();
3154 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3155 foreach ($records as $record) {
3156 $result[$record->id] = $record->aggregationcoef2;
3158 return $result;