Merge branch 'wip-mdl-52020-m29' of https://github.com/rajeshtaneja/moodle into MOODL...
[moodle.git] / grade / lib.php
blob1a7c933b62103394809f5738222126f2ff355e72
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions used by gradebook plugins and reports.
20 * @package core_grades
21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 require_once($CFG->libdir . '/gradelib.php');
26 require_once($CFG->dirroot . '/grade/export/lib.php');
28 /**
29 * This class iterates over all users that are graded in a course.
30 * Returns detailed info about users and their grades.
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class graded_users_iterator {
37 /**
38 * The couse whose users we are interested in
40 protected $course;
42 /**
43 * An array of grade items or null if only user data was requested
45 protected $grade_items;
47 /**
48 * The group ID we are interested in. 0 means all groups.
50 protected $groupid;
52 /**
53 * A recordset of graded users
55 protected $users_rs;
57 /**
58 * A recordset of user grades (grade_grade instances)
60 protected $grades_rs;
62 /**
63 * Array used when moving to next user while iterating through the grades recordset
65 protected $gradestack;
67 /**
68 * The first field of the users table by which the array of users will be sorted
70 protected $sortfield1;
72 /**
73 * Should sortfield1 be ASC or DESC
75 protected $sortorder1;
77 /**
78 * The second field of the users table by which the array of users will be sorted
80 protected $sortfield2;
82 /**
83 * Should sortfield2 be ASC or DESC
85 protected $sortorder2;
87 /**
88 * Should users whose enrolment has been suspended be ignored?
90 protected $onlyactive = false;
92 /**
93 * Enable user custom fields
95 protected $allowusercustomfields = false;
97 /**
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
101 protected $suspendedusers = array();
104 * Constructor
106 * @param object $course A course object
107 * @param array $grade_items array of grade items, if not specified only user info returned
108 * @param int $groupid iterate only group users if present
109 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
110 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
111 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
112 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
114 public function __construct($course, $grade_items=null, $groupid=0,
115 $sortfield1='lastname', $sortorder1='ASC',
116 $sortfield2='firstname', $sortorder2='ASC') {
117 $this->course = $course;
118 $this->grade_items = $grade_items;
119 $this->groupid = $groupid;
120 $this->sortfield1 = $sortfield1;
121 $this->sortorder1 = $sortorder1;
122 $this->sortfield2 = $sortfield2;
123 $this->sortorder2 = $sortorder2;
125 $this->gradestack = array();
129 * Initialise the iterator
131 * @return boolean success
133 public function init() {
134 global $CFG, $DB;
136 $this->close();
138 export_verify_grades($this->course->id);
139 $course_item = grade_item::fetch_course_item($this->course->id);
140 if ($course_item->needsupdate) {
141 // Can not calculate all final grades - sorry.
142 return false;
145 $coursecontext = context_course::instance($this->course->id);
147 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
148 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
149 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
151 $params = array_merge($params, $enrolledparams, $relatedctxparams);
153 if ($this->groupid) {
154 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
155 $groupwheresql = "AND gm.groupid = :groupid";
156 // $params contents: gradebookroles
157 $params['groupid'] = $this->groupid;
158 } else {
159 $groupsql = "";
160 $groupwheresql = "";
163 if (empty($this->sortfield1)) {
164 // We must do some sorting even if not specified.
165 $ofields = ", u.id AS usrt";
166 $order = "usrt ASC";
168 } else {
169 $ofields = ", u.$this->sortfield1 AS usrt1";
170 $order = "usrt1 $this->sortorder1";
171 if (!empty($this->sortfield2)) {
172 $ofields .= ", u.$this->sortfield2 AS usrt2";
173 $order .= ", usrt2 $this->sortorder2";
175 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
176 // User order MUST be the same in both queries,
177 // must include the only unique user->id if not already present.
178 $ofields .= ", u.id AS usrt";
179 $order .= ", usrt ASC";
183 $userfields = 'u.*';
184 $customfieldssql = '';
185 if ($this->allowusercustomfields && !empty($CFG->grade_export_customprofilefields)) {
186 $customfieldscount = 0;
187 $customfieldsarray = grade_helper::get_user_profile_fields($this->course->id, $this->allowusercustomfields);
188 foreach ($customfieldsarray as $field) {
189 if (!empty($field->customid)) {
190 $customfieldssql .= "
191 LEFT JOIN (SELECT * FROM {user_info_data}
192 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
193 ON u.id = cf$customfieldscount.userid";
194 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->shortname}";
195 $params['cf'.$customfieldscount] = $field->customid;
196 $customfieldscount++;
201 $users_sql = "SELECT $userfields $ofields
202 FROM {user} u
203 JOIN ($enrolledsql) je ON je.id = u.id
204 $groupsql $customfieldssql
205 JOIN (
206 SELECT DISTINCT ra.userid
207 FROM {role_assignments} ra
208 WHERE ra.roleid $gradebookroles_sql
209 AND ra.contextid $relatedctxsql
210 ) rainner ON rainner.userid = u.id
211 WHERE u.deleted = 0
212 $groupwheresql
213 ORDER BY $order";
214 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
216 if (!$this->onlyactive) {
217 $context = context_course::instance($this->course->id);
218 $this->suspendedusers = get_suspended_userids($context);
219 } else {
220 $this->suspendedusers = array();
223 if (!empty($this->grade_items)) {
224 $itemids = array_keys($this->grade_items);
225 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
226 $params = array_merge($params, $grades_params);
228 $grades_sql = "SELECT g.* $ofields
229 FROM {grade_grades} g
230 JOIN {user} u ON g.userid = u.id
231 JOIN ($enrolledsql) je ON je.id = u.id
232 $groupsql
233 JOIN (
234 SELECT DISTINCT ra.userid
235 FROM {role_assignments} ra
236 WHERE ra.roleid $gradebookroles_sql
237 AND ra.contextid $relatedctxsql
238 ) rainner ON rainner.userid = u.id
239 WHERE u.deleted = 0
240 AND g.itemid $itemidsql
241 $groupwheresql
242 ORDER BY $order, g.itemid ASC";
243 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
244 } else {
245 $this->grades_rs = false;
248 return true;
252 * Returns information about the next user
253 * @return mixed array of user info, all grades and feedback or null when no more users found
255 public function next_user() {
256 if (!$this->users_rs) {
257 return false; // no users present
260 if (!$this->users_rs->valid()) {
261 if ($current = $this->_pop()) {
262 // this is not good - user or grades updated between the two reads above :-(
265 return false; // no more users
266 } else {
267 $user = $this->users_rs->current();
268 $this->users_rs->next();
271 // find grades of this user
272 $grade_records = array();
273 while (true) {
274 if (!$current = $this->_pop()) {
275 break; // no more grades
278 if (empty($current->userid)) {
279 break;
282 if ($current->userid != $user->id) {
283 // grade of the next user, we have all for this user
284 $this->_push($current);
285 break;
288 $grade_records[$current->itemid] = $current;
291 $grades = array();
292 $feedbacks = array();
294 if (!empty($this->grade_items)) {
295 foreach ($this->grade_items as $grade_item) {
296 if (!isset($feedbacks[$grade_item->id])) {
297 $feedbacks[$grade_item->id] = new stdClass();
299 if (array_key_exists($grade_item->id, $grade_records)) {
300 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
301 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
302 unset($grade_records[$grade_item->id]->feedback);
303 unset($grade_records[$grade_item->id]->feedbackformat);
304 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
305 } else {
306 $feedbacks[$grade_item->id]->feedback = '';
307 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
308 $grades[$grade_item->id] =
309 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
311 $grades[$grade_item->id]->grade_item = $grade_item;
315 // Set user suspended status.
316 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
317 $result = new stdClass();
318 $result->user = $user;
319 $result->grades = $grades;
320 $result->feedbacks = $feedbacks;
321 return $result;
325 * Close the iterator, do not forget to call this function
327 public function close() {
328 if ($this->users_rs) {
329 $this->users_rs->close();
330 $this->users_rs = null;
332 if ($this->grades_rs) {
333 $this->grades_rs->close();
334 $this->grades_rs = null;
336 $this->gradestack = array();
340 * Should all enrolled users be exported or just those with an active enrolment?
342 * @param bool $onlyactive True to limit the export to users with an active enrolment
344 public function require_active_enrolment($onlyactive = true) {
345 if (!empty($this->users_rs)) {
346 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
348 $this->onlyactive = $onlyactive;
352 * Allow custom fields to be included
354 * @param bool $allow Whether to allow custom fields or not
355 * @return void
357 public function allow_user_custom_fields($allow = true) {
358 if ($allow) {
359 $this->allowusercustomfields = true;
360 } else {
361 $this->allowusercustomfields = false;
366 * Add a grade_grade instance to the grade stack
368 * @param grade_grade $grade Grade object
370 * @return void
372 private function _push($grade) {
373 array_push($this->gradestack, $grade);
378 * Remove a grade_grade instance from the grade stack
380 * @return grade_grade current grade object
382 private function _pop() {
383 global $DB;
384 if (empty($this->gradestack)) {
385 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
386 return null; // no grades present
389 $current = $this->grades_rs->current();
391 $this->grades_rs->next();
393 return $current;
394 } else {
395 return array_pop($this->gradestack);
401 * Print a selection popup form of the graded users in a course.
403 * @deprecated since 2.0
405 * @param int $course id of the course
406 * @param string $actionpage The page receiving the data from the popoup form
407 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
408 * @param int $groupid id of requested group, 0 means all
409 * @param int $includeall bool include all option
410 * @param bool $return If true, will return the HTML, otherwise, will print directly
411 * @return null
413 function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
414 global $CFG, $USER, $OUTPUT;
415 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
418 function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
419 global $USER, $CFG;
421 if (is_null($userid)) {
422 $userid = $USER->id;
424 $coursecontext = context_course::instance($course->id);
425 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
426 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
427 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
428 $menu = array(); // Will be a list of userid => user name
429 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
430 $gui = new graded_users_iterator($course, null, $groupid);
431 $gui->require_active_enrolment($showonlyactiveenrol);
432 $gui->init();
433 $label = get_string('selectauser', 'grades');
434 if ($includeall) {
435 $menu[0] = get_string('allusers', 'grades');
436 $label = get_string('selectalloroneuser', 'grades');
438 while ($userdata = $gui->next_user()) {
439 $user = $userdata->user;
440 $userfullname = fullname($user);
441 if ($user->suspendedenrolment) {
442 $menususpendedusers[$user->id] = $userfullname;
443 } else {
444 $menu[$user->id] = $userfullname;
447 $gui->close();
449 if ($includeall) {
450 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
453 if (!empty($menususpendedusers)) {
454 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
456 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
457 $select->label = $label;
458 $select->formid = 'choosegradeuser';
459 return $select;
463 * Hide warning about changed grades during upgrade to 2.8.
465 * @param int $courseid The current course id.
467 function hide_natural_aggregation_upgrade_notice($courseid) {
468 unset_config('show_sumofgrades_upgrade_' . $courseid);
472 * Hide warning about changed grades during upgrade from 2.8.0-2.8.6 and 2.9.0.
474 * @param int $courseid The current course id.
476 function grade_hide_min_max_grade_upgrade_notice($courseid) {
477 unset_config('show_min_max_grades_changed_' . $courseid);
481 * Use the grade min and max from the grade_grade.
483 * This is reserved for core use after an upgrade.
485 * @param int $courseid The current course id.
487 function grade_upgrade_use_min_max_from_grade_grade($courseid) {
488 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_GRADE);
490 grade_force_full_regrading($courseid);
491 // Do this now, because it probably happened to late in the page load to be happen automatically.
492 grade_regrade_final_grades($courseid);
496 * Use the grade min and max from the grade_item.
498 * This is reserved for core use after an upgrade.
500 * @param int $courseid The current course id.
502 function grade_upgrade_use_min_max_from_grade_item($courseid) {
503 grade_set_setting($courseid, 'minmaxtouse', GRADE_MIN_MAX_FROM_GRADE_ITEM);
505 grade_force_full_regrading($courseid);
506 // Do this now, because it probably happened to late in the page load to be happen automatically.
507 grade_regrade_final_grades($courseid);
511 * Hide warning about changed grades during upgrade to 2.8.
513 * @param int $courseid The current course id.
515 function hide_aggregatesubcats_upgrade_notice($courseid) {
516 unset_config('show_aggregatesubcats_upgrade_' . $courseid);
520 * Hide warning about changed grades due to bug fixes
522 * @param int $courseid The current course id.
524 function hide_gradebook_calculations_freeze_notice($courseid) {
525 unset_config('gradebook_calculations_freeze_' . $courseid);
529 * Print warning about changed grades during upgrade to 2.8.
531 * @param int $courseid The current course id.
532 * @param context $context The course context.
533 * @param string $thispage The relative path for the current page. E.g. /grade/report/user/index.php
534 * @param boolean $return return as string
536 * @return nothing or string if $return true
538 function print_natural_aggregation_upgrade_notice($courseid, $context, $thispage, $return=false) {
539 global $CFG, $OUTPUT;
540 $html = '';
542 // Do not do anything if they cannot manage the grades of this course.
543 if (!has_capability('moodle/grade:manage', $context)) {
544 return $html;
547 $hidesubcatswarning = optional_param('seenaggregatesubcatsupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
548 $showsubcatswarning = get_config('core', 'show_aggregatesubcats_upgrade_' . $courseid);
549 $hidenaturalwarning = optional_param('seensumofgradesupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
550 $shownaturalwarning = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
552 $hideminmaxwarning = optional_param('seenminmaxupgradedgrades', false, PARAM_BOOL) && confirm_sesskey();
553 $showminmaxwarning = get_config('core', 'show_min_max_grades_changed_' . $courseid);
555 $useminmaxfromgradeitem = optional_param('useminmaxfromgradeitem', false, PARAM_BOOL) && confirm_sesskey();
556 $useminmaxfromgradegrade = optional_param('useminmaxfromgradegrade', false, PARAM_BOOL) && confirm_sesskey();
558 $minmaxtouse = grade_get_setting($courseid, 'minmaxtouse', $CFG->grade_minmaxtouse);
560 $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $courseid);
561 $acceptgradebookchanges = optional_param('acceptgradebookchanges', false, PARAM_BOOL) && confirm_sesskey();
563 // Hide the warning if the user told it to go away.
564 if ($hidenaturalwarning) {
565 hide_natural_aggregation_upgrade_notice($courseid);
567 // Hide the warning if the user told it to go away.
568 if ($hidesubcatswarning) {
569 hide_aggregatesubcats_upgrade_notice($courseid);
572 // Hide the min/max warning if the user told it to go away.
573 if ($hideminmaxwarning) {
574 grade_hide_min_max_grade_upgrade_notice($courseid);
575 $showminmaxwarning = false;
578 if ($useminmaxfromgradegrade) {
579 // Revert to the new behaviour, we now use the grade_grade for min/max.
580 grade_upgrade_use_min_max_from_grade_grade($courseid);
581 grade_hide_min_max_grade_upgrade_notice($courseid);
582 $showminmaxwarning = false;
584 } else if ($useminmaxfromgradeitem) {
585 // Apply the new logic, we now use the grade_item for min/max.
586 grade_upgrade_use_min_max_from_grade_item($courseid);
587 grade_hide_min_max_grade_upgrade_notice($courseid);
588 $showminmaxwarning = false;
592 if (!$hidenaturalwarning && $shownaturalwarning) {
593 $message = get_string('sumofgradesupgradedgrades', 'grades');
594 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
595 $urlparams = array( 'id' => $courseid,
596 'seensumofgradesupgradedgrades' => true,
597 'sesskey' => sesskey());
598 $goawayurl = new moodle_url($thispage, $urlparams);
599 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
600 $html .= $OUTPUT->notification($message, 'notifysuccess');
601 $html .= $goawaybutton;
604 if (!$hidesubcatswarning && $showsubcatswarning) {
605 $message = get_string('aggregatesubcatsupgradedgrades', 'grades');
606 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
607 $urlparams = array( 'id' => $courseid,
608 'seenaggregatesubcatsupgradedgrades' => true,
609 'sesskey' => sesskey());
610 $goawayurl = new moodle_url($thispage, $urlparams);
611 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
612 $html .= $OUTPUT->notification($message, 'notifysuccess');
613 $html .= $goawaybutton;
616 if ($showminmaxwarning) {
617 $hidemessage = get_string('upgradedgradeshidemessage', 'grades');
618 $urlparams = array( 'id' => $courseid,
619 'seenminmaxupgradedgrades' => true,
620 'sesskey' => sesskey());
622 $goawayurl = new moodle_url($thispage, $urlparams);
623 $hideminmaxbutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
624 $moreinfo = html_writer::link(get_docs_url(get_string('minmaxtouse_link', 'grades')), get_string('moreinfo'),
625 array('target' => '_blank'));
627 if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_ITEM) {
628 // Show the message that there were min/max issues that have been resolved.
629 $message = get_string('minmaxupgradedgrades', 'grades') . ' ' . $moreinfo;
631 $revertmessage = get_string('upgradedminmaxrevertmessage', 'grades');
632 $urlparams = array('id' => $courseid,
633 'useminmaxfromgradegrade' => true,
634 'sesskey' => sesskey());
635 $reverturl = new moodle_url($thispage, $urlparams);
636 $revertbutton = $OUTPUT->single_button($reverturl, $revertmessage, 'get');
638 $html .= $OUTPUT->notification($message);
639 $html .= $revertbutton . $hideminmaxbutton;
641 } else if ($minmaxtouse == GRADE_MIN_MAX_FROM_GRADE_GRADE) {
642 // Show the warning that there are min/max issues that have not be resolved.
643 $message = get_string('minmaxupgradewarning', 'grades') . ' ' . $moreinfo;
645 $fixmessage = get_string('minmaxupgradefixbutton', 'grades');
646 $urlparams = array('id' => $courseid,
647 'useminmaxfromgradeitem' => true,
648 'sesskey' => sesskey());
649 $fixurl = new moodle_url($thispage, $urlparams);
650 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
652 $html .= $OUTPUT->notification($message);
653 $html .= $fixbutton . $hideminmaxbutton;
657 if ($gradebookcalculationsfreeze) {
658 if ($acceptgradebookchanges) {
659 // Accept potential changes in grades caused by extra credit bug MDL-49257.
660 hide_gradebook_calculations_freeze_notice($courseid);
661 $courseitem = grade_item::fetch_course_item($courseid);
662 $courseitem->force_regrading();
663 grade_regrade_final_grades($courseid);
665 $html .= $OUTPUT->notification(get_string('gradebookcalculationsuptodate', 'grades'), 'notifysuccess');
666 } else {
667 // Show the warning that there may be extra credit weights problems.
668 $a = new stdClass();
669 $a->gradebookversion = $gradebookcalculationsfreeze;
670 if (preg_match('/(\d{8,})/', $CFG->release, $matches)) {
671 $a->currentversion = $matches[1];
672 } else {
673 $a->currentversion = $CFG->release;
675 $a->url = get_docs_url('Gradebook_calculation_changes');
676 $message = get_string('gradebookcalculationswarning', 'grades', $a);
678 $fixmessage = get_string('gradebookcalculationsfixbutton', 'grades');
679 $urlparams = array('id' => $courseid,
680 'acceptgradebookchanges' => true,
681 'sesskey' => sesskey());
682 $fixurl = new moodle_url($thispage, $urlparams);
683 $fixbutton = $OUTPUT->single_button($fixurl, $fixmessage, 'get');
685 $html .= $OUTPUT->notification($message);
686 $html .= $fixbutton;
690 if (!empty($html)) {
691 $html = html_writer::tag('div', $html, array('class' => 'core_grades_notices'));
694 if ($return) {
695 return $html;
696 } else {
697 echo $html;
702 * Print grading plugin selection popup form.
704 * @param array $plugin_info An array of plugins containing information for the selector
705 * @param boolean $return return as string
707 * @return nothing or string if $return true
709 function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
710 global $CFG, $OUTPUT, $PAGE;
712 $menu = array();
713 $count = 0;
714 $active = '';
716 foreach ($plugin_info as $plugin_type => $plugins) {
717 if ($plugin_type == 'strings') {
718 continue;
721 $first_plugin = reset($plugins);
723 $sectionname = $plugin_info['strings'][$plugin_type];
724 $section = array();
726 foreach ($plugins as $plugin) {
727 $link = $plugin->link->out(false);
728 $section[$link] = $plugin->string;
729 $count++;
730 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
731 $active = $link;
735 if ($section) {
736 $menu[] = array($sectionname=>$section);
740 // finally print/return the popup form
741 if ($count > 1) {
742 $select = new url_select($menu, $active, null, 'choosepluginreport');
743 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
744 if ($return) {
745 return $OUTPUT->render($select);
746 } else {
747 echo $OUTPUT->render($select);
749 } else {
750 // only one option - no plugin selector needed
751 return '';
756 * Print grading plugin selection tab-based navigation.
758 * @param string $active_type type of plugin on current page - import, export, report or edit
759 * @param string $active_plugin active plugin type - grader, user, cvs, ...
760 * @param array $plugin_info Array of plugins
761 * @param boolean $return return as string
763 * @return nothing or string if $return true
765 function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
766 global $CFG, $COURSE;
768 if (!isset($currenttab)) { //TODO: this is weird
769 $currenttab = '';
772 $tabs = array();
773 $top_row = array();
774 $bottom_row = array();
775 $inactive = array($active_plugin);
776 $activated = array($active_type);
778 $count = 0;
779 $active = '';
781 foreach ($plugin_info as $plugin_type => $plugins) {
782 if ($plugin_type == 'strings') {
783 continue;
786 // If $plugins is actually the definition of a child-less parent link:
787 if (!empty($plugins->id)) {
788 $string = $plugins->string;
789 if (!empty($plugin_info[$active_type]->parent)) {
790 $string = $plugin_info[$active_type]->parent->string;
793 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
794 continue;
797 $first_plugin = reset($plugins);
798 $url = $first_plugin->link;
800 if ($plugin_type == 'report') {
801 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
804 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
806 if ($active_type == $plugin_type) {
807 foreach ($plugins as $plugin) {
808 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
809 if ($plugin->id == $active_plugin) {
810 $inactive = array($plugin->id);
816 $tabs[] = $top_row;
817 $tabs[] = $bottom_row;
819 if ($return) {
820 return print_tabs($tabs, $active_plugin, $inactive, $activated, true);
821 } else {
822 print_tabs($tabs, $active_plugin, $inactive, $activated);
827 * grade_get_plugin_info
829 * @param int $courseid The course id
830 * @param string $active_type type of plugin on current page - import, export, report or edit
831 * @param string $active_plugin active plugin type - grader, user, cvs, ...
833 * @return array
835 function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
836 global $CFG, $SITE;
838 $context = context_course::instance($courseid);
840 $plugin_info = array();
841 $count = 0;
842 $active = '';
843 $url_prefix = $CFG->wwwroot . '/grade/';
845 // Language strings
846 $plugin_info['strings'] = grade_helper::get_plugin_strings();
848 if ($reports = grade_helper::get_plugins_reports($courseid)) {
849 $plugin_info['report'] = $reports;
852 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
853 $plugin_info['settings'] = $settings;
856 if ($scale = grade_helper::get_info_scales($courseid)) {
857 $plugin_info['scale'] = array('view'=>$scale);
860 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
861 $plugin_info['outcome'] = $outcomes;
864 if ($letters = grade_helper::get_info_letters($courseid)) {
865 $plugin_info['letter'] = $letters;
868 if ($imports = grade_helper::get_plugins_import($courseid)) {
869 $plugin_info['import'] = $imports;
872 if ($exports = grade_helper::get_plugins_export($courseid)) {
873 $plugin_info['export'] = $exports;
876 foreach ($plugin_info as $plugin_type => $plugins) {
877 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
878 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
879 break;
881 foreach ($plugins as $plugin) {
882 if (is_a($plugin, 'grade_plugin_info')) {
883 if ($active_plugin == $plugin->id) {
884 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
890 foreach ($plugin_info as $plugin_type => $plugins) {
891 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
892 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
893 break;
895 foreach ($plugins as $plugin) {
896 if (is_a($plugin, 'grade_plugin_info')) {
897 if ($active_plugin == $plugin->id) {
898 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
904 return $plugin_info;
908 * A simple class containing info about grade plugins.
909 * Can be subclassed for special rules
911 * @package core_grades
912 * @copyright 2009 Nicolas Connault
913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
915 class grade_plugin_info {
917 * A unique id for this plugin
919 * @var mixed
921 public $id;
923 * A URL to access this plugin
925 * @var mixed
927 public $link;
929 * The name of this plugin
931 * @var mixed
933 public $string;
935 * Another grade_plugin_info object, parent of the current one
937 * @var mixed
939 public $parent;
942 * Constructor
944 * @param int $id A unique id for this plugin
945 * @param string $link A URL to access this plugin
946 * @param string $string The name of this plugin
947 * @param object $parent Another grade_plugin_info object, parent of the current one
949 * @return void
951 public function __construct($id, $link, $string, $parent=null) {
952 $this->id = $id;
953 $this->link = $link;
954 $this->string = $string;
955 $this->parent = $parent;
960 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
961 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
962 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
963 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
964 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
966 * @param int $courseid Course id
967 * @param string $active_type The type of the current page (report, settings,
968 * import, export, scales, outcomes, letters)
969 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
970 * @param string $heading The heading of the page. Tries to guess if none is given
971 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
972 * @param string $bodytags Additional attributes that will be added to the <body> tag
973 * @param string $buttons Additional buttons to display on the page
974 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
975 * @param string $headerhelpidentifier The help string identifier if required.
976 * @param string $headerhelpcomponent The component for the help string.
977 * @param stdClass $user The user object for use with the user context header.
979 * @return string HTML code or nothing if $return == false
981 function print_grade_page_head($courseid, $active_type, $active_plugin=null,
982 $heading = false, $return=false,
983 $buttons=false, $shownavigation=true, $headerhelpidentifier = null, $headerhelpcomponent = null,
984 $user = null) {
985 global $CFG, $OUTPUT, $PAGE;
987 if ($active_type === 'preferences') {
988 // In Moodle 2.8 report preferences were moved under 'settings'. Allow backward compatibility for 3rd party grade reports.
989 $active_type = 'settings';
992 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
994 // Determine the string of the active plugin
995 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
996 $stractive_type = $plugin_info['strings'][$active_type];
998 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
999 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
1000 } else {
1001 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
1004 if ($active_type == 'report') {
1005 $PAGE->set_pagelayout('report');
1006 } else {
1007 $PAGE->set_pagelayout('admin');
1009 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
1010 $PAGE->set_heading($title);
1011 if ($buttons instanceof single_button) {
1012 $buttons = $OUTPUT->render($buttons);
1014 $PAGE->set_button($buttons);
1015 if ($courseid != SITEID) {
1016 grade_extend_settings($plugin_info, $courseid);
1019 $returnval = $OUTPUT->header();
1021 if (!$return) {
1022 echo $returnval;
1025 // Guess heading if not given explicitly
1026 if (!$heading) {
1027 $heading = $stractive_plugin;
1030 if ($shownavigation) {
1031 $navselector = null;
1032 if ($courseid != SITEID &&
1033 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
1034 // It's absolutely essential that this grade plugin selector is shown after the user header. Just ask Fred.
1035 $navselector = print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, true);
1036 if ($return) {
1037 $returnval .= $navselector;
1038 } else if (!isset($user)) {
1039 echo $navselector;
1043 $output = '';
1044 // Add a help dialogue box if provided.
1045 if (isset($headerhelpidentifier)) {
1046 $output = $OUTPUT->heading_with_help($heading, $headerhelpidentifier, $headerhelpcomponent);
1047 } else {
1048 if (isset($user)) {
1049 $output = $OUTPUT->context_header(
1050 array(
1051 'heading' => fullname($user),
1052 'user' => $user,
1053 'usercontext' => context_user::instance($user->id)
1054 ), 2
1055 ) . $navselector;
1056 } else {
1057 $output = $OUTPUT->heading($heading);
1061 if ($return) {
1062 $returnval .= $output;
1063 } else {
1064 echo $output;
1067 if ($courseid != SITEID &&
1068 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
1069 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
1073 $returnval .= print_natural_aggregation_upgrade_notice($courseid,
1074 context_course::instance($courseid),
1075 $PAGE->url,
1076 $return);
1078 if ($return) {
1079 return $returnval;
1084 * Utility class used for return tracking when using edit and other forms in grade plugins
1086 * @package core_grades
1087 * @copyright 2009 Nicolas Connault
1088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1090 class grade_plugin_return {
1091 public $type;
1092 public $plugin;
1093 public $courseid;
1094 public $userid;
1095 public $page;
1098 * Constructor
1100 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
1102 public function grade_plugin_return($params = null) {
1103 if (empty($params)) {
1104 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
1105 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
1106 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
1107 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
1108 $this->page = optional_param('gpr_page', null, PARAM_INT);
1110 } else {
1111 foreach ($params as $key=>$value) {
1112 if (property_exists($this, $key)) {
1113 $this->$key = $value;
1120 * Returns return parameters as options array suitable for buttons.
1121 * @return array options
1123 public function get_options() {
1124 if (empty($this->type)) {
1125 return array();
1128 $params = array();
1130 if (!empty($this->plugin)) {
1131 $params['plugin'] = $this->plugin;
1134 if (!empty($this->courseid)) {
1135 $params['id'] = $this->courseid;
1138 if (!empty($this->userid)) {
1139 $params['userid'] = $this->userid;
1142 if (!empty($this->page)) {
1143 $params['page'] = $this->page;
1146 return $params;
1150 * Returns return url
1152 * @param string $default default url when params not set
1153 * @param array $extras Extra URL parameters
1155 * @return string url
1157 public function get_return_url($default, $extras=null) {
1158 global $CFG;
1160 if (empty($this->type) or empty($this->plugin)) {
1161 return $default;
1164 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
1165 $glue = '?';
1167 if (!empty($this->courseid)) {
1168 $url .= $glue.'id='.$this->courseid;
1169 $glue = '&amp;';
1172 if (!empty($this->userid)) {
1173 $url .= $glue.'userid='.$this->userid;
1174 $glue = '&amp;';
1177 if (!empty($this->page)) {
1178 $url .= $glue.'page='.$this->page;
1179 $glue = '&amp;';
1182 if (!empty($extras)) {
1183 foreach ($extras as $key=>$value) {
1184 $url .= $glue.$key.'='.$value;
1185 $glue = '&amp;';
1189 return $url;
1193 * Returns string with hidden return tracking form elements.
1194 * @return string
1196 public function get_form_fields() {
1197 if (empty($this->type)) {
1198 return '';
1201 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
1203 if (!empty($this->plugin)) {
1204 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
1207 if (!empty($this->courseid)) {
1208 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
1211 if (!empty($this->userid)) {
1212 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
1215 if (!empty($this->page)) {
1216 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
1221 * Add hidden elements into mform
1223 * @param object &$mform moodle form object
1225 * @return void
1227 public function add_mform_elements(&$mform) {
1228 if (empty($this->type)) {
1229 return;
1232 $mform->addElement('hidden', 'gpr_type', $this->type);
1233 $mform->setType('gpr_type', PARAM_SAFEDIR);
1235 if (!empty($this->plugin)) {
1236 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
1237 $mform->setType('gpr_plugin', PARAM_PLUGIN);
1240 if (!empty($this->courseid)) {
1241 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1242 $mform->setType('gpr_courseid', PARAM_INT);
1245 if (!empty($this->userid)) {
1246 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1247 $mform->setType('gpr_userid', PARAM_INT);
1250 if (!empty($this->page)) {
1251 $mform->addElement('hidden', 'gpr_page', $this->page);
1252 $mform->setType('gpr_page', PARAM_INT);
1257 * Add return tracking params into url
1259 * @param moodle_url $url A URL
1261 * @return string $url with return tracking params
1263 public function add_url_params(moodle_url $url) {
1264 if (empty($this->type)) {
1265 return $url;
1268 $url->param('gpr_type', $this->type);
1270 if (!empty($this->plugin)) {
1271 $url->param('gpr_plugin', $this->plugin);
1274 if (!empty($this->courseid)) {
1275 $url->param('gpr_courseid' ,$this->courseid);
1278 if (!empty($this->userid)) {
1279 $url->param('gpr_userid', $this->userid);
1282 if (!empty($this->page)) {
1283 $url->param('gpr_page', $this->page);
1286 return $url;
1291 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
1293 * @param string $path The path of the calling script (using __FILE__?)
1294 * @param string $pagename The language string to use as the last part of the navigation (non-link)
1295 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1296 * an array of keys and values (e.g courseid => $courseid, itemid...)
1298 * @return string
1300 function grade_build_nav($path, $pagename=null, $id=null) {
1301 global $CFG, $COURSE, $PAGE;
1303 $strgrades = get_string('grades', 'grades');
1305 // Parse the path and build navlinks from its elements
1306 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1307 $path = substr($path, $dirroot_length);
1308 $path = str_replace('\\', '/', $path);
1310 $path_elements = explode('/', $path);
1312 $path_elements_count = count($path_elements);
1314 // First link is always 'grade'
1315 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
1317 $link = null;
1318 $numberofelements = 3;
1320 // Prepare URL params string
1321 $linkparams = array();
1322 if (!is_null($id)) {
1323 if (is_array($id)) {
1324 foreach ($id as $idkey => $idvalue) {
1325 $linkparams[$idkey] = $idvalue;
1327 } else {
1328 $linkparams['id'] = $id;
1332 $navlink4 = null;
1334 // Remove file extensions from filenames
1335 foreach ($path_elements as $key => $filename) {
1336 $path_elements[$key] = str_replace('.php', '', $filename);
1339 // Second level links
1340 switch ($path_elements[1]) {
1341 case 'edit': // No link
1342 if ($path_elements[3] != 'index.php') {
1343 $numberofelements = 4;
1345 break;
1346 case 'import': // No link
1347 break;
1348 case 'export': // No link
1349 break;
1350 case 'report':
1351 // $id is required for this link. Do not print it if $id isn't given
1352 if (!is_null($id)) {
1353 $link = new moodle_url('/grade/report/index.php', $linkparams);
1356 if ($path_elements[2] == 'grader') {
1357 $numberofelements = 4;
1359 break;
1361 default:
1362 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
1363 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1364 " as the second path element after 'grade'.");
1365 return false;
1367 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
1369 // Third level links
1370 if (empty($pagename)) {
1371 $pagename = get_string($path_elements[2], 'grades');
1374 switch ($numberofelements) {
1375 case 3:
1376 $PAGE->navbar->add($pagename, $link);
1377 break;
1378 case 4:
1379 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
1380 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
1382 $PAGE->navbar->add($pagename);
1383 break;
1386 return '';
1390 * General structure representing grade items in course
1392 * @package core_grades
1393 * @copyright 2009 Nicolas Connault
1394 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1396 class grade_structure {
1397 public $context;
1399 public $courseid;
1402 * Reference to modinfo for current course (for performance, to save
1403 * retrieving it from courseid every time). Not actually set except for
1404 * the grade_tree type.
1405 * @var course_modinfo
1407 public $modinfo;
1410 * 1D array of grade items only
1412 public $items;
1415 * Returns icon of element
1417 * @param array &$element An array representing an element in the grade_tree
1418 * @param bool $spacerifnone return spacer if no icon found
1420 * @return string icon or spacer
1422 public function get_element_icon(&$element, $spacerifnone=false) {
1423 global $CFG, $OUTPUT;
1424 require_once $CFG->libdir.'/filelib.php';
1426 $outputstr = '';
1428 // Object holding pix_icon information before instantiation.
1429 $icon = new stdClass();
1430 $icon->attributes = array(
1431 'class' => 'icon itemicon'
1433 $icon->component = 'moodle';
1435 $none = true;
1436 switch ($element['type']) {
1437 case 'item':
1438 case 'courseitem':
1439 case 'categoryitem':
1440 $none = false;
1442 $is_course = $element['object']->is_course_item();
1443 $is_category = $element['object']->is_category_item();
1444 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1445 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
1446 $is_outcome = !empty($element['object']->outcomeid);
1448 if ($element['object']->is_calculated()) {
1449 $icon->pix = 'i/calc';
1450 $icon->title = s(get_string('calculatedgrade', 'grades'));
1452 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
1453 if ($category = $element['object']->get_item_category()) {
1454 $aggrstrings = grade_helper::get_aggregation_strings();
1455 $stragg = $aggrstrings[$category->aggregation];
1457 $icon->pix = 'i/calc';
1458 $icon->title = s($stragg);
1460 switch ($category->aggregation) {
1461 case GRADE_AGGREGATE_MEAN:
1462 case GRADE_AGGREGATE_MEDIAN:
1463 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1464 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
1465 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
1466 $icon->pix = 'i/agg_mean';
1467 break;
1468 case GRADE_AGGREGATE_SUM:
1469 $icon->pix = 'i/agg_sum';
1470 break;
1474 } else if ($element['object']->itemtype == 'mod') {
1475 // Prevent outcomes displaying the same icon as the activity they are attached to.
1476 if ($is_outcome) {
1477 $icon->pix = 'i/outcomes';
1478 $icon->title = s(get_string('outcome', 'grades'));
1479 } else {
1480 $icon->pix = 'icon';
1481 $icon->component = $element['object']->itemmodule;
1482 $icon->title = s(get_string('modulename', $element['object']->itemmodule));
1484 } else if ($element['object']->itemtype == 'manual') {
1485 if ($element['object']->is_outcome_item()) {
1486 $icon->pix = 'i/outcomes';
1487 $icon->title = s(get_string('outcome', 'grades'));
1488 } else {
1489 $icon->pix = 'i/manual_item';
1490 $icon->title = s(get_string('manualitem', 'grades'));
1493 break;
1495 case 'category':
1496 $none = false;
1497 $icon->pix = 'i/folder';
1498 $icon->title = s(get_string('category', 'grades'));
1499 break;
1502 if ($none) {
1503 if ($spacerifnone) {
1504 $outputstr = $OUTPUT->spacer() . ' ';
1506 } else {
1507 $outputstr = $OUTPUT->pix_icon($icon->pix, $icon->title, $icon->component, $icon->attributes);
1510 return $outputstr;
1514 * Returns name of element optionally with icon and link
1516 * @param array &$element An array representing an element in the grade_tree
1517 * @param bool $withlink Whether or not this header has a link
1518 * @param bool $icon Whether or not to display an icon with this header
1519 * @param bool $spacerifnone return spacer if no icon found
1520 * @param bool $withdescription Show description if defined by this item.
1521 * @param bool $fulltotal If the item is a category total, returns $categoryname."total"
1522 * instead of "Category total" or "Course total"
1524 * @return string header
1526 public function get_element_header(&$element, $withlink = false, $icon = true, $spacerifnone = false,
1527 $withdescription = false, $fulltotal = false) {
1528 $header = '';
1530 if ($icon) {
1531 $header .= $this->get_element_icon($element, $spacerifnone);
1534 $header .= $element['object']->get_name($fulltotal);
1536 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1537 $element['type'] != 'courseitem') {
1538 return $header;
1541 if ($withlink && $url = $this->get_activity_link($element)) {
1542 $a = new stdClass();
1543 $a->name = get_string('modulename', $element['object']->itemmodule);
1544 $title = get_string('linktoactivity', 'grades', $a);
1546 $header = html_writer::link($url, $header, array('title' => $title));
1547 } else {
1548 $header = html_writer::span($header);
1551 if ($withdescription) {
1552 $desc = $element['object']->get_description();
1553 if (!empty($desc)) {
1554 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1558 return $header;
1561 private function get_activity_link($element) {
1562 global $CFG;
1563 /** @var array static cache of the grade.php file existence flags */
1564 static $hasgradephp = array();
1566 $itemtype = $element['object']->itemtype;
1567 $itemmodule = $element['object']->itemmodule;
1568 $iteminstance = $element['object']->iteminstance;
1569 $itemnumber = $element['object']->itemnumber;
1571 // Links only for module items that have valid instance, module and are
1572 // called from grade_tree with valid modinfo
1573 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1574 return null;
1577 // Get $cm efficiently and with visibility information using modinfo
1578 $instances = $this->modinfo->get_instances();
1579 if (empty($instances[$itemmodule][$iteminstance])) {
1580 return null;
1582 $cm = $instances[$itemmodule][$iteminstance];
1584 // Do not add link if activity is not visible to the current user
1585 if (!$cm->uservisible) {
1586 return null;
1589 if (!array_key_exists($itemmodule, $hasgradephp)) {
1590 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1591 $hasgradephp[$itemmodule] = true;
1592 } else {
1593 $hasgradephp[$itemmodule] = false;
1597 // If module has grade.php, link to that, otherwise view.php
1598 if ($hasgradephp[$itemmodule]) {
1599 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1600 if (isset($element['userid'])) {
1601 $args['userid'] = $element['userid'];
1603 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
1604 } else {
1605 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1610 * Returns URL of a page that is supposed to contain detailed grade analysis
1612 * At the moment, only activity modules are supported. The method generates link
1613 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
1614 * gradeid and userid. If the grade.php does not exist, null is returned.
1616 * @return moodle_url|null URL or null if unable to construct it
1618 public function get_grade_analysis_url(grade_grade $grade) {
1619 global $CFG;
1620 /** @var array static cache of the grade.php file existence flags */
1621 static $hasgradephp = array();
1623 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1624 throw new coding_exception('Passed grade without the associated grade item');
1626 $item = $grade->grade_item;
1628 if (!$item->is_external_item()) {
1629 // at the moment, only activity modules are supported
1630 return null;
1632 if ($item->itemtype !== 'mod') {
1633 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1635 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1636 return null;
1639 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1640 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1641 $hasgradephp[$item->itemmodule] = true;
1642 } else {
1643 $hasgradephp[$item->itemmodule] = false;
1647 if (!$hasgradephp[$item->itemmodule]) {
1648 return null;
1651 $instances = $this->modinfo->get_instances();
1652 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1653 return null;
1655 $cm = $instances[$item->itemmodule][$item->iteminstance];
1656 if (!$cm->uservisible) {
1657 return null;
1660 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1661 'id' => $cm->id,
1662 'itemid' => $item->id,
1663 'itemnumber' => $item->itemnumber,
1664 'gradeid' => $grade->id,
1665 'userid' => $grade->userid,
1668 return $url;
1672 * Returns an action icon leading to the grade analysis page
1674 * @param grade_grade $grade
1675 * @return string
1677 public function get_grade_analysis_icon(grade_grade $grade) {
1678 global $OUTPUT;
1680 $url = $this->get_grade_analysis_url($grade);
1681 if (is_null($url)) {
1682 return '';
1685 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
1686 get_string('gradeanalysis', 'core_grades')));
1690 * Returns the grade eid - the grade may not exist yet.
1692 * @param grade_grade $grade_grade A grade_grade object
1694 * @return string eid
1696 public function get_grade_eid($grade_grade) {
1697 if (empty($grade_grade->id)) {
1698 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1699 } else {
1700 return 'g'.$grade_grade->id;
1705 * Returns the grade_item eid
1706 * @param grade_item $grade_item A grade_item object
1707 * @return string eid
1709 public function get_item_eid($grade_item) {
1710 return 'ig'.$grade_item->id;
1714 * Given a grade_tree element, returns an array of parameters
1715 * used to build an icon for that element.
1717 * @param array $element An array representing an element in the grade_tree
1719 * @return array
1721 public function get_params_for_iconstr($element) {
1722 $strparams = new stdClass();
1723 $strparams->category = '';
1724 $strparams->itemname = '';
1725 $strparams->itemmodule = '';
1727 if (!method_exists($element['object'], 'get_name')) {
1728 return $strparams;
1731 $strparams->itemname = html_to_text($element['object']->get_name());
1733 // If element name is categorytotal, get the name of the parent category
1734 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1735 $parent = $element['object']->get_parent_category();
1736 $strparams->category = $parent->get_name() . ' ';
1737 } else {
1738 $strparams->category = '';
1741 $strparams->itemmodule = null;
1742 if (isset($element['object']->itemmodule)) {
1743 $strparams->itemmodule = $element['object']->itemmodule;
1745 return $strparams;
1749 * Return a reset icon for the given element.
1751 * @param array $element An array representing an element in the grade_tree
1752 * @param object $gpr A grade_plugin_return object
1753 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1754 * @return string|action_menu_link
1756 public function get_reset_icon($element, $gpr, $returnactionmenulink = false) {
1757 global $CFG, $OUTPUT;
1759 // Limit to category items set to use the natural weights aggregation method, and users
1760 // with the capability to manage grades.
1761 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1762 !has_capability('moodle/grade:manage', $this->context)) {
1763 return $returnactionmenulink ? null : '';
1766 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1767 $url = new moodle_url('/grade/edit/tree/action.php', array(
1768 'id' => $this->courseid,
1769 'action' => 'resetweights',
1770 'eid' => $element['eid'],
1771 'sesskey' => sesskey(),
1774 if ($returnactionmenulink) {
1775 return new action_menu_link_secondary($gpr->add_url_params($url), new pix_icon('t/reset', $str),
1776 get_string('resetweightsshort', 'grades'));
1777 } else {
1778 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1783 * Return edit icon for give element
1785 * @param array $element An array representing an element in the grade_tree
1786 * @param object $gpr A grade_plugin_return object
1787 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1788 * @return string|action_menu_link
1790 public function get_edit_icon($element, $gpr, $returnactionmenulink = false) {
1791 global $CFG, $OUTPUT;
1793 if (!has_capability('moodle/grade:manage', $this->context)) {
1794 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1795 // oki - let them override grade
1796 } else {
1797 return $returnactionmenulink ? null : '';
1801 static $strfeedback = null;
1802 static $streditgrade = null;
1803 if (is_null($streditgrade)) {
1804 $streditgrade = get_string('editgrade', 'grades');
1805 $strfeedback = get_string('feedback');
1808 $strparams = $this->get_params_for_iconstr($element);
1810 $object = $element['object'];
1812 switch ($element['type']) {
1813 case 'item':
1814 case 'categoryitem':
1815 case 'courseitem':
1816 $stredit = get_string('editverbose', 'grades', $strparams);
1817 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
1818 $url = new moodle_url('/grade/edit/tree/item.php',
1819 array('courseid' => $this->courseid, 'id' => $object->id));
1820 } else {
1821 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1822 array('courseid' => $this->courseid, 'id' => $object->id));
1824 break;
1826 case 'category':
1827 $stredit = get_string('editverbose', 'grades', $strparams);
1828 $url = new moodle_url('/grade/edit/tree/category.php',
1829 array('courseid' => $this->courseid, 'id' => $object->id));
1830 break;
1832 case 'grade':
1833 $stredit = $streditgrade;
1834 if (empty($object->id)) {
1835 $url = new moodle_url('/grade/edit/tree/grade.php',
1836 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
1837 } else {
1838 $url = new moodle_url('/grade/edit/tree/grade.php',
1839 array('courseid' => $this->courseid, 'id' => $object->id));
1841 if (!empty($object->feedback)) {
1842 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
1844 break;
1846 default:
1847 $url = null;
1850 if ($url) {
1851 if ($returnactionmenulink) {
1852 return new action_menu_link_secondary($gpr->add_url_params($url),
1853 new pix_icon('t/edit', $stredit),
1854 get_string('editsettings'));
1855 } else {
1856 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
1859 } else {
1860 return $returnactionmenulink ? null : '';
1865 * Return hiding icon for give element
1867 * @param array $element An array representing an element in the grade_tree
1868 * @param object $gpr A grade_plugin_return object
1869 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1870 * @return string|action_menu_link
1872 public function get_hiding_icon($element, $gpr, $returnactionmenulink = false) {
1873 global $CFG, $OUTPUT;
1875 if (!$element['object']->can_control_visibility()) {
1876 return $returnactionmenulink ? null : '';
1879 if (!has_capability('moodle/grade:manage', $this->context) and
1880 !has_capability('moodle/grade:hide', $this->context)) {
1881 return $returnactionmenulink ? null : '';
1884 $strparams = $this->get_params_for_iconstr($element);
1885 $strshow = get_string('showverbose', 'grades', $strparams);
1886 $strhide = get_string('hideverbose', 'grades', $strparams);
1888 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1889 $url = $gpr->add_url_params($url);
1891 if ($element['object']->is_hidden()) {
1892 $type = 'show';
1893 $tooltip = $strshow;
1895 // Change the icon and add a tooltip showing the date
1896 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
1897 $type = 'hiddenuntil';
1898 $tooltip = get_string('hiddenuntildate', 'grades',
1899 userdate($element['object']->get_hidden()));
1902 $url->param('action', 'show');
1904 if ($returnactionmenulink) {
1905 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/'.$type, $tooltip), get_string('show'));
1906 } else {
1907 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
1910 } else {
1911 $url->param('action', 'hide');
1912 if ($returnactionmenulink) {
1913 $hideicon = new action_menu_link_secondary($url, new pix_icon('t/hide', $strhide), get_string('hide'));
1914 } else {
1915 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
1919 return $hideicon;
1923 * Return locking icon for given element
1925 * @param array $element An array representing an element in the grade_tree
1926 * @param object $gpr A grade_plugin_return object
1928 * @return string
1930 public function get_locking_icon($element, $gpr) {
1931 global $CFG, $OUTPUT;
1933 $strparams = $this->get_params_for_iconstr($element);
1934 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1935 $strlock = get_string('lockverbose', 'grades', $strparams);
1937 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
1938 $url = $gpr->add_url_params($url);
1940 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1941 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1942 $strparamobj = new stdClass();
1943 $strparamobj->itemname = $element['object']->grade_item->itemname;
1944 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1946 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1947 array('class' => 'action-icon'));
1949 } else if ($element['object']->is_locked()) {
1950 $type = 'unlock';
1951 $tooltip = $strunlock;
1953 // Change the icon and add a tooltip showing the date
1954 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
1955 $type = 'locktime';
1956 $tooltip = get_string('locktimedate', 'grades',
1957 userdate($element['object']->get_locktime()));
1960 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1961 $action = '';
1962 } else {
1963 $url->param('action', 'unlock');
1964 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
1967 } else {
1968 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1969 $action = '';
1970 } else {
1971 $url->param('action', 'lock');
1972 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
1976 return $action;
1980 * Return calculation icon for given element
1982 * @param array $element An array representing an element in the grade_tree
1983 * @param object $gpr A grade_plugin_return object
1984 * @param bool $returnactionmenulink return the instance of action_menu_link instead of string
1985 * @return string|action_menu_link
1987 public function get_calculation_icon($element, $gpr, $returnactionmenulink = false) {
1988 global $CFG, $OUTPUT;
1989 if (!has_capability('moodle/grade:manage', $this->context)) {
1990 return $returnactionmenulink ? null : '';
1993 $type = $element['type'];
1994 $object = $element['object'];
1996 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
1997 $strparams = $this->get_params_for_iconstr($element);
1998 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
2000 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
2001 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
2003 // show calculation icon only when calculation possible
2004 if (!$object->is_external_item() and ($is_scale or $is_value)) {
2005 if ($object->is_calculated()) {
2006 $icon = 't/calc';
2007 } else {
2008 $icon = 't/calc_off';
2011 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
2012 $url = $gpr->add_url_params($url);
2013 if ($returnactionmenulink) {
2014 return new action_menu_link_secondary($url,
2015 new pix_icon($icon, $streditcalculation),
2016 get_string('editcalculation', 'grades'));
2017 } else {
2018 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
2023 return $returnactionmenulink ? null : '';
2028 * Flat structure similar to grade tree.
2030 * @uses grade_structure
2031 * @package core_grades
2032 * @copyright 2009 Nicolas Connault
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2035 class grade_seq extends grade_structure {
2038 * 1D array of elements
2040 public $elements;
2043 * Constructor, retrieves and stores array of all grade_category and grade_item
2044 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2046 * @param int $courseid The course id
2047 * @param bool $category_grade_last category grade item is the last child
2048 * @param bool $nooutcomes Whether or not outcomes should be included
2050 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
2051 global $USER, $CFG;
2053 $this->courseid = $courseid;
2054 $this->context = context_course::instance($courseid);
2056 // get course grade tree
2057 $top_element = grade_category::fetch_course_tree($courseid, true);
2059 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
2061 foreach ($this->elements as $key=>$unused) {
2062 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
2067 * Static recursive helper - makes the grade_item for category the last children
2069 * @param array &$element The seed of the recursion
2070 * @param bool $category_grade_last category grade item is the last child
2071 * @param bool $nooutcomes Whether or not outcomes should be included
2073 * @return array
2075 public function flatten(&$element, $category_grade_last, $nooutcomes) {
2076 if (empty($element['children'])) {
2077 return array();
2079 $children = array();
2081 foreach ($element['children'] as $sortorder=>$unused) {
2082 if ($nooutcomes and $element['type'] != 'category' and
2083 $element['children'][$sortorder]['object']->is_outcome_item()) {
2084 continue;
2086 $children[] = $element['children'][$sortorder];
2088 unset($element['children']);
2090 if ($category_grade_last and count($children) > 1) {
2091 $cat_item = array_shift($children);
2092 array_push($children, $cat_item);
2095 $result = array();
2096 foreach ($children as $child) {
2097 if ($child['type'] == 'category') {
2098 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
2099 } else {
2100 $child['eid'] = 'i'.$child['object']->id;
2101 $result[$child['object']->id] = $child;
2105 return $result;
2109 * Parses the array in search of a given eid and returns a element object with
2110 * information about the element it has found.
2112 * @param int $eid Gradetree Element ID
2114 * @return object element
2116 public function locate_element($eid) {
2117 // it is a grade - construct a new object
2118 if (strpos($eid, 'n') === 0) {
2119 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2120 return null;
2123 $itemid = $matches[1];
2124 $userid = $matches[2];
2126 //extra security check - the grade item must be in this tree
2127 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2128 return null;
2131 // $gradea->id may be null - means does not exist yet
2132 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2134 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2135 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2137 } else if (strpos($eid, 'g') === 0) {
2138 $id = (int) substr($eid, 1);
2139 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2140 return null;
2142 //extra security check - the grade item must be in this tree
2143 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2144 return null;
2146 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2147 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2150 // it is a category or item
2151 foreach ($this->elements as $element) {
2152 if ($element['eid'] == $eid) {
2153 return $element;
2157 return null;
2162 * This class represents a complete tree of categories, grade_items and final grades,
2163 * organises as an array primarily, but which can also be converted to other formats.
2164 * It has simple method calls with complex implementations, allowing for easy insertion,
2165 * deletion and moving of items and categories within the tree.
2167 * @uses grade_structure
2168 * @package core_grades
2169 * @copyright 2009 Nicolas Connault
2170 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2172 class grade_tree extends grade_structure {
2175 * The basic representation of the tree as a hierarchical, 3-tiered array.
2176 * @var object $top_element
2178 public $top_element;
2181 * 2D array of grade items and categories
2182 * @var array $levels
2184 public $levels;
2187 * Grade items
2188 * @var array $items
2190 public $items;
2193 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
2194 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
2196 * @param int $courseid The Course ID
2197 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
2198 * @param bool $category_grade_last category grade item is the last child
2199 * @param array $collapsed array of collapsed categories
2200 * @param bool $nooutcomes Whether or not outcomes should be included
2202 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
2203 $collapsed=null, $nooutcomes=false) {
2204 global $USER, $CFG, $COURSE, $DB;
2206 $this->courseid = $courseid;
2207 $this->levels = array();
2208 $this->context = context_course::instance($courseid);
2210 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
2211 $course = $COURSE;
2212 } else {
2213 $course = $DB->get_record('course', array('id' => $this->courseid));
2215 $this->modinfo = get_fast_modinfo($course);
2217 // get course grade tree
2218 $this->top_element = grade_category::fetch_course_tree($courseid, true);
2220 // collapse the categories if requested
2221 if (!empty($collapsed)) {
2222 grade_tree::category_collapse($this->top_element, $collapsed);
2225 // no otucomes if requested
2226 if (!empty($nooutcomes)) {
2227 grade_tree::no_outcomes($this->top_element);
2230 // move category item to last position in category
2231 if ($category_grade_last) {
2232 grade_tree::category_grade_last($this->top_element);
2235 if ($fillers) {
2236 // inject fake categories == fillers
2237 grade_tree::inject_fillers($this->top_element, 0);
2238 // add colspans to categories and fillers
2239 grade_tree::inject_colspans($this->top_element);
2242 grade_tree::fill_levels($this->levels, $this->top_element, 0);
2247 * Static recursive helper - removes items from collapsed categories
2249 * @param array &$element The seed of the recursion
2250 * @param array $collapsed array of collapsed categories
2252 * @return void
2254 public function category_collapse(&$element, $collapsed) {
2255 if ($element['type'] != 'category') {
2256 return;
2258 if (empty($element['children']) or count($element['children']) < 2) {
2259 return;
2262 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
2263 $category_item = reset($element['children']); //keep only category item
2264 $element['children'] = array(key($element['children'])=>$category_item);
2266 } else {
2267 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
2268 reset($element['children']);
2269 $first_key = key($element['children']);
2270 unset($element['children'][$first_key]);
2272 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
2273 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2279 * Static recursive helper - removes all outcomes
2281 * @param array &$element The seed of the recursion
2283 * @return void
2285 public function no_outcomes(&$element) {
2286 if ($element['type'] != 'category') {
2287 return;
2289 foreach ($element['children'] as $sortorder=>$child) {
2290 if ($element['children'][$sortorder]['type'] == 'item'
2291 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2292 unset($element['children'][$sortorder]);
2294 } else if ($element['children'][$sortorder]['type'] == 'category') {
2295 grade_tree::no_outcomes($element['children'][$sortorder]);
2301 * Static recursive helper - makes the grade_item for category the last children
2303 * @param array &$element The seed of the recursion
2305 * @return void
2307 public function category_grade_last(&$element) {
2308 if (empty($element['children'])) {
2309 return;
2311 if (count($element['children']) < 2) {
2312 return;
2314 $first_item = reset($element['children']);
2315 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
2316 // the category item might have been already removed
2317 $order = key($element['children']);
2318 unset($element['children'][$order]);
2319 $element['children'][$order] =& $first_item;
2321 foreach ($element['children'] as $sortorder => $child) {
2322 grade_tree::category_grade_last($element['children'][$sortorder]);
2327 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
2329 * @param array &$levels The levels of the grade tree through which to recurse
2330 * @param array &$element The seed of the recursion
2331 * @param int $depth How deep are we?
2332 * @return void
2334 public function fill_levels(&$levels, &$element, $depth) {
2335 if (!array_key_exists($depth, $levels)) {
2336 $levels[$depth] = array();
2339 // prepare unique identifier
2340 if ($element['type'] == 'category') {
2341 $element['eid'] = 'cg'.$element['object']->id;
2342 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
2343 $element['eid'] = 'ig'.$element['object']->id;
2344 $this->items[$element['object']->id] =& $element['object'];
2347 $levels[$depth][] =& $element;
2348 $depth++;
2349 if (empty($element['children'])) {
2350 return;
2352 $prev = 0;
2353 foreach ($element['children'] as $sortorder=>$child) {
2354 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2355 $element['children'][$sortorder]['prev'] = $prev;
2356 $element['children'][$sortorder]['next'] = 0;
2357 if ($prev) {
2358 $element['children'][$prev]['next'] = $sortorder;
2360 $prev = $sortorder;
2365 * Static recursive helper - makes full tree (all leafes are at the same level)
2367 * @param array &$element The seed of the recursion
2368 * @param int $depth How deep are we?
2370 * @return int
2372 public function inject_fillers(&$element, $depth) {
2373 $depth++;
2375 if (empty($element['children'])) {
2376 return $depth;
2378 $chdepths = array();
2379 $chids = array_keys($element['children']);
2380 $last_child = end($chids);
2381 $first_child = reset($chids);
2383 foreach ($chids as $chid) {
2384 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2386 arsort($chdepths);
2388 $maxdepth = reset($chdepths);
2389 foreach ($chdepths as $chid=>$chd) {
2390 if ($chd == $maxdepth) {
2391 continue;
2393 for ($i=0; $i < $maxdepth-$chd; $i++) {
2394 if ($chid == $first_child) {
2395 $type = 'fillerfirst';
2396 } else if ($chid == $last_child) {
2397 $type = 'fillerlast';
2398 } else {
2399 $type = 'filler';
2401 $oldchild =& $element['children'][$chid];
2402 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2403 'eid'=>'', 'depth'=>$element['object']->depth,
2404 'children'=>array($oldchild));
2408 return $maxdepth;
2412 * Static recursive helper - add colspan information into categories
2414 * @param array &$element The seed of the recursion
2416 * @return int
2418 public function inject_colspans(&$element) {
2419 if (empty($element['children'])) {
2420 return 1;
2422 $count = 0;
2423 foreach ($element['children'] as $key=>$child) {
2424 $count += grade_tree::inject_colspans($element['children'][$key]);
2426 $element['colspan'] = $count;
2427 return $count;
2431 * Parses the array in search of a given eid and returns a element object with
2432 * information about the element it has found.
2433 * @param int $eid Gradetree Element ID
2434 * @return object element
2436 public function locate_element($eid) {
2437 // it is a grade - construct a new object
2438 if (strpos($eid, 'n') === 0) {
2439 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2440 return null;
2443 $itemid = $matches[1];
2444 $userid = $matches[2];
2446 //extra security check - the grade item must be in this tree
2447 if (!$item_el = $this->locate_element('ig'.$itemid)) {
2448 return null;
2451 // $gradea->id may be null - means does not exist yet
2452 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2454 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2455 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2457 } else if (strpos($eid, 'g') === 0) {
2458 $id = (int) substr($eid, 1);
2459 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2460 return null;
2462 //extra security check - the grade item must be in this tree
2463 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
2464 return null;
2466 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2467 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2470 // it is a category or item
2471 foreach ($this->levels as $row) {
2472 foreach ($row as $element) {
2473 if ($element['type'] == 'filler') {
2474 continue;
2476 if ($element['eid'] == $eid) {
2477 return $element;
2482 return null;
2486 * Returns a well-formed XML representation of the grade-tree using recursion.
2488 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2489 * @param string $tabs The control character to use for tabs
2491 * @return string $xml
2493 public function exporttoxml($root=null, $tabs="\t") {
2494 $xml = null;
2495 $first = false;
2496 if (is_null($root)) {
2497 $root = $this->top_element;
2498 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2499 $xml .= "<gradetree>\n";
2500 $first = true;
2503 $type = 'undefined';
2504 if (strpos($root['object']->table, 'grade_categories') !== false) {
2505 $type = 'category';
2506 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2507 $type = 'item';
2508 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2509 $type = 'outcome';
2512 $xml .= "$tabs<element type=\"$type\">\n";
2513 foreach ($root['object'] as $var => $value) {
2514 if (!is_object($value) && !is_array($value) && !empty($value)) {
2515 $xml .= "$tabs\t<$var>$value</$var>\n";
2519 if (!empty($root['children'])) {
2520 $xml .= "$tabs\t<children>\n";
2521 foreach ($root['children'] as $sortorder => $child) {
2522 $xml .= $this->exportToXML($child, $tabs."\t\t");
2524 $xml .= "$tabs\t</children>\n";
2527 $xml .= "$tabs</element>\n";
2529 if ($first) {
2530 $xml .= "</gradetree>";
2533 return $xml;
2537 * Returns a JSON representation of the grade-tree using recursion.
2539 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2540 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
2542 * @return string
2544 public function exporttojson($root=null, $tabs="\t") {
2545 $json = null;
2546 $first = false;
2547 if (is_null($root)) {
2548 $root = $this->top_element;
2549 $first = true;
2552 $name = '';
2555 if (strpos($root['object']->table, 'grade_categories') !== false) {
2556 $name = $root['object']->fullname;
2557 if ($name == '?') {
2558 $name = $root['object']->get_name();
2560 } else if (strpos($root['object']->table, 'grade_items') !== false) {
2561 $name = $root['object']->itemname;
2562 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
2563 $name = $root['object']->itemname;
2566 $json .= "$tabs {\n";
2567 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2568 $json .= "$tabs\t \"name\": \"$name\",\n";
2570 foreach ($root['object'] as $var => $value) {
2571 if (!is_object($value) && !is_array($value) && !empty($value)) {
2572 $json .= "$tabs\t \"$var\": \"$value\",\n";
2576 $json = substr($json, 0, strrpos($json, ','));
2578 if (!empty($root['children'])) {
2579 $json .= ",\n$tabs\t\"children\": [\n";
2580 foreach ($root['children'] as $sortorder => $child) {
2581 $json .= $this->exportToJSON($child, $tabs."\t\t");
2583 $json = substr($json, 0, strrpos($json, ','));
2584 $json .= "\n$tabs\t]\n";
2587 if ($first) {
2588 $json .= "\n}";
2589 } else {
2590 $json .= "\n$tabs},\n";
2593 return $json;
2597 * Returns the array of levels
2599 * @return array
2601 public function get_levels() {
2602 return $this->levels;
2606 * Returns the array of grade items
2608 * @return array
2610 public function get_items() {
2611 return $this->items;
2615 * Returns a specific Grade Item
2617 * @param int $itemid The ID of the grade_item object
2619 * @return grade_item
2621 public function get_item($itemid) {
2622 if (array_key_exists($itemid, $this->items)) {
2623 return $this->items[$itemid];
2624 } else {
2625 return false;
2631 * Local shortcut function for creating an edit/delete button for a grade_* object.
2632 * @param string $type 'edit' or 'delete'
2633 * @param int $courseid The Course ID
2634 * @param grade_* $object The grade_* object
2635 * @return string html
2637 function grade_button($type, $courseid, $object) {
2638 global $CFG, $OUTPUT;
2639 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2640 $objectidstring = $matches[1] . 'id';
2641 } else {
2642 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2645 $strdelete = get_string('delete');
2646 $stredit = get_string('edit');
2648 if ($type == 'delete') {
2649 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
2650 } else if ($type == 'edit') {
2651 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
2654 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
2659 * This method adds settings to the settings block for the grade system and its
2660 * plugins
2662 * @global moodle_page $PAGE
2664 function grade_extend_settings($plugininfo, $courseid) {
2665 global $PAGE;
2667 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2669 $strings = array_shift($plugininfo);
2671 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2672 foreach ($reports as $report) {
2673 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2677 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2678 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2679 foreach ($settings as $setting) {
2680 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2684 if ($imports = grade_helper::get_plugins_import($courseid)) {
2685 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2686 foreach ($imports as $import) {
2687 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
2691 if ($exports = grade_helper::get_plugins_export($courseid)) {
2692 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2693 foreach ($exports as $export) {
2694 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
2698 if ($letters = grade_helper::get_info_letters($courseid)) {
2699 $letters = array_shift($letters);
2700 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2703 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2704 $outcomes = array_shift($outcomes);
2705 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2708 if ($scales = grade_helper::get_info_scales($courseid)) {
2709 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2712 if ($gradenode->contains_active_node()) {
2713 // If the gradenode is active include the settings base node (gradeadministration) in
2714 // the navbar, typcially this is ignored.
2715 $PAGE->navbar->includesettingsbase = true;
2717 // If we can get the course admin node make sure it is closed by default
2718 // as in this case the gradenode will be opened
2719 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2720 $coursenode->make_inactive();
2721 $coursenode->forceopen = false;
2727 * Grade helper class
2729 * This class provides several helpful functions that work irrespective of any
2730 * current state.
2732 * @copyright 2010 Sam Hemelryk
2733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2735 abstract class grade_helper {
2737 * Cached manage settings info {@see get_info_settings}
2738 * @var grade_plugin_info|false
2740 protected static $managesetting = null;
2742 * Cached grade report plugins {@see get_plugins_reports}
2743 * @var array|false
2745 protected static $gradereports = null;
2747 * Cached grade report plugins preferences {@see get_info_scales}
2748 * @var array|false
2750 protected static $gradereportpreferences = null;
2752 * Cached scale info {@see get_info_scales}
2753 * @var grade_plugin_info|false
2755 protected static $scaleinfo = null;
2757 * Cached outcome info {@see get_info_outcomes}
2758 * @var grade_plugin_info|false
2760 protected static $outcomeinfo = null;
2762 * Cached leftter info {@see get_info_letters}
2763 * @var grade_plugin_info|false
2765 protected static $letterinfo = null;
2767 * Cached grade import plugins {@see get_plugins_import}
2768 * @var array|false
2770 protected static $importplugins = null;
2772 * Cached grade export plugins {@see get_plugins_export}
2773 * @var array|false
2775 protected static $exportplugins = null;
2777 * Cached grade plugin strings
2778 * @var array
2780 protected static $pluginstrings = null;
2782 * Cached grade aggregation strings
2783 * @var array
2785 protected static $aggregationstrings = null;
2788 * Gets strings commonly used by the describe plugins
2790 * report => get_string('view'),
2791 * scale => get_string('scales'),
2792 * outcome => get_string('outcomes', 'grades'),
2793 * letter => get_string('letters', 'grades'),
2794 * export => get_string('export', 'grades'),
2795 * import => get_string('import'),
2796 * settings => get_string('settings')
2798 * @return array
2800 public static function get_plugin_strings() {
2801 if (self::$pluginstrings === null) {
2802 self::$pluginstrings = array(
2803 'report' => get_string('view'),
2804 'scale' => get_string('scales'),
2805 'outcome' => get_string('outcomes', 'grades'),
2806 'letter' => get_string('letters', 'grades'),
2807 'export' => get_string('export', 'grades'),
2808 'import' => get_string('import'),
2809 'settings' => get_string('edittree', 'grades')
2812 return self::$pluginstrings;
2816 * Gets strings describing the available aggregation methods.
2818 * @return array
2820 public static function get_aggregation_strings() {
2821 if (self::$aggregationstrings === null) {
2822 self::$aggregationstrings = array(
2823 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2824 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2825 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2826 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2827 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2828 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2829 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2830 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2831 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2834 return self::$aggregationstrings;
2838 * Get grade_plugin_info object for managing settings if the user can
2840 * @param int $courseid
2841 * @return grade_plugin_info[]
2843 public static function get_info_manage_settings($courseid) {
2844 if (self::$managesetting !== null) {
2845 return self::$managesetting;
2847 $context = context_course::instance($courseid);
2848 self::$managesetting = array();
2849 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2850 self::$managesetting['categoriesanditems'] = new grade_plugin_info('setup',
2851 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2852 get_string('categoriesanditems', 'grades'));
2853 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2854 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2855 get_string('coursegradesettings', 'grades'));
2857 if (self::$gradereportpreferences === null) {
2858 self::get_plugins_reports($courseid);
2860 if (self::$gradereportpreferences) {
2861 self::$managesetting = array_merge(self::$managesetting, self::$gradereportpreferences);
2863 return self::$managesetting;
2866 * Returns an array of plugin reports as grade_plugin_info objects
2868 * @param int $courseid
2869 * @return array
2871 public static function get_plugins_reports($courseid) {
2872 global $SITE;
2874 if (self::$gradereports !== null) {
2875 return self::$gradereports;
2877 $context = context_course::instance($courseid);
2878 $gradereports = array();
2879 $gradepreferences = array();
2880 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
2881 //some reports make no sense if we're not within a course
2882 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2883 continue;
2886 // Remove ones we can't see
2887 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2888 continue;
2891 // Singleview doesn't doesn't accomodate for all cap combos yet, so this is hardcoded..
2892 if ($plugin === 'singleview' && !has_all_capabilities(array('moodle/grade:viewall',
2893 'moodle/grade:edit'), $context)) {
2894 continue;
2897 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
2898 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2899 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2901 // Add link to preferences tab if such a page exists
2902 if (file_exists($plugindir.'/preferences.php')) {
2903 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2904 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url,
2905 get_string('preferences', 'grades') . ': ' . $pluginstr);
2908 if (count($gradereports) == 0) {
2909 $gradereports = false;
2910 $gradepreferences = false;
2911 } else if (count($gradepreferences) == 0) {
2912 $gradepreferences = false;
2913 asort($gradereports);
2914 } else {
2915 asort($gradereports);
2916 asort($gradepreferences);
2918 self::$gradereports = $gradereports;
2919 self::$gradereportpreferences = $gradepreferences;
2920 return self::$gradereports;
2924 * Get information on scales
2925 * @param int $courseid
2926 * @return grade_plugin_info
2928 public static function get_info_scales($courseid) {
2929 if (self::$scaleinfo !== null) {
2930 return self::$scaleinfo;
2932 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
2933 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2934 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2935 } else {
2936 self::$scaleinfo = false;
2938 return self::$scaleinfo;
2941 * Get information on outcomes
2942 * @param int $courseid
2943 * @return grade_plugin_info
2945 public static function get_info_outcomes($courseid) {
2946 global $CFG, $SITE;
2948 if (self::$outcomeinfo !== null) {
2949 return self::$outcomeinfo;
2951 $context = context_course::instance($courseid);
2952 $canmanage = has_capability('moodle/grade:manage', $context);
2953 $canupdate = has_capability('moodle/course:update', $context);
2954 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2955 $outcomes = array();
2956 if ($canupdate) {
2957 if ($courseid!=$SITE->id) {
2958 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2959 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2961 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2962 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
2963 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2964 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
2965 } else {
2966 if ($courseid!=$SITE->id) {
2967 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2968 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2971 self::$outcomeinfo = $outcomes;
2972 } else {
2973 self::$outcomeinfo = false;
2975 return self::$outcomeinfo;
2978 * Get information on letters
2979 * @param int $courseid
2980 * @return array
2982 public static function get_info_letters($courseid) {
2983 global $SITE;
2984 if (self::$letterinfo !== null) {
2985 return self::$letterinfo;
2987 $context = context_course::instance($courseid);
2988 $canmanage = has_capability('moodle/grade:manage', $context);
2989 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2990 if ($canmanage || $canmanageletters) {
2991 // Redirect to system context when report is accessed from admin settings MDL-31633
2992 if ($context->instanceid == $SITE->id) {
2993 $param = array('edit' => 1);
2994 } else {
2995 $param = array('edit' => 1,'id' => $context->id);
2997 self::$letterinfo = array(
2998 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
2999 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
3001 } else {
3002 self::$letterinfo = false;
3004 return self::$letterinfo;
3007 * Get information import plugins
3008 * @param int $courseid
3009 * @return array
3011 public static function get_plugins_import($courseid) {
3012 global $CFG;
3014 if (self::$importplugins !== null) {
3015 return self::$importplugins;
3017 $importplugins = array();
3018 $context = context_course::instance($courseid);
3020 if (has_capability('moodle/grade:import', $context)) {
3021 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
3022 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
3023 continue;
3025 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
3026 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
3027 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3030 // Show key manager if grade publishing is enabled and the user has xml publishing capability.
3031 // XML is the only grade import plugin that has publishing feature.
3032 if ($CFG->gradepublishing && has_capability('gradeimport/xml:publish', $context)) {
3033 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
3034 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3038 if (count($importplugins) > 0) {
3039 asort($importplugins);
3040 self::$importplugins = $importplugins;
3041 } else {
3042 self::$importplugins = false;
3044 return self::$importplugins;
3047 * Get information export plugins
3048 * @param int $courseid
3049 * @return array
3051 public static function get_plugins_export($courseid) {
3052 global $CFG;
3054 if (self::$exportplugins !== null) {
3055 return self::$exportplugins;
3057 $context = context_course::instance($courseid);
3058 $exportplugins = array();
3059 $canpublishgrades = 0;
3060 if (has_capability('moodle/grade:export', $context)) {
3061 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
3062 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
3063 continue;
3065 // All the grade export plugins has grade publishing capabilities.
3066 if (has_capability('gradeexport/'.$plugin.':publish', $context)) {
3067 $canpublishgrades++;
3070 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
3071 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
3072 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
3075 // Show key manager if grade publishing is enabled and the user has at least one grade publishing capability.
3076 if ($CFG->gradepublishing && $canpublishgrades != 0) {
3077 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
3078 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
3081 if (count($exportplugins) > 0) {
3082 asort($exportplugins);
3083 self::$exportplugins = $exportplugins;
3084 } else {
3085 self::$exportplugins = false;
3087 return self::$exportplugins;
3091 * Returns the value of a field from a user record
3093 * @param stdClass $user object
3094 * @param stdClass $field object
3095 * @return string value of the field
3097 public static function get_user_field_value($user, $field) {
3098 if (!empty($field->customid)) {
3099 $fieldname = 'customfield_' . $field->shortname;
3100 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
3101 $fieldvalue = $user->{$fieldname};
3102 } else {
3103 $fieldvalue = $field->default;
3105 } else {
3106 $fieldvalue = $user->{$field->shortname};
3108 return $fieldvalue;
3112 * Returns an array of user profile fields to be included in export
3114 * @param int $courseid
3115 * @param bool $includecustomfields
3116 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
3118 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
3119 global $CFG, $DB;
3121 // Gets the fields that have to be hidden
3122 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
3123 $context = context_course::instance($courseid);
3124 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
3125 if ($canseehiddenfields) {
3126 $hiddenfields = array();
3129 $fields = array();
3130 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
3131 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
3132 $userdefaultfields = user_get_default_fields();
3134 // Sets the list of profile fields
3135 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
3136 if (!empty($userprofilefields)) {
3137 foreach ($userprofilefields as $field) {
3138 $field = trim($field);
3139 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
3140 continue;
3142 $obj = new stdClass();
3143 $obj->customid = 0;
3144 $obj->shortname = $field;
3145 $obj->fullname = get_string($field);
3146 $fields[] = $obj;
3150 // Sets the list of custom profile fields
3151 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
3152 if ($includecustomfields && !empty($customprofilefields)) {
3153 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
3154 $customfields = $DB->get_records_sql("SELECT f.*
3155 FROM {user_info_field} f
3156 JOIN {user_info_category} c ON f.categoryid=c.id
3157 WHERE f.shortname $wherefields
3158 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
3160 foreach ($customfields as $field) {
3161 // Make sure we can display this custom field
3162 if (!in_array($field->shortname, $customprofilefields)) {
3163 continue;
3164 } else if (in_array($field->shortname, $hiddenfields)) {
3165 continue;
3166 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
3167 continue;
3170 $obj = new stdClass();
3171 $obj->customid = $field->id;
3172 $obj->shortname = $field->shortname;
3173 $obj->fullname = format_string($field->name);
3174 $obj->datatype = $field->datatype;
3175 $obj->default = $field->defaultdata;
3176 $fields[] = $obj;
3180 return $fields;
3184 * This helper method gets a snapshot of all the weights for a course.
3185 * It is used as a quick method to see if any wieghts have been automatically adjusted.
3186 * @param int $courseid
3187 * @return array of itemid -> aggregationcoef2
3189 public static function fetch_all_natural_weights_for_course($courseid) {
3190 global $DB;
3191 $result = array();
3193 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
3194 foreach ($records as $record) {
3195 $result[$record->id] = $record->aggregationcoef2;
3197 return $result;