MDL-47541 core_grades: hints about aggregation settings on setup page
[moodle.git] / grade / lib.php
CommitLineData
cf72e2dd 1<?php
cf72e2dd 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.
13//
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/>.
16
cf72e2dd 17/**
18 * Functions used by gradebook plugins and reports.
19 *
a153c9f2 20 * @package core_grades
cf72e2dd 21 * @copyright 2009 Petr Skoda and Nicolas Connault
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
8ad36f4c 24
63d2081e
MN
25require_once($CFG->libdir . '/gradelib.php');
26require_once($CFG->dirroot . '/grade/export/lib.php');
7a6b7acf 27
0f5660f7 28/**
29 * This class iterates over all users that are graded in a course.
b9f49659 30 * Returns detailed info about users and their grades.
cf72e2dd 31 *
32 * @author Petr Skoda <skodak@moodle.org>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0f5660f7 34 */
35class graded_users_iterator {
728ff21b
AD
36
37 /**
38 * The couse whose users we are interested in
39 */
40 protected $course;
41
42 /**
43 * An array of grade items or null if only user data was requested
44 */
45 protected $grade_items;
46
47 /**
48 * The group ID we are interested in. 0 means all groups.
49 */
50 protected $groupid;
51
52 /**
53 * A recordset of graded users
54 */
55 protected $users_rs;
56
57 /**
58 * A recordset of user grades (grade_grade instances)
59 */
60 protected $grades_rs;
61
62 /**
63 * Array used when moving to next user while iterating through the grades recordset
64 */
65 protected $gradestack;
66
67 /**
68 * The first field of the users table by which the array of users will be sorted
69 */
70 protected $sortfield1;
71
72 /**
73 * Should sortfield1 be ASC or DESC
74 */
75 protected $sortorder1;
76
77 /**
78 * The second field of the users table by which the array of users will be sorted
79 */
80 protected $sortfield2;
81
82 /**
83 * Should sortfield2 be ASC or DESC
84 */
85 protected $sortorder2;
0f5660f7 86
78ab98bc
AD
87 /**
88 * Should users whose enrolment has been suspended be ignored?
89 */
90 protected $onlyactive = false;
91
61c8e0d7
FM
92 /**
93 * Enable user custom fields
94 */
95 protected $allowusercustomfields = false;
96
38c1dd19
RT
97 /**
98 * List of suspended users in course. This includes users whose enrolment status is suspended
99 * or enrolment has expired or not started.
100 */
101 protected $suspendedusers = array();
102
0f5660f7 103 /**
104 * Constructor
cf72e2dd 105 *
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
d08bba83 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)
0f5660f7 113 */
728ff21b 114 public function __construct($course, $grade_items=null, $groupid=0,
cf72e2dd 115 $sortfield1='lastname', $sortorder1='ASC',
116 $sortfield2='firstname', $sortorder2='ASC') {
0f5660f7 117 $this->course = $course;
118 $this->grade_items = $grade_items;
119 $this->groupid = $groupid;
d08bba83 120 $this->sortfield1 = $sortfield1;
121 $this->sortorder1 = $sortorder1;
122 $this->sortfield2 = $sortfield2;
123 $this->sortorder2 = $sortorder2;
0f5660f7 124
125 $this->gradestack = array();
126 }
127
128 /**
129 * Initialise the iterator
728ff21b 130 *
0f5660f7 131 * @return boolean success
132 */
d24832f9 133 public function init() {
134 global $CFG, $DB;
0f5660f7 135
136 $this->close();
137
63d2081e 138 export_verify_grades($this->course->id);
0f5660f7 139 $course_item = grade_item::fetch_course_item($this->course->id);
140 if ($course_item->needsupdate) {
4e829d48 141 // Can not calculate all final grades - sorry.
0f5660f7 142 return false;
143 }
144
d4060472 145 $coursecontext = context_course::instance($this->course->id);
656d17c2 146
4e829d48
MN
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');
78ab98bc 149 list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, '', 0, $this->onlyactive);
656d17c2 150
4e829d48 151 $params = array_merge($params, $enrolledparams, $relatedctxparams);
0f5660f7 152
153 if ($this->groupid) {
d24832f9 154 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
e58fcb35 155 $groupwheresql = "AND gm.groupid = :groupid";
d24832f9 156 // $params contents: gradebookroles
e58fcb35 157 $params['groupid'] = $this->groupid;
0f5660f7 158 } else {
159 $groupsql = "";
160 $groupwheresql = "";
161 }
162
345674ca 163 if (empty($this->sortfield1)) {
4e829d48 164 // We must do some sorting even if not specified.
345674ca 165 $ofields = ", u.id AS usrt";
166 $order = "usrt ASC";
167
168 } else {
169 $ofields = ", u.$this->sortfield1 AS usrt1";
170 $order = "usrt1 $this->sortorder1";
171 if (!empty($this->sortfield2)) {
0febb12d 172 $ofields .= ", u.$this->sortfield2 AS usrt2";
345674ca 173 $order .= ", usrt2 $this->sortorder2";
174 }
175 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
4e829d48
MN
176 // User order MUST be the same in both queries,
177 // must include the only unique user->id if not already present.
345674ca 178 $ofields .= ", u.id AS usrt";
179 $order .= ", usrt ASC";
180 }
181 }
182
293f42b6
CF
183 $userfields = 'u.*';
184 $customfieldssql = '';
61c8e0d7
FM
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)) {
293f42b6 190 $customfieldssql .= "
61c8e0d7
FM
191 LEFT JOIN (SELECT * FROM {user_info_data}
192 WHERE fieldid = :cf$customfieldscount) cf$customfieldscount
193 ON u.id = cf$customfieldscount.userid";
c1735baf 194 $userfields .= ", cf$customfieldscount.data AS customfield_{$field->shortname}";
61c8e0d7
FM
195 $params['cf'.$customfieldscount] = $field->customid;
196 $customfieldscount++;
293f42b6
CF
197 }
198 }
199 }
200
293f42b6 201 $users_sql = "SELECT $userfields $ofields
d24832f9 202 FROM {user} u
656d17c2 203 JOIN ($enrolledsql) je ON je.id = u.id
293f42b6 204 $groupsql $customfieldssql
656d17c2
AD
205 JOIN (
206 SELECT DISTINCT ra.userid
207 FROM {role_assignments} ra
208 WHERE ra.roleid $gradebookroles_sql
4e829d48 209 AND ra.contextid $relatedctxsql
656d17c2
AD
210 ) rainner ON rainner.userid = u.id
211 WHERE u.deleted = 0
345674ca 212 $groupwheresql
213 ORDER BY $order";
d24832f9 214 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
0f5660f7 215
38c1dd19
RT
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();
221 }
222
0f5660f7 223 if (!empty($this->grade_items)) {
224 $itemids = array_keys($this->grade_items);
cf717dc2 225 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
d24832f9 226 $params = array_merge($params, $grades_params);
0f5660f7 227
345674ca 228 $grades_sql = "SELECT g.* $ofields
d24832f9 229 FROM {grade_grades} g
656d17c2
AD
230 JOIN {user} u ON g.userid = u.id
231 JOIN ($enrolledsql) je ON je.id = u.id
0f5660f7 232 $groupsql
656d17c2
AD
233 JOIN (
234 SELECT DISTINCT ra.userid
235 FROM {role_assignments} ra
236 WHERE ra.roleid $gradebookroles_sql
4e829d48 237 AND ra.contextid $relatedctxsql
4f82032a 238 ) rainner ON rainner.userid = u.id
656d17c2
AD
239 WHERE u.deleted = 0
240 AND g.itemid $itemidsql
241 $groupwheresql
345674ca 242 ORDER BY $order, g.itemid ASC";
d24832f9 243 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
345674ca 244 } else {
245 $this->grades_rs = false;
0f5660f7 246 }
345674ca 247
0f5660f7 248 return true;
249 }
250
251 /**
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
254 */
728ff21b 255 public function next_user() {
03cedd62 256 if (!$this->users_rs) {
0f5660f7 257 return false; // no users present
258 }
259
5c75a0a3 260 if (!$this->users_rs->valid()) {
345674ca 261 if ($current = $this->_pop()) {
262 // this is not good - user or grades updated between the two reads above :-(
263 }
264
0f5660f7 265 return false; // no more users
5c75a0a3 266 } else {
267 $user = $this->users_rs->current();
268 $this->users_rs->next();
0f5660f7 269 }
270
345674ca 271 // find grades of this user
0f5660f7 272 $grade_records = array();
273 while (true) {
274 if (!$current = $this->_pop()) {
275 break; // no more grades
276 }
277
5c75a0a3 278 if (empty($current->userid)) {
279 break;
280 }
281
345674ca 282 if ($current->userid != $user->id) {
283 // grade of the next user, we have all for this user
0f5660f7 284 $this->_push($current);
285 break;
286 }
287
288 $grade_records[$current->itemid] = $current;
289 }
290
291 $grades = array();
292 $feedbacks = array();
293
d08bba83 294 if (!empty($this->grade_items)) {
345674ca 295 foreach ($this->grade_items as $grade_item) {
6189c7b4
FM
296 if (!isset($feedbacks[$grade_item->id])) {
297 $feedbacks[$grade_item->id] = new stdClass();
298 }
345674ca 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;
cf72e2dd 308 $grades[$grade_item->id] =
309 new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
345674ca 310 }
0f5660f7 311 }
312 }
313
38c1dd19
RT
314 // Set user suspended status.
315 $user->suspendedenrolment = isset($this->suspendedusers[$user->id]);
ace9051c 316 $result = new stdClass();
0f5660f7 317 $result->user = $user;
318 $result->grades = $grades;
319 $result->feedbacks = $feedbacks;
0f5660f7 320 return $result;
321 }
322
323 /**
728ff21b 324 * Close the iterator, do not forget to call this function
0f5660f7 325 */
728ff21b 326 public function close() {
caffc55a 327 if ($this->users_rs) {
d24832f9 328 $this->users_rs->close();
caffc55a 329 $this->users_rs = null;
0f5660f7 330 }
caffc55a 331 if ($this->grades_rs) {
d24832f9 332 $this->grades_rs->close();
caffc55a 333 $this->grades_rs = null;
0f5660f7 334 }
335 $this->gradestack = array();
336 }
337
78ab98bc
AD
338 /**
339 * Should all enrolled users be exported or just those with an active enrolment?
340 *
341 * @param bool $onlyactive True to limit the export to users with an active enrolment
342 */
343 public function require_active_enrolment($onlyactive = true) {
344 if (!empty($this->users_rs)) {
345 debugging('Calling require_active_enrolment() has no effect unless you call init() again', DEBUG_DEVELOPER);
346 }
347 $this->onlyactive = $onlyactive;
348 }
349
61c8e0d7
FM
350 /**
351 * Allow custom fields to be included
352 *
353 * @param bool $allow Whether to allow custom fields or not
354 * @return void
355 */
356 public function allow_user_custom_fields($allow = true) {
357 if ($allow) {
358 $this->allowusercustomfields = true;
359 } else {
360 $this->allowusercustomfields = false;
361 }
362 }
cf72e2dd 363
0f5660f7 364 /**
728ff21b 365 * Add a grade_grade instance to the grade stack
cf72e2dd 366 *
367 * @param grade_grade $grade Grade object
368 *
369 * @return void
0f5660f7 370 */
728ff21b 371 private function _push($grade) {
0f5660f7 372 array_push($this->gradestack, $grade);
373 }
374
cf72e2dd 375
0f5660f7 376 /**
728ff21b 377 * Remove a grade_grade instance from the grade stack
cf72e2dd 378 *
728ff21b 379 * @return grade_grade current grade object
0f5660f7 380 */
728ff21b 381 private function _pop() {
d24832f9 382 global $DB;
0f5660f7 383 if (empty($this->gradestack)) {
8de7c8a7 384 if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
cf72e2dd 385 return null; // no grades present
0f5660f7 386 }
387
7ce5df86
AD
388 $current = $this->grades_rs->current();
389
390 $this->grades_rs->next();
0f5660f7 391
7ce5df86 392 return $current;
0f5660f7 393 } else {
394 return array_pop($this->gradestack);
395 }
396 }
397}
398
d08bba83 399/**
400 * Print a selection popup form of the graded users in a course.
401 *
4d5059d4
SH
402 * @deprecated since 2.0
403 *
cf72e2dd 404 * @param int $course id of the course
d08bba83 405 * @param string $actionpage The page receiving the data from the popoup form
cf72e2dd 406 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
407 * @param int $groupid id of requested group, 0 means all
408 * @param int $includeall bool include all option
409 * @param bool $return If true, will return the HTML, otherwise, will print directly
d08bba83 410 * @return null
411 */
7ac88172 412function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
714b4745 413 global $CFG, $USER, $OUTPUT;
4d5059d4
SH
414 return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
415}
345674ca 416
4d5059d4 417function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
4e829d48 418 global $USER, $CFG;
f9510667 419
879c99bb 420 if (is_null($userid)) {
421 $userid = $USER->id;
422 }
38c1dd19
RT
423 $coursecontext = context_course::instance($course->id);
424 $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
425 $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
426 $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $coursecontext);
d08bba83 427 $menu = array(); // Will be a list of userid => user name
38c1dd19 428 $menususpendedusers = array(); // Suspended users go to a separate optgroup.
772229f3 429 $gui = new graded_users_iterator($course, null, $groupid);
38c1dd19 430 $gui->require_active_enrolment($showonlyactiveenrol);
d08bba83 431 $gui->init();
10f5c046 432 $label = get_string('selectauser', 'grades');
7ac88172 433 if ($includeall) {
879c99bb 434 $menu[0] = get_string('allusers', 'grades');
10f5c046 435 $label = get_string('selectalloroneuser', 'grades');
d08bba83 436 }
d08bba83 437 while ($userdata = $gui->next_user()) {
438 $user = $userdata->user;
38c1dd19
RT
439 $userfullname = fullname($user);
440 if ($user->suspendedenrolment) {
441 $menususpendedusers[$user->id] = $userfullname;
442 } else {
443 $menu[$user->id] = $userfullname;
444 }
d08bba83 445 }
d08bba83 446 $gui->close();
447
7ac88172 448 if ($includeall) {
38c1dd19
RT
449 $menu[0] .= " (" . (count($menu) + count($menususpendedusers) - 1) . ")";
450 }
451
452 if (!empty($menususpendedusers)) {
453 $menu[] = array(get_string('suspendedusers') => $menususpendedusers);
879c99bb 454 }
4d5059d4 455 $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
f8dab966
PS
456 $select->label = $label;
457 $select->formid = 'choosegradeuser';
4d5059d4 458 return $select;
d08bba83 459}
460
a9937aec
DW
461/**
462 * Hide warning about changed grades during upgrade to 2.8.
463 *
464 * @param int $courseid The current course id.
465 */
466function hide_natural_aggregation_upgrade_notice($courseid) {
467 set_config('show_sumofgrades_upgrade_' . $courseid, false);
468}
469
470/**
471 * Print warning about changed grades during upgrade to 2.8.
472 *
473 * @param int $courseid The current course id.
474 * @param context $context The course context.
475 * @param boolean $return return as string
476 *
477 * @return nothing or string if $return true
478 */
479function print_natural_aggregation_upgrade_notice($courseid, $context, $return=false) {
480 global $OUTPUT;
481 $html = '';
482 $show = get_config('core', 'show_sumofgrades_upgrade_' . $courseid);
483
484 if ($show) {
485 $message = get_string('sumofgradesupgradedgrades', 'grades');
486 $hidemessage = get_string('sumofgradesupgradedgradeshidemessage', 'grades');
487 $urlparams = array( 'id' => $courseid,
488 'seensumofgradesupgradedgrades' => true,
489 'sesskey' => sesskey());
490 $goawayurl = new moodle_url('/grade/report/grader/index.php', $urlparams);
491 $goawaybutton = $OUTPUT->single_button($goawayurl, $hidemessage, 'get');
492 $html .= $OUTPUT->notification($message, 'notifysuccess');
493 $html .= $goawaybutton;
494 }
495
496 if ($return) {
497 return $html;
498 } else {
499 echo $html;
500 }
501}
502
0610812a 503/**
504 * Print grading plugin selection popup form.
505 *
cf72e2dd 506 * @param array $plugin_info An array of plugins containing information for the selector
0610812a 507 * @param boolean $return return as string
cf72e2dd 508 *
0610812a 509 * @return nothing or string if $return true
510 */
f1a3e072 511function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
714b4745 512 global $CFG, $OUTPUT, $PAGE;
dc482cfa 513
514 $menu = array();
515 $count = 0;
516 $active = '';
517
518 foreach ($plugin_info as $plugin_type => $plugins) {
519 if ($plugin_type == 'strings') {
520 continue;
521 }
522
7981d537 523 $first_plugin = reset($plugins);
dc482cfa 524
f1a3e072
PS
525 $sectionname = $plugin_info['strings'][$plugin_type];
526 $section = array();
d4dcfc6b 527
f1a3e072 528 foreach ($plugins as $plugin) {
d4dcfc6b 529 $link = $plugin->link->out(false);
f1a3e072
PS
530 $section[$link] = $plugin->string;
531 $count++;
532 if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
533 $active = $link;
dc482cfa 534 }
535 }
f1a3e072
PS
536
537 if ($section) {
538 $menu[] = array($sectionname=>$section);
539 }
dc482cfa 540 }
541
cf72e2dd 542 // finally print/return the popup form
dc482cfa 543 if ($count > 1) {
f1a3e072 544 $select = new url_select($menu, $active, null, 'choosepluginreport');
29bea634 545 $select->set_label(get_string('gradereport', 'grades'), array('class' => 'accesshide'));
7981d537 546 if ($return) {
f1a3e072 547 return $OUTPUT->render($select);
7981d537 548 } else {
f1a3e072 549 echo $OUTPUT->render($select);
7981d537 550 }
dc482cfa 551 } else {
552 // only one option - no plugin selector needed
553 return '';
554 }
555}
556
557/**
558 * Print grading plugin selection tab-based navigation.
559 *
cf72e2dd 560 * @param string $active_type type of plugin on current page - import, export, report or edit
561 * @param string $active_plugin active plugin type - grader, user, cvs, ...
562 * @param array $plugin_info Array of plugins
dc482cfa 563 * @param boolean $return return as string
cf72e2dd 564 *
dc482cfa 565 * @return nothing or string if $return true
566 */
b827784e 567function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
dc482cfa 568 global $CFG, $COURSE;
1c1f64a2 569
e1513ca9 570 if (!isset($currenttab)) { //TODO: this is weird
dc482cfa 571 $currenttab = '';
572 }
573
574 $tabs = array();
575 $top_row = array();
576 $bottom_row = array();
577 $inactive = array($active_plugin);
578 $activated = array();
579
580 $count = 0;
581 $active = '';
582
583 foreach ($plugin_info as $plugin_type => $plugins) {
584 if ($plugin_type == 'strings') {
585 continue;
586 }
587
588 // If $plugins is actually the definition of a child-less parent link:
cf72e2dd 589 if (!empty($plugins->id)) {
590 $string = $plugins->string;
591 if (!empty($plugin_info[$active_type]->parent)) {
592 $string = $plugin_info[$active_type]->parent->string;
27eef3bb 593 }
594
cf72e2dd 595 $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
dc482cfa 596 continue;
597 }
598
599 $first_plugin = reset($plugins);
cf72e2dd 600 $url = $first_plugin->link;
dc482cfa 601
602 if ($plugin_type == 'report') {
603 $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
604 }
605
606 $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
607
608 if ($active_type == $plugin_type) {
609 foreach ($plugins as $plugin) {
cf72e2dd 610 $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
611 if ($plugin->id == $active_plugin) {
612 $inactive = array($plugin->id);
dc482cfa 613 }
614 }
615 }
616 }
617
618 $tabs[] = $top_row;
619 $tabs[] = $bottom_row;
620
621 if ($return) {
622 return print_tabs($tabs, $active_type, $inactive, $activated, true);
623 } else {
624 print_tabs($tabs, $active_type, $inactive, $activated);
625 }
626}
627
cf72e2dd 628/**
629 * grade_get_plugin_info
630 *
631 * @param int $courseid The course id
632 * @param string $active_type type of plugin on current page - import, export, report or edit
633 * @param string $active_plugin active plugin type - grader, user, cvs, ...
634 *
635 * @return array
636 */
dc482cfa 637function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
f7fcf4cd 638 global $CFG, $SITE;
cbff94ba 639
d4060472 640 $context = context_course::instance($courseid);
cbff94ba 641
dc482cfa 642 $plugin_info = array();
6e2f3121 643 $count = 0;
3af29899 644 $active = '';
dc482cfa 645 $url_prefix = $CFG->wwwroot . '/grade/';
646
647 // Language strings
4d5059d4 648 $plugin_info['strings'] = grade_helper::get_plugin_strings();
b827784e 649
4d5059d4
SH
650 if ($reports = grade_helper::get_plugins_reports($courseid)) {
651 $plugin_info['report'] = $reports;
b827784e 652 }
c46aeeab 653
4d5059d4
SH
654 if ($scale = grade_helper::get_info_scales($courseid)) {
655 $plugin_info['scale'] = array('view'=>$scale);
cbff94ba 656 }
dc482cfa 657
4d5059d4
SH
658 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
659 $plugin_info['outcome'] = $outcomes;
cbff94ba 660 }
cbff94ba 661
4d5059d4
SH
662 if ($letters = grade_helper::get_info_letters($courseid)) {
663 $plugin_info['letter'] = $letters;
cbff94ba 664 }
4d5059d4
SH
665
666 if ($imports = grade_helper::get_plugins_import($courseid)) {
667 $plugin_info['import'] = $imports;
281ffa4a 668 }
c46aeeab 669
4d5059d4
SH
670 if ($exports = grade_helper::get_plugins_export($courseid)) {
671 $plugin_info['export'] = $exports;
281ffa4a 672 }
281ffa4a 673
4d5059d4
SH
674 foreach ($plugin_info as $plugin_type => $plugins) {
675 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
676 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
677 break;
281ffa4a 678 }
4d5059d4
SH
679 foreach ($plugins as $plugin) {
680 if (is_a($plugin, 'grade_plugin_info')) {
681 if ($active_plugin == $plugin->id) {
682 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
683 }
3af29899 684 }
281ffa4a 685 }
cbff94ba 686 }
c46aeeab 687
8faa560c
MG
688 // Hide course settings if we're not in a course
689 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
690 $plugin_info['settings'] = $settings;
281ffa4a 691 }
cbff94ba 692
4d5059d4
SH
693 // Put preferences last
694 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
695 $plugin_info['preferences'] = $preferences;
27eef3bb 696 }
697
dc482cfa 698 foreach ($plugin_info as $plugin_type => $plugins) {
cf72e2dd 699 if (!empty($plugins->id) && $active_plugin == $plugins->id) {
700 $plugin_info['strings']['active_plugin_str'] = $plugins->string;
dc482cfa 701 break;
78ad5f3f 702 }
dc482cfa 703 foreach ($plugins as $plugin) {
cf72e2dd 704 if (is_a($plugin, 'grade_plugin_info')) {
705 if ($active_plugin == $plugin->id) {
706 $plugin_info['strings']['active_plugin_str'] = $plugin->string;
707 }
78ad5f3f 708 }
78ad5f3f 709 }
dc482cfa 710 }
78ad5f3f 711
dc482cfa 712 return $plugin_info;
713}
284abb09 714
cf72e2dd 715/**
716 * A simple class containing info about grade plugins.
717 * Can be subclassed for special rules
718 *
a153c9f2 719 * @package core_grades
cf72e2dd 720 * @copyright 2009 Nicolas Connault
721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
722 */
723class grade_plugin_info {
724 /**
725 * A unique id for this plugin
726 *
727 * @var mixed
728 */
729 public $id;
730 /**
731 * A URL to access this plugin
732 *
733 * @var mixed
734 */
735 public $link;
736 /**
737 * The name of this plugin
738 *
739 * @var mixed
740 */
741 public $string;
742 /**
743 * Another grade_plugin_info object, parent of the current one
744 *
745 * @var mixed
746 */
747 public $parent;
748
749 /**
750 * Constructor
751 *
752 * @param int $id A unique id for this plugin
753 * @param string $link A URL to access this plugin
754 * @param string $string The name of this plugin
755 * @param object $parent Another grade_plugin_info object, parent of the current one
756 *
757 * @return void
758 */
759 public function __construct($id, $link, $string, $parent=null) {
760 $this->id = $id;
761 $this->link = $link;
762 $this->string = $string;
763 $this->parent = $parent;
764 }
765}
766
de0300ea 767/**
768 * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
769 * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
770 * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
771 * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
772 * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
773 *
cf72e2dd 774 * @param int $courseid Course id
775 * @param string $active_type The type of the current page (report, settings,
776 * import, export, scales, outcomes, letters)
777 * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
778 * @param string $heading The heading of the page. Tries to guess if none is given
de0300ea 779 * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
cf72e2dd 780 * @param string $bodytags Additional attributes that will be added to the <body> tag
781 * @param string $buttons Additional buttons to display on the page
5625d33d 782 * @param boolean $shownavigation should the gradebook navigation drop down (or tabs) be shown?
de0300ea 783 *
784 * @return string HTML code or nothing if $return == false
785 */
cf72e2dd 786function print_grade_page_head($courseid, $active_type, $active_plugin=null,
34a2777c 787 $heading = false, $return=false,
2821c495 788 $buttons=false, $shownavigation=true) {
4d5059d4 789 global $CFG, $OUTPUT, $PAGE;
c46aeeab 790
dc482cfa 791 $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
c46aeeab 792
dc482cfa 793 // Determine the string of the active plugin
794 $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
795 $stractive_type = $plugin_info['strings'][$active_type];
e0724506 796
cf72e2dd 797 if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
4d5059d4
SH
798 $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
799 } else {
800 $title = $PAGE->course->fullname.': ' . $stractive_plugin;
c4c97a6d 801 }
802
367a75fa
SH
803 if ($active_type == 'report') {
804 $PAGE->set_pagelayout('report');
805 } else {
806 $PAGE->set_pagelayout('admin');
807 }
4d5059d4 808 $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
f3df5e14 809 $PAGE->set_heading($title);
4d5059d4
SH
810 if ($buttons instanceof single_button) {
811 $buttons = $OUTPUT->render($buttons);
812 }
f3df5e14 813 $PAGE->set_button($buttons);
6bf696bb
MG
814 if ($courseid != SITEID) {
815 grade_extend_settings($plugin_info, $courseid);
816 }
4d5059d4 817
f3df5e14 818 $returnval = $OUTPUT->header();
819 if (!$return) {
820 echo $returnval;
821 }
dc482cfa 822
823 // Guess heading if not given explicitly
824 if (!$heading) {
825 $heading = $stractive_plugin;
826 }
827
2821c495 828 if ($shownavigation) {
6bf696bb
MG
829 if ($courseid != SITEID &&
830 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN)) {
2821c495
AD
831 $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
832 }
5625d33d
AD
833
834 if ($return) {
835 $returnval .= $OUTPUT->heading($heading);
836 } else {
e59a1dd6 837 echo $OUTPUT->heading($heading);
5625d33d
AD
838 }
839
6bf696bb
MG
840 if ($courseid != SITEID &&
841 ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS)) {
2821c495
AD
842 $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
843 }
8354e716 844 }
dc482cfa 845
846 if ($return) {
847 return $returnval;
6e2f3121 848 }
cbff94ba 849}
850
0610812a 851/**
7a6b7acf 852 * Utility class used for return tracking when using edit and other forms in grade plugins
cf72e2dd 853 *
a153c9f2 854 * @package core_grades
cf72e2dd 855 * @copyright 2009 Nicolas Connault
856 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
0610812a 857 */
3af29899 858class grade_plugin_return {
d24832f9 859 public $type;
860 public $plugin;
861 public $courseid;
862 public $userid;
863 public $page;
281ffa4a 864
0610812a 865 /**
866 * Constructor
cf72e2dd 867 *
0610812a 868 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
869 */
cf72e2dd 870 public function grade_plugin_return($params = null) {
3af29899 871 if (empty($params)) {
872 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
aff24313 873 $this->plugin = optional_param('gpr_plugin', null, PARAM_PLUGIN);
3af29899 874 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
875 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
876 $this->page = optional_param('gpr_page', null, PARAM_INT);
a983b6ec 877
a983b6ec 878 } else {
3af29899 879 foreach ($params as $key=>$value) {
4cc977a6 880 if (property_exists($this, $key)) {
3af29899 881 $this->$key = $value;
882 }
cbff94ba 883 }
884 }
6cd8c592 885 }
886
0610812a 887 /**
888 * Returns return parameters as options array suitable for buttons.
889 * @return array options
890 */
d24832f9 891 public function get_options() {
7a6b7acf 892 if (empty($this->type)) {
3af29899 893 return array();
865e9a82 894 }
6cd8c592 895
3af29899 896 $params = array();
6cd8c592 897
7a6b7acf 898 if (!empty($this->plugin)) {
899 $params['plugin'] = $this->plugin;
900 }
6cd8c592 901
3af29899 902 if (!empty($this->courseid)) {
903 $params['id'] = $this->courseid;
6cd8c592 904 }
9c61ba4d 905
3af29899 906 if (!empty($this->userid)) {
907 $params['userid'] = $this->userid;
9c61ba4d 908 }
9c61ba4d 909
3af29899 910 if (!empty($this->page)) {
911 $params['page'] = $this->page;
cbff94ba 912 }
865e9a82 913
3af29899 914 return $params;
cbff94ba 915 }
cbff94ba 916
0610812a 917 /**
918 * Returns return url
cf72e2dd 919 *
0610812a 920 * @param string $default default url when params not set
cf72e2dd 921 * @param array $extras Extra URL parameters
922 *
0610812a 923 * @return string url
924 */
d24832f9 925 public function get_return_url($default, $extras=null) {
3af29899 926 global $CFG;
cbff94ba 927
3af29899 928 if (empty($this->type) or empty($this->plugin)) {
929 return $default;
cbff94ba 930 }
931
65dd61bd 932 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
933 $glue = '?';
cbff94ba 934
3af29899 935 if (!empty($this->courseid)) {
936 $url .= $glue.'id='.$this->courseid;
937 $glue = '&amp;';
cbff94ba 938 }
cbff94ba 939
3af29899 940 if (!empty($this->userid)) {
941 $url .= $glue.'userid='.$this->userid;
942 $glue = '&amp;';
cbff94ba 943 }
7e2d7c92 944
3af29899 945 if (!empty($this->page)) {
946 $url .= $glue.'page='.$this->page;
65dd61bd 947 $glue = '&amp;';
948 }
949
950 if (!empty($extras)) {
cf72e2dd 951 foreach ($extras as $key=>$value) {
65dd61bd 952 $url .= $glue.$key.'='.$value;
953 $glue = '&amp;';
7a6b7acf 954 }
cbff94ba 955 }
cbff94ba 956
3af29899 957 return $url;
cbff94ba 958 }
cbff94ba 959
0610812a 960 /**
961 * Returns string with hidden return tracking form elements.
962 * @return string
963 */
d24832f9 964 public function get_form_fields() {
7a6b7acf 965 if (empty($this->type)) {
3af29899 966 return '';
cbff94ba 967 }
cbff94ba 968
3af29899 969 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
7a6b7acf 970
971 if (!empty($this->plugin)) {
972 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
973 }
0ca5abd6 974
3af29899 975 if (!empty($this->courseid)) {
976 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
cbff94ba 977 }
cbff94ba 978
3af29899 979 if (!empty($this->userid)) {
980 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
cbff94ba 981 }
cbff94ba 982
3af29899 983 if (!empty($this->page)) {
984 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
cbff94ba 985 }
986 }
cbff94ba 987
0610812a 988 /**
989 * Add hidden elements into mform
cf72e2dd 990 *
991 * @param object &$mform moodle form object
992 *
0610812a 993 * @return void
994 */
d24832f9 995 public function add_mform_elements(&$mform) {
7a6b7acf 996 if (empty($this->type)) {
3af29899 997 return;
cbff94ba 998 }
cbff94ba 999
3af29899 1000 $mform->addElement('hidden', 'gpr_type', $this->type);
1001 $mform->setType('gpr_type', PARAM_SAFEDIR);
cbff94ba 1002
7a6b7acf 1003 if (!empty($this->plugin)) {
1004 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
aff24313 1005 $mform->setType('gpr_plugin', PARAM_PLUGIN);
7a6b7acf 1006 }
97033c86 1007
3af29899 1008 if (!empty($this->courseid)) {
1009 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
1010 $mform->setType('gpr_courseid', PARAM_INT);
cbff94ba 1011 }
cbff94ba 1012
3af29899 1013 if (!empty($this->userid)) {
1014 $mform->addElement('hidden', 'gpr_userid', $this->userid);
1015 $mform->setType('gpr_userid', PARAM_INT);
cbff94ba 1016 }
cbff94ba 1017
3af29899 1018 if (!empty($this->page)) {
1019 $mform->addElement('hidden', 'gpr_page', $this->page);
1020 $mform->setType('gpr_page', PARAM_INT);
cbff94ba 1021 }
1022 }
281ffa4a 1023
0610812a 1024 /**
1025 * Add return tracking params into url
cf72e2dd 1026 *
1c1f64a2 1027 * @param moodle_url $url A URL
cf72e2dd 1028 *
6ef4878b 1029 * @return string $url with return tracking params
0610812a 1030 */
1c1f64a2 1031 public function add_url_params(moodle_url $url) {
7a6b7acf 1032 if (empty($this->type)) {
3af29899 1033 return $url;
cbff94ba 1034 }
5609f9e6 1035
1c1f64a2 1036 $url->param('gpr_type', $this->type);
cbff94ba 1037
7a6b7acf 1038 if (!empty($this->plugin)) {
1c1f64a2 1039 $url->param('gpr_plugin', $this->plugin);
7a6b7acf 1040 }
cbff94ba 1041
3af29899 1042 if (!empty($this->courseid)) {
1c1f64a2 1043 $url->param('gpr_courseid' ,$this->courseid);
cbff94ba 1044 }
cbff94ba 1045
3af29899 1046 if (!empty($this->userid)) {
1c1f64a2 1047 $url->param('gpr_userid', $this->userid);
cbff94ba 1048 }
0a8a95c9 1049
3af29899 1050 if (!empty($this->page)) {
1c1f64a2 1051 $url->param('gpr_page', $this->page);
0a8a95c9 1052 }
5a412dbf 1053
3af29899 1054 return $url;
5a412dbf 1055 }
5a412dbf 1056}
7a6b7acf 1057
826c5f86 1058/**
1059 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
cf72e2dd 1060 *
826c5f86 1061 * @param string $path The path of the calling script (using __FILE__?)
1062 * @param string $pagename The language string to use as the last part of the navigation (non-link)
cf72e2dd 1063 * @param mixed $id Either a plain integer (assuming the key is 'id') or
1064 * an array of keys and values (e.g courseid => $courseid, itemid...)
1065 *
826c5f86 1066 * @return string
1067 */
1068function grade_build_nav($path, $pagename=null, $id=null) {
f3df5e14 1069 global $CFG, $COURSE, $PAGE;
826c5f86 1070
1071 $strgrades = get_string('grades', 'grades');
1072
1073 // Parse the path and build navlinks from its elements
1074 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
1075 $path = substr($path, $dirroot_length);
1076 $path = str_replace('\\', '/', $path);
1077
1078 $path_elements = explode('/', $path);
1079
1080 $path_elements_count = count($path_elements);
1081
826c5f86 1082 // First link is always 'grade'
a6855934 1083 $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
826c5f86 1084
f3df5e14 1085 $link = null;
826c5f86 1086 $numberofelements = 3;
1087
1088 // Prepare URL params string
f3df5e14 1089 $linkparams = array();
826c5f86 1090 if (!is_null($id)) {
1091 if (is_array($id)) {
1092 foreach ($id as $idkey => $idvalue) {
f3df5e14 1093 $linkparams[$idkey] = $idvalue;
826c5f86 1094 }
1095 } else {
f3df5e14 1096 $linkparams['id'] = $id;
826c5f86 1097 }
1098 }
1099
1100 $navlink4 = null;
1101
0f78c4de 1102 // Remove file extensions from filenames
1103 foreach ($path_elements as $key => $filename) {
1104 $path_elements[$key] = str_replace('.php', '', $filename);
1105 }
1106
826c5f86 1107 // Second level links
1108 switch ($path_elements[1]) {
1109 case 'edit': // No link
1110 if ($path_elements[3] != 'index.php') {
1111 $numberofelements = 4;
1112 }
1113 break;
1114 case 'import': // No link
1115 break;
1116 case 'export': // No link
1117 break;
1118 case 'report':
1119 // $id is required for this link. Do not print it if $id isn't given
1120 if (!is_null($id)) {
a6855934 1121 $link = new moodle_url('/grade/report/index.php', $linkparams);
826c5f86 1122 }
1123
1124 if ($path_elements[2] == 'grader') {
1125 $numberofelements = 4;
1126 }
1127 break;
1128
1129 default:
1130 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
cf72e2dd 1131 debugging("grade_build_nav() doesn't support ". $path_elements[1] .
1132 " as the second path element after 'grade'.");
826c5f86 1133 return false;
1134 }
f3df5e14 1135 $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
826c5f86 1136
1137 // Third level links
1138 if (empty($pagename)) {
1139 $pagename = get_string($path_elements[2], 'grades');
1140 }
1141
1142 switch ($numberofelements) {
1143 case 3:
f3df5e14 1144 $PAGE->navbar->add($pagename, $link);
826c5f86 1145 break;
1146 case 4:
826c5f86 1147 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
b5e7b2bf 1148 $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
826c5f86 1149 }
f3df5e14 1150 $PAGE->navbar->add($pagename);
826c5f86 1151 break;
1152 }
826c5f86 1153
f3df5e14 1154 return '';
d4795a07 1155}
7a6b7acf 1156
e98871a2 1157/**
6cc3e350 1158 * General structure representing grade items in course
cf72e2dd 1159 *
a153c9f2 1160 * @package core_grades
cf72e2dd 1161 * @copyright 2009 Nicolas Connault
1162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e98871a2 1163 */
6cc3e350 1164class grade_structure {
d24832f9 1165 public $context;
e98871a2 1166
d24832f9 1167 public $courseid;
e98871a2 1168
73ca5f01 1169 /**
1170 * Reference to modinfo for current course (for performance, to save
1171 * retrieving it from courseid every time). Not actually set except for
1172 * the grade_tree type.
1173 * @var course_modinfo
1174 */
1175 public $modinfo;
1176
e98871a2 1177 /**
1178 * 1D array of grade items only
1179 */
d24832f9 1180 public $items;
e98871a2 1181
6391ebe7 1182 /**
6cc3e350 1183 * Returns icon of element
cf72e2dd 1184 *
1185 * @param array &$element An array representing an element in the grade_tree
1186 * @param bool $spacerifnone return spacer if no icon found
1187 *
6cc3e350 1188 * @return string icon or spacer
6391ebe7 1189 */
d24832f9 1190 public function get_element_icon(&$element, $spacerifnone=false) {
6b608f8f 1191 global $CFG, $OUTPUT;
559276b1 1192 require_once $CFG->libdir.'/filelib.php';
6cc3e350 1193
1194 switch ($element['type']) {
1195 case 'item':
1196 case 'courseitem':
1197 case 'categoryitem':
cf72e2dd 1198 $is_course = $element['object']->is_course_item();
1199 $is_category = $element['object']->is_category_item();
1200 $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
1201 $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
0077f571 1202 $is_outcome = !empty($element['object']->outcomeid);
cf72e2dd 1203
6cc3e350 1204 if ($element['object']->is_calculated()) {
dc482cfa 1205 $strcalc = get_string('calculatedgrade', 'grades');
b5d0cafc 1206 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
cf72e2dd 1207 s($strcalc).'" alt="'.s($strcalc).'"/>';
6cc3e350 1208
cf72e2dd 1209 } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
6cc3e350 1210 if ($category = $element['object']->get_item_category()) {
bfe969e8
DW
1211 $aggrstrings = grade_helper::get_aggregation_strings();
1212 $stragg = $aggrstrings[$category->aggregation];
6cc3e350 1213 switch ($category->aggregation) {
1214 case GRADE_AGGREGATE_MEAN:
1215 case GRADE_AGGREGATE_MEDIAN:
1216 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1426edac 1217 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
6cc3e350 1218 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
b5d0cafc 1219 return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
cf72e2dd 1220 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
0758a08e 1221 case GRADE_AGGREGATE_SUM:
b5d0cafc 1222 return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
cf72e2dd 1223 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
9dd80882
DW
1224 default:
1225 return '<img src="'.$OUTPUT->pix_url('i/calc') . '" ' .
1226 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
6cc3e350 1227 }
1228 }
1229
1230 } else if ($element['object']->itemtype == 'mod') {
0077f571
AD
1231 //prevent outcomes being displaying the same icon as the activity they are attached to
1232 if ($is_outcome) {
1233 $stroutcome = s(get_string('outcome', 'grades'));
1234 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
1235 'class="icon itemicon" title="'.$stroutcome.
1236 '" alt="'.$stroutcome.'"/>';
1237 } else {
1238 $strmodname = get_string('modulename', $element['object']->itemmodule);
1239 return '<img src="'.$OUTPUT->pix_url('icon',
e63f88c9 1240 $element['object']->itemmodule) . '" ' .
cf72e2dd 1241 'class="icon itemicon" title="' .s($strmodname).
1242 '" alt="' .s($strmodname).'"/>';
0077f571 1243 }
6cc3e350 1244 } else if ($element['object']->itemtype == 'manual') {
1245 if ($element['object']->is_outcome_item()) {
dc482cfa 1246 $stroutcome = get_string('outcome', 'grades');
b5d0cafc 1247 return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
cf72e2dd 1248 'class="icon itemicon" title="'.s($stroutcome).
1249 '" alt="'.s($stroutcome).'"/>';
6cc3e350 1250 } else {
dc482cfa 1251 $strmanual = get_string('manualitem', 'grades');
0cddd851 1252 return '<img src="'.$OUTPUT->pix_url('i/manual_item') . '" '.
cf72e2dd 1253 'class="icon itemicon" title="'.s($strmanual).
1254 '" alt="'.s($strmanual).'"/>';
6cc3e350 1255 }
1256 }
1257 break;
1258
1259 case 'category':
dc482cfa 1260 $strcat = get_string('category', 'grades');
0cddd851 1261 return '<img src="'.$OUTPUT->pix_url('i/folder') . '" class="icon itemicon" ' .
cf72e2dd 1262 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
6cc3e350 1263 }
1264
1265 if ($spacerifnone) {
b11681e0 1266 return $OUTPUT->spacer().' ';
6cc3e350 1267 } else {
1268 return '';
1269 }
1270 }
6391ebe7 1271
e98871a2 1272 /**
6cc3e350 1273 * Returns name of element optionally with icon and link
cf72e2dd 1274 *
1275 * @param array &$element An array representing an element in the grade_tree
1276 * @param bool $withlink Whether or not this header has a link
1277 * @param bool $icon Whether or not to display an icon with this header
1278 * @param bool $spacerifnone return spacer if no icon found
65c2ac93 1279 * @param bool $withdescription Show description if defined by this item.
cf72e2dd 1280 *
1281 * @return string header
e98871a2 1282 */
65c2ac93 1283 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false, $withdescription=false) {
6cc3e350 1284 $header = '';
1285
1286 if ($icon) {
1287 $header .= $this->get_element_icon($element, $spacerifnone);
1288 }
1289
dc482cfa 1290 $header .= $element['object']->get_name();
6cc3e350 1291
cf72e2dd 1292 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
1293 $element['type'] != 'courseitem') {
6cc3e350 1294 return $header;
1295 }
1296
73ca5f01 1297 if ($withlink) {
1298 $url = $this->get_activity_link($element);
1299 if ($url) {
ace9051c 1300 $a = new stdClass();
45a639d5 1301 $a->name = get_string('modulename', $element['object']->itemmodule);
dc482cfa 1302 $title = get_string('linktoactivity', 'grades', $a);
6cc3e350 1303
73ca5f01 1304 $header = html_writer::link($url, $header, array('title' => $title));
46d1af82 1305 }
6cc3e350 1306 }
1307
65c2ac93
DW
1308 if ($withdescription) {
1309 $desc = $element['object']->get_description();
1310 if (!empty($desc)) {
1311 $header .= '<div class="gradeitemdescription">' . s($desc) . '</div><div class="gradeitemdescriptionfiller"></div>';
1312 }
1313 }
1314
6cc3e350 1315 return $header;
1316 }
1317
73ca5f01 1318 private function get_activity_link($element) {
1319 global $CFG;
eff314b0
DM
1320 /** @var array static cache of the grade.php file existence flags */
1321 static $hasgradephp = array();
73ca5f01 1322
1323 $itemtype = $element['object']->itemtype;
1324 $itemmodule = $element['object']->itemmodule;
1325 $iteminstance = $element['object']->iteminstance;
25ab1d50 1326 $itemnumber = $element['object']->itemnumber;
73ca5f01 1327
1328 // Links only for module items that have valid instance, module and are
1329 // called from grade_tree with valid modinfo
1330 if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
1331 return null;
1332 }
1333
1334 // Get $cm efficiently and with visibility information using modinfo
1335 $instances = $this->modinfo->get_instances();
1336 if (empty($instances[$itemmodule][$iteminstance])) {
1337 return null;
1338 }
1339 $cm = $instances[$itemmodule][$iteminstance];
1340
1341 // Do not add link if activity is not visible to the current user
1342 if (!$cm->uservisible) {
1343 return null;
1344 }
1345
eff314b0
DM
1346 if (!array_key_exists($itemmodule, $hasgradephp)) {
1347 if (file_exists($CFG->dirroot . '/mod/' . $itemmodule . '/grade.php')) {
1348 $hasgradephp[$itemmodule] = true;
1349 } else {
1350 $hasgradephp[$itemmodule] = false;
1351 }
1352 }
1353
73ca5f01 1354 // If module has grade.php, link to that, otherwise view.php
eff314b0 1355 if ($hasgradephp[$itemmodule]) {
c97933ff
MG
1356 $args = array('id' => $cm->id, 'itemnumber' => $itemnumber);
1357 if (isset($element['userid'])) {
1358 $args['userid'] = $element['userid'];
1359 }
1360 return new moodle_url('/mod/' . $itemmodule . '/grade.php', $args);
73ca5f01 1361 } else {
1362 return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
1363 }
1364 }
1365
bb17ac1e
DM
1366 /**
1367 * Returns URL of a page that is supposed to contain detailed grade analysis
1368 *
bb17ac1e
DM
1369 * At the moment, only activity modules are supported. The method generates link
1370 * to the module's file grade.php with the parameters id (cmid), itemid, itemnumber,
eff314b0 1371 * gradeid and userid. If the grade.php does not exist, null is returned.
bb17ac1e
DM
1372 *
1373 * @return moodle_url|null URL or null if unable to construct it
1374 */
1375 public function get_grade_analysis_url(grade_grade $grade) {
eff314b0
DM
1376 global $CFG;
1377 /** @var array static cache of the grade.php file existence flags */
1378 static $hasgradephp = array();
bb17ac1e
DM
1379
1380 if (empty($grade->grade_item) or !($grade->grade_item instanceof grade_item)) {
1381 throw new coding_exception('Passed grade without the associated grade item');
1382 }
1383 $item = $grade->grade_item;
1384
1385 if (!$item->is_external_item()) {
1386 // at the moment, only activity modules are supported
1387 return null;
1388 }
1389 if ($item->itemtype !== 'mod') {
1390 throw new coding_exception('Unknown external itemtype: '.$item->itemtype);
1391 }
1392 if (empty($item->iteminstance) or empty($item->itemmodule) or empty($this->modinfo)) {
1393 return null;
1394 }
1395
eff314b0
DM
1396 if (!array_key_exists($item->itemmodule, $hasgradephp)) {
1397 if (file_exists($CFG->dirroot . '/mod/' . $item->itemmodule . '/grade.php')) {
1398 $hasgradephp[$item->itemmodule] = true;
1399 } else {
1400 $hasgradephp[$item->itemmodule] = false;
1401 }
1402 }
1403
1404 if (!$hasgradephp[$item->itemmodule]) {
1405 return null;
1406 }
1407
bb17ac1e
DM
1408 $instances = $this->modinfo->get_instances();
1409 if (empty($instances[$item->itemmodule][$item->iteminstance])) {
1410 return null;
1411 }
1412 $cm = $instances[$item->itemmodule][$item->iteminstance];
1413 if (!$cm->uservisible) {
1414 return null;
1415 }
1416
1417 $url = new moodle_url('/mod/'.$item->itemmodule.'/grade.php', array(
1418 'id' => $cm->id,
1419 'itemid' => $item->id,
1420 'itemnumber' => $item->itemnumber,
1421 'gradeid' => $grade->id,
1422 'userid' => $grade->userid,
1423 ));
1424
1425 return $url;
1426 }
1427
1428 /**
1429 * Returns an action icon leading to the grade analysis page
1430 *
1431 * @param grade_grade $grade
1432 * @return string
1433 */
1434 public function get_grade_analysis_icon(grade_grade $grade) {
1435 global $OUTPUT;
1436
1437 $url = $this->get_grade_analysis_url($grade);
1438 if (is_null($url)) {
1439 return '';
1440 }
1441
c97933ff 1442 return $OUTPUT->action_icon($url, new pix_icon('t/preview',
bb17ac1e
DM
1443 get_string('gradeanalysis', 'core_grades')));
1444 }
1445
6cc3e350 1446 /**
1447 * Returns the grade eid - the grade may not exist yet.
cf72e2dd 1448 *
1449 * @param grade_grade $grade_grade A grade_grade object
1450 *
6cc3e350 1451 * @return string eid
1452 */
d24832f9 1453 public function get_grade_eid($grade_grade) {
6cc3e350 1454 if (empty($grade_grade->id)) {
1455 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
1456 } else {
1457 return 'g'.$grade_grade->id;
1458 }
1459 }
1460
1461 /**
1462 * Returns the grade_item eid
cf72e2dd 1463 * @param grade_item $grade_item A grade_item object
6cc3e350 1464 * @return string eid
1465 */
d24832f9 1466 public function get_item_eid($grade_item) {
ddb9c95f 1467 return 'ig'.$grade_item->id;
6cc3e350 1468 }
1469
cf72e2dd 1470 /**
1471 * Given a grade_tree element, returns an array of parameters
1472 * used to build an icon for that element.
1473 *
1474 * @param array $element An array representing an element in the grade_tree
1475 *
1476 * @return array
1477 */
1478 public function get_params_for_iconstr($element) {
9ecd4386 1479 $strparams = new stdClass();
1480 $strparams->category = '';
1481 $strparams->itemname = '';
1482 $strparams->itemmodule = '';
cf72e2dd 1483
9ecd4386 1484 if (!method_exists($element['object'], 'get_name')) {
1485 return $strparams;
1486 }
345674ca 1487
b285c5aa 1488 $strparams->itemname = html_to_text($element['object']->get_name());
9ecd4386 1489
1490 // If element name is categorytotal, get the name of the parent category
1491 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
1492 $parent = $element['object']->get_parent_category();
1493 $strparams->category = $parent->get_name() . ' ';
1494 } else {
1495 $strparams->category = '';
1496 }
1497
1498 $strparams->itemmodule = null;
1499 if (isset($element['object']->itemmodule)) {
1500 $strparams->itemmodule = $element['object']->itemmodule;
345674ca 1501 }
9ecd4386 1502 return $strparams;
1503 }
1504
ae93f353
FM
1505 /**
1506 * Return a reset icon for the given element.
1507 *
1508 * @param array $element An array representing an element in the grade_tree
1509 * @param object $gpr A grade_plugin_return object
1510 * @return string
1511 */
1512 public function get_reset_icon($element, $gpr) {
1513 global $CFG, $OUTPUT;
1514
1515 // Limit to category items set to use the natural weights aggregation method, and users
1516 // with the capability to manage grades.
1517 if ($element['type'] != 'category' || $element['object']->aggregation != GRADE_AGGREGATE_SUM ||
1518 !has_capability('moodle/grade:manage', $this->context)) {
1519 return '';
1520 }
1521
1522 $str = get_string('resetweights', 'grades', $this->get_params_for_iconstr($element));
1523 $url = new moodle_url('/grade/edit/tree/action.php', array(
1524 'id' => $this->courseid,
1525 'action' => 'resetweights',
1526 'eid' => $element['eid'],
1527 'sesskey' => sesskey(),
1528 ));
1529
1530 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/reset', $str));
1531 }
1532
6cc3e350 1533 /**
1534 * Return edit icon for give element
cf72e2dd 1535 *
1536 * @param array $element An array representing an element in the grade_tree
1537 * @param object $gpr A grade_plugin_return object
1538 *
6cc3e350 1539 * @return string
1540 */
d24832f9 1541 public function get_edit_icon($element, $gpr) {
6b608f8f 1542 global $CFG, $OUTPUT;
6cc3e350 1543
1544 if (!has_capability('moodle/grade:manage', $this->context)) {
1545 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
1546 // oki - let them override grade
1547 } else {
1548 return '';
1549 }
1550 }
1551
05aba805 1552 static $strfeedback = null;
1553 static $streditgrade = null;
1554 if (is_null($streditgrade)) {
1555 $streditgrade = get_string('editgrade', 'grades');
1556 $strfeedback = get_string('feedback');
6cc3e350 1557 }
1558
9ecd4386 1559 $strparams = $this->get_params_for_iconstr($element);
6ef4878b 1560
6cc3e350 1561 $object = $element['object'];
6cc3e350 1562
1563 switch ($element['type']) {
1564 case 'item':
1565 case 'categoryitem':
1566 case 'courseitem':
9ecd4386 1567 $stredit = get_string('editverbose', 'grades', $strparams);
6cc3e350 1568 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
a6855934 1569 $url = new moodle_url('/grade/edit/tree/item.php',
1c1f64a2 1570 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1571 } else {
a6855934 1572 $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
1c1f64a2 1573 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1574 }
6cc3e350 1575 break;
1576
1577 case 'category':
9ecd4386 1578 $stredit = get_string('editverbose', 'grades', $strparams);
a6855934 1579 $url = new moodle_url('/grade/edit/tree/category.php',
1c1f64a2 1580 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1581 break;
1582
1583 case 'grade':
05aba805 1584 $stredit = $streditgrade;
6cc3e350 1585 if (empty($object->id)) {
a6855934 1586 $url = new moodle_url('/grade/edit/tree/grade.php',
1c1f64a2 1587 array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
6cc3e350 1588 } else {
a6855934 1589 $url = new moodle_url('/grade/edit/tree/grade.php',
1c1f64a2 1590 array('courseid' => $this->courseid, 'id' => $object->id));
6cc3e350 1591 }
6cc3e350 1592 if (!empty($object->feedback)) {
1593 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
6cc3e350 1594 }
1595 break;
1596
1597 default:
1598 $url = null;
1599 }
1600
1601 if ($url) {
c63923bd 1602 return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
6cc3e350 1603
1604 } else {
1605 return '';
1606 }
1607 }
1608
1609 /**
1610 * Return hiding icon for give element
cf72e2dd 1611 *
1612 * @param array $element An array representing an element in the grade_tree
1613 * @param object $gpr A grade_plugin_return object
1614 *
6cc3e350 1615 * @return string
1616 */
d24832f9 1617 public function get_hiding_icon($element, $gpr) {
5d3b9994 1618 global $CFG, $OUTPUT;
6cc3e350 1619
39873128
TH
1620 if (!$element['object']->can_control_visibility()) {
1621 return '';
1622 }
1623
cf72e2dd 1624 if (!has_capability('moodle/grade:manage', $this->context) and
1625 !has_capability('moodle/grade:hide', $this->context)) {
6cc3e350 1626 return '';
1627 }
1628
345674ca 1629 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1630 $strshow = get_string('showverbose', 'grades', $strparams);
345674ca 1631 $strhide = get_string('hideverbose', 'grades', $strparams);
6cc3e350 1632
a6855934 1633 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
8ae8bf8a 1634 $url = $gpr->add_url_params($url);
1c1f64a2 1635
6cc3e350 1636 if ($element['object']->is_hidden()) {
8ae8bf8a 1637 $type = 'show';
6cc3e350 1638 $tooltip = $strshow;
1639
cf72e2dd 1640 // Change the icon and add a tooltip showing the date
1641 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
8ae8bf8a 1642 $type = 'hiddenuntil';
cf72e2dd 1643 $tooltip = get_string('hiddenuntildate', 'grades',
1644 userdate($element['object']->get_hidden()));
6cc3e350 1645 }
1646
8ae8bf8a 1647 $url->param('action', 'show');
b9cc756e 1648
a377cc53 1649 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'smallicon')));
6cc3e350 1650
1651 } else {
8ae8bf8a 1652 $url->param('action', 'hide');
c63923bd 1653 $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
6cc3e350 1654 }
1c1f64a2 1655
8ae8bf8a 1656 return $hideicon;
6cc3e350 1657 }
1658
1659 /**
2673c733 1660 * Return locking icon for given element
cf72e2dd 1661 *
1662 * @param array $element An array representing an element in the grade_tree
1663 * @param object $gpr A grade_plugin_return object
1664 *
6cc3e350 1665 * @return string
1666 */
d24832f9 1667 public function get_locking_icon($element, $gpr) {
6b608f8f 1668 global $CFG, $OUTPUT;
6cc3e350 1669
345674ca 1670 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1671 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1672 $strlock = get_string('lockverbose', 'grades', $strparams);
d24832f9 1673
a6855934 1674 $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
8ae8bf8a 1675 $url = $gpr->add_url_params($url);
1c1f64a2 1676
2673c733 1677 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1678 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1679 $strparamobj = new stdClass();
1680 $strparamobj->itemname = $element['object']->grade_item->itemname;
1681 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
1c1f64a2 1682
0cddd851
FM
1683 $action = html_writer::tag('span', $OUTPUT->pix_icon('t/locked', $strnonunlockable),
1684 array('class' => 'action-icon'));
8ae8bf8a 1685
cf72e2dd 1686 } else if ($element['object']->is_locked()) {
8ae8bf8a 1687 $type = 'unlock';
6cc3e350 1688 $tooltip = $strunlock;
1689
cf72e2dd 1690 // Change the icon and add a tooltip showing the date
1691 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
8ae8bf8a 1692 $type = 'locktime';
cf72e2dd 1693 $tooltip = get_string('locktimedate', 'grades',
1694 userdate($element['object']->get_locktime()));
6cc3e350 1695 }
1696
8ae8bf8a
PS
1697 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1698 $action = '';
1699 } else {
1700 $url->param('action', 'unlock');
c63923bd 1701 $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
6cc3e350 1702 }
6cc3e350 1703
1704 } else {
8ae8bf8a
PS
1705 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1706 $action = '';
1707 } else {
1708 $url->param('action', 'lock');
c63923bd 1709 $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
6cc3e350 1710 }
6cc3e350 1711 }
8ae8bf8a 1712
6cc3e350 1713 return $action;
1714 }
1715
1716 /**
1717 * Return calculation icon for given element
cf72e2dd 1718 *
1719 * @param array $element An array representing an element in the grade_tree
1720 * @param object $gpr A grade_plugin_return object
1721 *
6cc3e350 1722 * @return string
1723 */
d24832f9 1724 public function get_calculation_icon($element, $gpr) {
666e8458 1725 global $CFG, $OUTPUT;
6cc3e350 1726 if (!has_capability('moodle/grade:manage', $this->context)) {
1727 return '';
1728 }
1729
6cc3e350 1730 $type = $element['type'];
1731 $object = $element['object'];
1732
1733 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
345674ca 1734 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1735 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
6cc3e350 1736
cf72e2dd 1737 $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
1738 $is_value = $object->gradetype == GRADE_TYPE_VALUE;
1739
6cc3e350 1740 // show calculation icon only when calculation possible
cf72e2dd 1741 if (!$object->is_external_item() and ($is_scale or $is_value)) {
6cc3e350 1742 if ($object->is_calculated()) {
666e8458 1743 $icon = 't/calc';
6cc3e350 1744 } else {
666e8458 1745 $icon = 't/calc_off';
6cc3e350 1746 }
cf72e2dd 1747
a6855934 1748 $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
8ae8bf8a 1749 $url = $gpr->add_url_params($url);
0cddd851 1750 return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation));
6cc3e350 1751 }
1752 }
1753
1c1f64a2 1754 return '';
6cc3e350 1755 }
1756}
1757
1758/**
1759 * Flat structure similar to grade tree.
cf72e2dd 1760 *
1761 * @uses grade_structure
a153c9f2 1762 * @package core_grades
cf72e2dd 1763 * @copyright 2009 Nicolas Connault
1764 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6cc3e350 1765 */
1766class grade_seq extends grade_structure {
1767
6cc3e350 1768 /**
1769 * 1D array of elements
1770 */
d24832f9 1771 public $elements;
e98871a2 1772
1773 /**
1774 * Constructor, retrieves and stores array of all grade_category and grade_item
1775 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 1776 *
1777 * @param int $courseid The course id
1778 * @param bool $category_grade_last category grade item is the last child
1779 * @param bool $nooutcomes Whether or not outcomes should be included
e98871a2 1780 */
d24832f9 1781 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
e98871a2 1782 global $USER, $CFG;
1783
1784 $this->courseid = $courseid;
d4060472 1785 $this->context = context_course::instance($courseid);
e98871a2 1786
1787 // get course grade tree
1788 $top_element = grade_category::fetch_course_tree($courseid, true);
1789
6391ebe7 1790 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1791
1792 foreach ($this->elements as $key=>$unused) {
b89a70ce 1793 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
6391ebe7 1794 }
e98871a2 1795 }
1796
1797 /**
1798 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 1799 *
1800 * @param array &$element The seed of the recursion
1801 * @param bool $category_grade_last category grade item is the last child
1802 * @param bool $nooutcomes Whether or not outcomes should be included
1803 *
1804 * @return array
e98871a2 1805 */
d24832f9 1806 public function flatten(&$element, $category_grade_last, $nooutcomes) {
e98871a2 1807 if (empty($element['children'])) {
1808 return array();
1809 }
1810 $children = array();
1811
1812 foreach ($element['children'] as $sortorder=>$unused) {
cf72e2dd 1813 if ($nooutcomes and $element['type'] != 'category' and
1814 $element['children'][$sortorder]['object']->is_outcome_item()) {
e98871a2 1815 continue;
1816 }
1817 $children[] = $element['children'][$sortorder];
1818 }
1819 unset($element['children']);
1820
1821 if ($category_grade_last and count($children) > 1) {
1822 $cat_item = array_shift($children);
1823 array_push($children, $cat_item);
1824 }
1825
1826 $result = array();
1827 foreach ($children as $child) {
e0724506 1828 if ($child['type'] == 'category') {
6391ebe7 1829 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
e98871a2 1830 } else {
1831 $child['eid'] = 'i'.$child['object']->id;
6391ebe7 1832 $result[$child['object']->id] = $child;
e98871a2 1833 }
1834 }
1835
1836 return $result;
1837 }
1838
1839 /**
1840 * Parses the array in search of a given eid and returns a element object with
1841 * information about the element it has found.
cf72e2dd 1842 *
1843 * @param int $eid Gradetree Element ID
1844 *
e98871a2 1845 * @return object element
1846 */
d24832f9 1847 public function locate_element($eid) {
e98871a2 1848 // it is a grade - construct a new object
1849 if (strpos($eid, 'n') === 0) {
1850 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1851 return null;
1852 }
1853
1854 $itemid = $matches[1];
1855 $userid = $matches[2];
1856
1857 //extra security check - the grade item must be in this tree
ddb9c95f 1858 if (!$item_el = $this->locate_element('ig'.$itemid)) {
e98871a2 1859 return null;
1860 }
1861
1862 // $gradea->id may be null - means does not exist yet
1863 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1864
1865 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1866 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1867
1868 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 1869 $id = (int) substr($eid, 1);
e98871a2 1870 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1871 return null;
1872 }
1873 //extra security check - the grade item must be in this tree
ddb9c95f 1874 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
e98871a2 1875 return null;
1876 }
1877 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1878 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1879 }
1880
1881 // it is a category or item
6391ebe7 1882 foreach ($this->elements as $element) {
6cc3e350 1883 if ($element['eid'] == $eid) {
1884 return $element;
1885 }
e98871a2 1886 }
6cc3e350 1887
1888 return null;
e98871a2 1889 }
e98871a2 1890}
1891
7a6b7acf 1892/**
1893 * This class represents a complete tree of categories, grade_items and final grades,
1894 * organises as an array primarily, but which can also be converted to other formats.
1895 * It has simple method calls with complex implementations, allowing for easy insertion,
1896 * deletion and moving of items and categories within the tree.
cf72e2dd 1897 *
1898 * @uses grade_structure
a153c9f2 1899 * @package core_grades
cf72e2dd 1900 * @copyright 2009 Nicolas Connault
1901 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7a6b7acf 1902 */
6cc3e350 1903class grade_tree extends grade_structure {
7a6b7acf 1904
1905 /**
1906 * The basic representation of the tree as a hierarchical, 3-tiered array.
1907 * @var object $top_element
1908 */
d24832f9 1909 public $top_element;
7a6b7acf 1910
7a6b7acf 1911 /**
1912 * 2D array of grade items and categories
cf72e2dd 1913 * @var array $levels
7a6b7acf 1914 */
d24832f9 1915 public $levels;
7a6b7acf 1916
b89a70ce 1917 /**
1918 * Grade items
cf72e2dd 1919 * @var array $items
b89a70ce 1920 */
d24832f9 1921 public $items;
b89a70ce 1922
7a6b7acf 1923 /**
1924 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
e98871a2 1925 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
cf72e2dd 1926 *
1927 * @param int $courseid The Course ID
1928 * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
1929 * @param bool $category_grade_last category grade item is the last child
4faf5f99 1930 * @param array $collapsed array of collapsed categories
cf72e2dd 1931 * @param bool $nooutcomes Whether or not outcomes should be included
7a6b7acf 1932 */
cf72e2dd 1933 public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
1934 $collapsed=null, $nooutcomes=false) {
73ca5f01 1935 global $USER, $CFG, $COURSE, $DB;
7a6b7acf 1936
1937 $this->courseid = $courseid;
7a6b7acf 1938 $this->levels = array();
d4060472 1939 $this->context = context_course::instance($courseid);
7a6b7acf 1940
73ca5f01 1941 if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
1942 $course = $COURSE;
1943 } else {
1944 $course = $DB->get_record('course', array('id' => $this->courseid));
1945 }
1946 $this->modinfo = get_fast_modinfo($course);
1947
7a6b7acf 1948 // get course grade tree
1949 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1950
4faf5f99 1951 // collapse the categories if requested
1952 if (!empty($collapsed)) {
1953 grade_tree::category_collapse($this->top_element, $collapsed);
1954 }
1955
aea4df41 1956 // no otucomes if requested
1957 if (!empty($nooutcomes)) {
1958 grade_tree::no_outcomes($this->top_element);
1959 }
1960
4faf5f99 1961 // move category item to last position in category
7a6b7acf 1962 if ($category_grade_last) {
1963 grade_tree::category_grade_last($this->top_element);
1964 }
1965
1966 if ($fillers) {
1967 // inject fake categories == fillers
1968 grade_tree::inject_fillers($this->top_element, 0);
1969 // add colspans to categories and fillers
1970 grade_tree::inject_colspans($this->top_element);
1971 }
1972
1973 grade_tree::fill_levels($this->levels, $this->top_element, 0);
d297269d 1974
7a6b7acf 1975 }
1976
4faf5f99 1977 /**
1978 * Static recursive helper - removes items from collapsed categories
cf72e2dd 1979 *
1980 * @param array &$element The seed of the recursion
4faf5f99 1981 * @param array $collapsed array of collapsed categories
cf72e2dd 1982 *
4faf5f99 1983 * @return void
1984 */
d24832f9 1985 public function category_collapse(&$element, $collapsed) {
4faf5f99 1986 if ($element['type'] != 'category') {
1987 return;
1988 }
1989 if (empty($element['children']) or count($element['children']) < 2) {
1990 return;
1991 }
1992
384960dd 1993 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 1994 $category_item = reset($element['children']); //keep only category item
1995 $element['children'] = array(key($element['children'])=>$category_item);
1996
1997 } else {
384960dd 1998 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1999 reset($element['children']);
2000 $first_key = key($element['children']);
2001 unset($element['children'][$first_key]);
2002 }
2003 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 2004 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
2005 }
2006 }
2007 }
7a6b7acf 2008
aea4df41 2009 /**
2010 * Static recursive helper - removes all outcomes
cf72e2dd 2011 *
2012 * @param array &$element The seed of the recursion
2013 *
aea4df41 2014 * @return void
2015 */
d24832f9 2016 public function no_outcomes(&$element) {
aea4df41 2017 if ($element['type'] != 'category') {
2018 return;
2019 }
2020 foreach ($element['children'] as $sortorder=>$child) {
2021 if ($element['children'][$sortorder]['type'] == 'item'
2022 and $element['children'][$sortorder]['object']->is_outcome_item()) {
2023 unset($element['children'][$sortorder]);
2024
d4795a07 2025 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 2026 grade_tree::no_outcomes($element['children'][$sortorder]);
2027 }
2028 }
2029 }
2030
7a6b7acf 2031 /**
2032 * Static recursive helper - makes the grade_item for category the last children
cf72e2dd 2033 *
2034 * @param array &$element The seed of the recursion
2035 *
7a6b7acf 2036 * @return void
2037 */
d24832f9 2038 public function category_grade_last(&$element) {
7a6b7acf 2039 if (empty($element['children'])) {
2040 return;
2041 }
2042 if (count($element['children']) < 2) {
2043 return;
2044 }
3e0e2436 2045 $first_item = reset($element['children']);
4a3dfd9a 2046 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3e0e2436 2047 // the category item might have been already removed
2048 $order = key($element['children']);
2049 unset($element['children'][$order]);
2050 $element['children'][$order] =& $first_item;
2051 }
206f9953 2052 foreach ($element['children'] as $sortorder => $child) {
7a6b7acf 2053 grade_tree::category_grade_last($element['children'][$sortorder]);
2054 }
2055 }
2056
2057 /**
2058 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
cf72e2dd 2059 *
2060 * @param array &$levels The levels of the grade tree through which to recurse
2061 * @param array &$element The seed of the recursion
2062 * @param int $depth How deep are we?
7a6b7acf 2063 * @return void
2064 */
d24832f9 2065 public function fill_levels(&$levels, &$element, $depth) {
7a6b7acf 2066 if (!array_key_exists($depth, $levels)) {
2067 $levels[$depth] = array();
2068 }
2069
2070 // prepare unique identifier
2071 if ($element['type'] == 'category') {
ddb9c95f 2072 $element['eid'] = 'cg'.$element['object']->id;
7a6b7acf 2073 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
ddb9c95f 2074 $element['eid'] = 'ig'.$element['object']->id;
b89a70ce 2075 $this->items[$element['object']->id] =& $element['object'];
7a6b7acf 2076 }
2077
2078 $levels[$depth][] =& $element;
2079 $depth++;
2080 if (empty($element['children'])) {
2081 return;
2082 }
2083 $prev = 0;
2084 foreach ($element['children'] as $sortorder=>$child) {
2085 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
2086 $element['children'][$sortorder]['prev'] = $prev;
2087 $element['children'][$sortorder]['next'] = 0;
2088 if ($prev) {
2089 $element['children'][$prev]['next'] = $sortorder;
2090 }
2091 $prev = $sortorder;
2092 }
2093 }
2094
2095 /**
2096 * Static recursive helper - makes full tree (all leafes are at the same level)
cf72e2dd 2097 *
2098 * @param array &$element The seed of the recursion
2099 * @param int $depth How deep are we?
2100 *
2101 * @return int
7a6b7acf 2102 */
d24832f9 2103 public function inject_fillers(&$element, $depth) {
7a6b7acf 2104 $depth++;
2105
2106 if (empty($element['children'])) {
2107 return $depth;
2108 }
2109 $chdepths = array();
2110 $chids = array_keys($element['children']);
2111 $last_child = end($chids);
2112 $first_child = reset($chids);
2113
2114 foreach ($chids as $chid) {
2115 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
2116 }
2117 arsort($chdepths);
2118
2119 $maxdepth = reset($chdepths);
2120 foreach ($chdepths as $chid=>$chd) {
2121 if ($chd == $maxdepth) {
2122 continue;
2123 }
2124 for ($i=0; $i < $maxdepth-$chd; $i++) {
2125 if ($chid == $first_child) {
2126 $type = 'fillerfirst';
2127 } else if ($chid == $last_child) {
2128 $type = 'fillerlast';
2129 } else {
2130 $type = 'filler';
2131 }
2132 $oldchild =& $element['children'][$chid];
cf72e2dd 2133 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
2134 'eid'=>'', 'depth'=>$element['object']->depth,
2135 'children'=>array($oldchild));
7a6b7acf 2136 }
2137 }
2138
2139 return $maxdepth;
2140 }
2141
2142 /**
2143 * Static recursive helper - add colspan information into categories
cf72e2dd 2144 *
2145 * @param array &$element The seed of the recursion
2146 *
2147 * @return int
7a6b7acf 2148 */
d24832f9 2149 public function inject_colspans(&$element) {
7a6b7acf 2150 if (empty($element['children'])) {
2151 return 1;
2152 }
2153 $count = 0;
2154 foreach ($element['children'] as $key=>$child) {
2155 $count += grade_tree::inject_colspans($element['children'][$key]);
2156 }
2157 $element['colspan'] = $count;
2158 return $count;
2159 }
2160
2161 /**
2162 * Parses the array in search of a given eid and returns a element object with
2163 * information about the element it has found.
cf72e2dd 2164 * @param int $eid Gradetree Element ID
7a6b7acf 2165 * @return object element
2166 */
d24832f9 2167 public function locate_element($eid) {
d3c3da1b 2168 // it is a grade - construct a new object
2169 if (strpos($eid, 'n') === 0) {
2170 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
2171 return null;
2172 }
2173
2174 $itemid = $matches[1];
2175 $userid = $matches[2];
2176
2177 //extra security check - the grade item must be in this tree
ddb9c95f 2178 if (!$item_el = $this->locate_element('ig'.$itemid)) {
d3c3da1b 2179 return null;
2180 }
2181
2182 // $gradea->id may be null - means does not exist yet
2183 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
2184
2185 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2186 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
2187
2188 } else if (strpos($eid, 'g') === 0) {
cf72e2dd 2189 $id = (int) substr($eid, 1);
7a6b7acf 2190 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
2191 return null;
2192 }
2193 //extra security check - the grade item must be in this tree
ddb9c95f 2194 if (!$item_el = $this->locate_element('ig'.$grade->itemid)) {
7a6b7acf 2195 return null;
2196 }
2197 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
2198 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
2199 }
2200
2201 // it is a category or item
2202 foreach ($this->levels as $row) {
2203 foreach ($row as $element) {
2204 if ($element['type'] == 'filler') {
2205 continue;
2206 }
2207 if ($element['eid'] == $eid) {
2208 return $element;
2209 }
2210 }
2211 }
2212
2213 return null;
2214 }
d24832f9 2215
b244b9b7 2216 /**
2217 * Returns a well-formed XML representation of the grade-tree using recursion.
cf72e2dd 2218 *
2219 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2220 * @param string $tabs The control character to use for tabs
2221 *
b244b9b7 2222 * @return string $xml
2223 */
cf72e2dd 2224 public function exporttoxml($root=null, $tabs="\t") {
b244b9b7 2225 $xml = null;
2226 $first = false;
2227 if (is_null($root)) {
2228 $root = $this->top_element;
2229 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
2230 $xml .= "<gradetree>\n";
2231 $first = true;
2232 }
d24832f9 2233
b244b9b7 2234 $type = 'undefined';
2235 if (strpos($root['object']->table, 'grade_categories') !== false) {
2236 $type = 'category';
cf72e2dd 2237 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2238 $type = 'item';
cf72e2dd 2239 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2240 $type = 'outcome';
2241 }
d24832f9 2242
b244b9b7 2243 $xml .= "$tabs<element type=\"$type\">\n";
2244 foreach ($root['object'] as $var => $value) {
2245 if (!is_object($value) && !is_array($value) && !empty($value)) {
2246 $xml .= "$tabs\t<$var>$value</$var>\n";
2247 }
2248 }
2249
2250 if (!empty($root['children'])) {
2251 $xml .= "$tabs\t<children>\n";
2252 foreach ($root['children'] as $sortorder => $child) {
2253 $xml .= $this->exportToXML($child, $tabs."\t\t");
2254 }
2255 $xml .= "$tabs\t</children>\n";
2256 }
d24832f9 2257
b244b9b7 2258 $xml .= "$tabs</element>\n";
2259
2260 if ($first) {
2261 $xml .= "</gradetree>";
2262 }
d24832f9 2263
b244b9b7 2264 return $xml;
2265 }
d24832f9 2266
b244b9b7 2267 /**
2268 * Returns a JSON representation of the grade-tree using recursion.
cf72e2dd 2269 *
b244b9b7 2270 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
2271 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
cf72e2dd 2272 *
2273 * @return string
b244b9b7 2274 */
cf72e2dd 2275 public function exporttojson($root=null, $tabs="\t") {
b244b9b7 2276 $json = null;
2277 $first = false;
2278 if (is_null($root)) {
2279 $root = $this->top_element;
2280 $first = true;
2281 }
d24832f9 2282
b244b9b7 2283 $name = '';
2284
2285
2286 if (strpos($root['object']->table, 'grade_categories') !== false) {
2287 $name = $root['object']->fullname;
2288 if ($name == '?') {
d24832f9 2289 $name = $root['object']->get_name();
b244b9b7 2290 }
cf72e2dd 2291 } else if (strpos($root['object']->table, 'grade_items') !== false) {
b244b9b7 2292 $name = $root['object']->itemname;
cf72e2dd 2293 } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
b244b9b7 2294 $name = $root['object']->itemname;
2295 }
d24832f9 2296
b244b9b7 2297 $json .= "$tabs {\n";
2298 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
2299 $json .= "$tabs\t \"name\": \"$name\",\n";
2300
2301 foreach ($root['object'] as $var => $value) {
2302 if (!is_object($value) && !is_array($value) && !empty($value)) {
2303 $json .= "$tabs\t \"$var\": \"$value\",\n";
2304 }
2305 }
d24832f9 2306
b244b9b7 2307 $json = substr($json, 0, strrpos($json, ','));
d24832f9 2308
b244b9b7 2309 if (!empty($root['children'])) {
2310 $json .= ",\n$tabs\t\"children\": [\n";
2311 foreach ($root['children'] as $sortorder => $child) {
2312 $json .= $this->exportToJSON($child, $tabs."\t\t");
2313 }
2314 $json = substr($json, 0, strrpos($json, ','));
2315 $json .= "\n$tabs\t]\n";
d24832f9 2316 }
b244b9b7 2317
2318 if ($first) {
2319 $json .= "\n}";
2320 } else {
2321 $json .= "\n$tabs},\n";
2322 }
d24832f9 2323
b244b9b7 2324 return $json;
2325 }
d24832f9 2326
cf72e2dd 2327 /**
2328 * Returns the array of levels
2329 *
2330 * @return array
2331 */
d24832f9 2332 public function get_levels() {
2333 return $this->levels;
2334 }
2335
cf72e2dd 2336 /**
2337 * Returns the array of grade items
2338 *
2339 * @return array
2340 */
d24832f9 2341 public function get_items() {
2342 return $this->items;
2343 }
2344
cf72e2dd 2345 /**
2346 * Returns a specific Grade Item
2347 *
2348 * @param int $itemid The ID of the grade_item object
2349 *
2350 * @return grade_item
2351 */
d24832f9 2352 public function get_item($itemid) {
2353 if (array_key_exists($itemid, $this->items)) {
2354 return $this->items[$itemid];
2355 } else {
2356 return false;
2357 }
2358 }
7a6b7acf 2359}
eef00ade 2360
2361/**
2362 * Local shortcut function for creating an edit/delete button for a grade_* object.
4d27bc79 2363 * @param string $type 'edit' or 'delete'
eef00ade 2364 * @param int $courseid The Course ID
2365 * @param grade_* $object The grade_* object
2366 * @return string html
2367 */
2368function grade_button($type, $courseid, $object) {
2369 global $CFG, $OUTPUT;
2370 if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
2371 $objectidstring = $matches[1] . 'id';
2372 } else {
2373 throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
2374 }
2375
2376 $strdelete = get_string('delete');
2377 $stredit = get_string('edit');
2378
eef00ade 2379 if ($type == 'delete') {
8ae8bf8a 2380 $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
eef00ade 2381 } else if ($type == 'edit') {
8ae8bf8a 2382 $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
eef00ade 2383 }
2384
fa9c0aab 2385 return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}, '', array('class' => 'iconsmall')));
eef00ade 2386
2387}
4d5059d4
SH
2388
2389/**
2390 * This method adds settings to the settings block for the grade system and its
2391 * plugins
2392 *
2393 * @global moodle_page $PAGE
2394 */
2395function grade_extend_settings($plugininfo, $courseid) {
2396 global $PAGE;
2397
2398 $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
2399
2400 $strings = array_shift($plugininfo);
2401
2402 if ($reports = grade_helper::get_plugins_reports($courseid)) {
2403 foreach ($reports as $report) {
2404 $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
2405 }
2406 }
2407
2408 if ($imports = grade_helper::get_plugins_import($courseid)) {
2409 $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
2410 foreach ($imports as $import) {
11f87187 2411 $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/import', ''));
4d5059d4
SH
2412 }
2413 }
2414
2415 if ($exports = grade_helper::get_plugins_export($courseid)) {
2416 $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
2417 foreach ($exports as $export) {
11f87187 2418 $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/export', ''));
4d5059d4
SH
2419 }
2420 }
2421
8faa560c
MG
2422 if ($settings = grade_helper::get_info_manage_settings($courseid)) {
2423 $settingsnode = $gradenode->add($strings['settings'], null, navigation_node::TYPE_CONTAINER);
2424 foreach ($settings as $setting) {
2425 $settingsnode->add($setting->string, $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
2426 }
4d5059d4
SH
2427 }
2428
2429 if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
2430 $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
2431 foreach ($preferences as $preference) {
2432 $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
2433 }
2434 }
2435
2436 if ($letters = grade_helper::get_info_letters($courseid)) {
2437 $letters = array_shift($letters);
2438 $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
2439 }
2440
2441 if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
2442 $outcomes = array_shift($outcomes);
2443 $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
2444 }
2445
2446 if ($scales = grade_helper::get_info_scales($courseid)) {
2447 $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
2448 }
2449
4d5059d4
SH
2450 if ($gradenode->contains_active_node()) {
2451 // If the gradenode is active include the settings base node (gradeadministration) in
2452 // the navbar, typcially this is ignored.
2453 $PAGE->navbar->includesettingsbase = true;
2454
2455 // If we can get the course admin node make sure it is closed by default
2456 // as in this case the gradenode will be opened
2457 if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
2458 $coursenode->make_inactive();
2459 $coursenode->forceopen = false;
2460 }
2461 }
2462}
2463
2464/**
2465 * Grade helper class
2466 *
2467 * This class provides several helpful functions that work irrespective of any
2468 * current state.
2469 *
2470 * @copyright 2010 Sam Hemelryk
2471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2472 */
2473abstract class grade_helper {
2474 /**
2475 * Cached manage settings info {@see get_info_settings}
2476 * @var grade_plugin_info|false
2477 */
2478 protected static $managesetting = null;
2479 /**
2480 * Cached grade report plugins {@see get_plugins_reports}
2481 * @var array|false
2482 */
2483 protected static $gradereports = null;
2484 /**
2485 * Cached grade report plugins preferences {@see get_info_scales}
2486 * @var array|false
2487 */
2488 protected static $gradereportpreferences = null;
2489 /**
2490 * Cached scale info {@see get_info_scales}
2491 * @var grade_plugin_info|false
2492 */
2493 protected static $scaleinfo = null;
2494 /**
2495 * Cached outcome info {@see get_info_outcomes}
2496 * @var grade_plugin_info|false
2497 */
2498 protected static $outcomeinfo = null;
4d5059d4
SH
2499 /**
2500 * Cached leftter info {@see get_info_letters}
2501 * @var grade_plugin_info|false
2502 */
2503 protected static $letterinfo = null;
2504 /**
2505 * Cached grade import plugins {@see get_plugins_import}
2506 * @var array|false
2507 */
2508 protected static $importplugins = null;
2509 /**
2510 * Cached grade export plugins {@see get_plugins_export}
2511 * @var array|false
2512 */
2513 protected static $exportplugins = null;
2514 /**
2515 * Cached grade plugin strings
2516 * @var array
2517 */
2518 protected static $pluginstrings = null;
bfe969e8
DW
2519 /**
2520 * Cached grade aggregation strings
2521 * @var array
2522 */
2523 protected static $aggregationstrings = null;
4d5059d4
SH
2524
2525 /**
2526 * Gets strings commonly used by the describe plugins
2527 *
2528 * report => get_string('view'),
4d5059d4
SH
2529 * scale => get_string('scales'),
2530 * outcome => get_string('outcomes', 'grades'),
2531 * letter => get_string('letters', 'grades'),
2532 * export => get_string('export', 'grades'),
2533 * import => get_string('import'),
2534 * preferences => get_string('mypreferences', 'grades'),
2535 * settings => get_string('settings')
2536 *
2537 * @return array
2538 */
2539 public static function get_plugin_strings() {
2540 if (self::$pluginstrings === null) {
2541 self::$pluginstrings = array(
2542 'report' => get_string('view'),
4d5059d4
SH
2543 'scale' => get_string('scales'),
2544 'outcome' => get_string('outcomes', 'grades'),
2545 'letter' => get_string('letters', 'grades'),
2546 'export' => get_string('export', 'grades'),
2547 'import' => get_string('import'),
2548 'preferences' => get_string('mypreferences', 'grades'),
2549 'settings' => get_string('settings')
2550 );
2551 }
2552 return self::$pluginstrings;
2553 }
bfe969e8
DW
2554
2555 /**
2556 * Gets strings describing the available aggregation methods.
2557 *
2558 * @return array
2559 */
2560 public static function get_aggregation_strings() {
2561 if (self::$aggregationstrings === null) {
2562 self::$aggregationstrings = array(
2563 GRADE_AGGREGATE_MEAN => get_string('aggregatemean', 'grades'),
2564 GRADE_AGGREGATE_WEIGHTED_MEAN => get_string('aggregateweightedmean', 'grades'),
2565 GRADE_AGGREGATE_WEIGHTED_MEAN2 => get_string('aggregateweightedmean2', 'grades'),
2566 GRADE_AGGREGATE_EXTRACREDIT_MEAN => get_string('aggregateextracreditmean', 'grades'),
2567 GRADE_AGGREGATE_MEDIAN => get_string('aggregatemedian', 'grades'),
2568 GRADE_AGGREGATE_MIN => get_string('aggregatemin', 'grades'),
2569 GRADE_AGGREGATE_MAX => get_string('aggregatemax', 'grades'),
2570 GRADE_AGGREGATE_MODE => get_string('aggregatemode', 'grades'),
2571 GRADE_AGGREGATE_SUM => get_string('aggregatesum', 'grades')
2572 );
2573 }
2574 return self::$aggregationstrings;
2575 }
2576
4d5059d4
SH
2577 /**
2578 * Get grade_plugin_info object for managing settings if the user can
2579 *
2580 * @param int $courseid
8faa560c 2581 * @return grade_plugin_info[]
4d5059d4
SH
2582 */
2583 public static function get_info_manage_settings($courseid) {
2584 if (self::$managesetting !== null) {
2585 return self::$managesetting;
2586 }
d4060472 2587 $context = context_course::instance($courseid);
8faa560c
MG
2588 self::$managesetting = array();
2589 if ($courseid != SITEID && has_capability('moodle/grade:manage', $context)) {
2590 self::$managesetting['coursesettings'] = new grade_plugin_info('coursesettings',
2591 new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)),
2592 get_string('coursegradesettings', 'grades'));
2593 self::$managesetting['setup'] = new grade_plugin_info('setup',
2594 new moodle_url('/grade/edit/tree/index.php', array('id' => $courseid)),
2595 get_string('setupgradeslayout', 'grades'));
4d5059d4
SH
2596 }
2597 return self::$managesetting;
2598 }
2599 /**
2600 * Returns an array of plugin reports as grade_plugin_info objects
2601 *
2602 * @param int $courseid
2603 * @return array
2604 */
2605 public static function get_plugins_reports($courseid) {
f7fcf4cd 2606 global $SITE;
cf717dc2 2607
4d5059d4
SH
2608 if (self::$gradereports !== null) {
2609 return self::$gradereports;
2610 }
d4060472 2611 $context = context_course::instance($courseid);
4d5059d4
SH
2612 $gradereports = array();
2613 $gradepreferences = array();
bd3b3bba 2614 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
f7fcf4cd
AD
2615 //some reports make no sense if we're not within a course
2616 if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
2617 continue;
2618 }
2619
4d5059d4
SH
2620 // Remove ones we can't see
2621 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
2622 continue;
2623 }
2624
b5e7b2bf 2625 $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
4d5059d4
SH
2626 $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
2627 $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2628
2629 // Add link to preferences tab if such a page exists
2630 if (file_exists($plugindir.'/preferences.php')) {
2631 $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
2632 $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2633 }
2634 }
2635 if (count($gradereports) == 0) {
2636 $gradereports = false;
2637 $gradepreferences = false;
2638 } else if (count($gradepreferences) == 0) {
2639 $gradepreferences = false;
2640 asort($gradereports);
2641 } else {
2642 asort($gradereports);
2643 asort($gradepreferences);
2644 }
2645 self::$gradereports = $gradereports;
2646 self::$gradereportpreferences = $gradepreferences;
2647 return self::$gradereports;
2648 }
2649 /**
2650 * Returns an array of grade plugin report preferences for plugin reports that
2651 * support preferences
2652 * @param int $courseid
2653 * @return array
2654 */
2655 public static function get_plugins_report_preferences($courseid) {
2656 if (self::$gradereportpreferences !== null) {
2657 return self::$gradereportpreferences;
2658 }
2659 self::get_plugins_reports($courseid);
2660 return self::$gradereportpreferences;
2661 }
2662 /**
2663 * Get information on scales
2664 * @param int $courseid
2665 * @return grade_plugin_info
2666 */
2667 public static function get_info_scales($courseid) {
2668 if (self::$scaleinfo !== null) {
2669 return self::$scaleinfo;
2670 }
d4060472 2671 if (has_capability('moodle/course:managescales', context_course::instance($courseid))) {
4d5059d4
SH
2672 $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
2673 self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
2674 } else {
2675 self::$scaleinfo = false;
2676 }
2677 return self::$scaleinfo;
2678 }
2679 /**
2680 * Get information on outcomes
2681 * @param int $courseid
2682 * @return grade_plugin_info
2683 */
2684 public static function get_info_outcomes($courseid) {
f7fcf4cd 2685 global $CFG, $SITE;
4d5059d4
SH
2686
2687 if (self::$outcomeinfo !== null) {
2688 return self::$outcomeinfo;
2689 }
d4060472 2690 $context = context_course::instance($courseid);
4d5059d4
SH
2691 $canmanage = has_capability('moodle/grade:manage', $context);
2692 $canupdate = has_capability('moodle/course:update', $context);
2693 if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
2694 $outcomes = array();
2695 if ($canupdate) {
f7fcf4cd
AD
2696 if ($courseid!=$SITE->id) {
2697 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2698 $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
2699 }
4d5059d4
SH
2700 $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
2701 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
c46aeeab
DC
2702 $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
2703 $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
4d5059d4 2704 } else {
f7fcf4cd
AD
2705 if ($courseid!=$SITE->id) {
2706 $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
2707 $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
2708 }
4d5059d4
SH
2709 }
2710 self::$outcomeinfo = $outcomes;
2711 } else {
2712 self::$outcomeinfo = false;
2713 }
2714 return self::$outcomeinfo;
2715 }
4d5059d4
SH
2716 /**
2717 * Get information on letters
2718 * @param int $courseid
4d27bc79 2719 * @return array
4d5059d4
SH
2720 */
2721 public static function get_info_letters($courseid) {
a8dfc483 2722 global $SITE;
4d5059d4
SH
2723 if (self::$letterinfo !== null) {
2724 return self::$letterinfo;
2725 }
d4060472 2726 $context = context_course::instance($courseid);
4d5059d4
SH
2727 $canmanage = has_capability('moodle/grade:manage', $context);
2728 $canmanageletters = has_capability('moodle/grade:manageletters', $context);
2729 if ($canmanage || $canmanageletters) {
a8dfc483
AA
2730 // Redirect to system context when report is accessed from admin settings MDL-31633
2731 if ($context->instanceid == $SITE->id) {
2732 $param = array('edit' => 1);
2733 } else {
2734 $param = array('edit' => 1,'id' => $context->id);
2735 }
4d5059d4 2736 self::$letterinfo = array(
54caa598 2737 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
a8dfc483 2738 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', $param), get_string('edit'))
4d5059d4
SH
2739 );
2740 } else {
2741 self::$letterinfo = false;
2742 }
2743 return self::$letterinfo;
2744 }
2745 /**
2746 * Get information import plugins
2747 * @param int $courseid
2748 * @return array
2749 */
2750 public static function get_plugins_import($courseid) {
2751 global $CFG;
2752
2753 if (self::$importplugins !== null) {
2754 return self::$importplugins;
2755 }
2756 $importplugins = array();
d4060472 2757 $context = context_course::instance($courseid);
4d5059d4
SH
2758
2759 if (has_capability('moodle/grade:import', $context)) {
bd3b3bba 2760 foreach (core_component::get_plugin_list('gradeimport') as $plugin => $plugindir) {
4d5059d4
SH
2761 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
2762 continue;
2763 }
b5e7b2bf 2764 $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
4d5059d4
SH
2765 $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
2766 $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2767 }
2768
2769
2770 if ($CFG->gradepublishing) {
2771 $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
2772 $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2773 }
2774 }
2775
2776 if (count($importplugins) > 0) {
2777 asort($importplugins);
2778 self::$importplugins = $importplugins;
2779 } else {
2780 self::$importplugins = false;
2781 }
2782 return self::$importplugins;
2783 }
2784 /**
2785 * Get information export plugins
2786 * @param int $courseid
2787 * @return array
2788 */
2789 public static function get_plugins_export($courseid) {
2790 global $CFG;
2791
2792 if (self::$exportplugins !== null) {
2793 return self::$exportplugins;
2794 }
d4060472 2795 $context = context_course::instance($courseid);
4d5059d4
SH
2796 $exportplugins = array();
2797 if (has_capability('moodle/grade:export', $context)) {
bd3b3bba 2798 foreach (core_component::get_plugin_list('gradeexport') as $plugin => $plugindir) {
4d5059d4
SH
2799 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
2800 continue;
2801 }
b5e7b2bf 2802 $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
4d5059d4
SH
2803 $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
2804 $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
2805 }
2806
2807 if ($CFG->gradepublishing) {
2808 $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
2809 $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
2810 }
2811 }
2812 if (count($exportplugins) > 0) {
2813 asort($exportplugins);
2814 self::$exportplugins = $exportplugins;
2815 } else {
2816 self::$exportplugins = false;
2817 }
2818 return self::$exportplugins;
2819 }
293f42b6 2820
61c8e0d7
FM
2821 /**
2822 * Returns the value of a field from a user record
2823 *
2824 * @param stdClass $user object
2825 * @param stdClass $field object
2826 * @return string value of the field
2827 */
2828 public static function get_user_field_value($user, $field) {
2829 if (!empty($field->customid)) {
2830 $fieldname = 'customfield_' . $field->shortname;
2831 if (!empty($user->{$fieldname}) || is_numeric($user->{$fieldname})) {
2832 $fieldvalue = $user->{$fieldname};
2833 } else {
2834 $fieldvalue = $field->default;
2835 }
2836 } else {
2837 $fieldvalue = $user->{$field->shortname};
2838 }
2839 return $fieldvalue;
2840 }
2841
2842 /**
2843 * Returns an array of user profile fields to be included in export
2844 *
2845 * @param int $courseid
2846 * @param bool $includecustomfields
2847 * @return array An array of stdClass instances with customid, shortname, datatype, default and fullname fields
2848 */
2849 public static function get_user_profile_fields($courseid, $includecustomfields = false) {
2850 global $CFG, $DB;
2851
2852 // Gets the fields that have to be hidden
2853 $hiddenfields = array_map('trim', explode(',', $CFG->hiddenuserfields));
2854 $context = context_course::instance($courseid);
2855 $canseehiddenfields = has_capability('moodle/course:viewhiddenuserfields', $context);
2856 if ($canseehiddenfields) {
2857 $hiddenfields = array();
2858 }
2859
2860 $fields = array();
2861 require_once($CFG->dirroot.'/user/lib.php'); // Loads user_get_default_fields()
2862 require_once($CFG->dirroot.'/user/profile/lib.php'); // Loads constants, such as PROFILE_VISIBLE_ALL
2863 $userdefaultfields = user_get_default_fields();
2864
2865 // Sets the list of profile fields
2866 $userprofilefields = array_map('trim', explode(',', $CFG->grade_export_userprofilefields));
2867 if (!empty($userprofilefields)) {
2868 foreach ($userprofilefields as $field) {
2869 $field = trim($field);
2870 if (in_array($field, $hiddenfields) || !in_array($field, $userdefaultfields)) {
2871 continue;
2872 }
293f42b6 2873 $obj = new stdClass();
61c8e0d7 2874 $obj->customid = 0;
293f42b6 2875 $obj->shortname = $field;
61c8e0d7 2876 $obj->fullname = get_string($field);
293f42b6
CF
2877 $fields[] = $obj;
2878 }
2879 }
293f42b6 2880
61c8e0d7
FM
2881 // Sets the list of custom profile fields
2882 $customprofilefields = array_map('trim', explode(',', $CFG->grade_export_customprofilefields));
2883 if ($includecustomfields && !empty($customprofilefields)) {
2884 list($wherefields, $whereparams) = $DB->get_in_or_equal($customprofilefields);
2885 $customfields = $DB->get_records_sql("SELECT f.*
2886 FROM {user_info_field} f
2887 JOIN {user_info_category} c ON f.categoryid=c.id
2888 WHERE f.shortname $wherefields
2889 ORDER BY c.sortorder ASC, f.sortorder ASC", $whereparams);
2890 if (!is_array($customfields)) {
2891 continue;
2892 }
2893
2894 foreach ($customfields as $field) {
2895 // Make sure we can display this custom field
2896 if (!in_array($field->shortname, $customprofilefields)) {
2897 continue;
2898 } else if (in_array($field->shortname, $hiddenfields)) {
2899 continue;
2900 } else if ($field->visible != PROFILE_VISIBLE_ALL && !$canseehiddenfields) {
2901 continue;
2902 }
2903
2904 $obj = new stdClass();
2905 $obj->customid = $field->id;
2906 $obj->shortname = $field->shortname;
2907 $obj->fullname = format_string($field->name);
2908 $obj->datatype = $field->datatype;
2909 $obj->default = $field->defaultdata;
2910 $fields[] = $obj;
2911 }
2912 }
2913
2914 return $fields;
2915 }
e61f25a4
DW
2916
2917 /**
2918 * This helper method gets a snapshot of all the weights for a course.
2919 * It is used as a quick method to see if any wieghts have been automatically adjusted.
2920 * @param int $courseid
2921 * @return array of itemid -> aggregationcoef2
2922 */
2923 public static function fetch_all_natural_weights_for_course($courseid) {
2924 global $DB;
2925 $result = array();
2926
2927 $records = $DB->get_records('grade_items', array('courseid'=>$courseid), 'id', 'id, aggregationcoef2');
2928 foreach ($records as $record) {
2929 $result[$record->id] = $record->aggregationcoef2;
2930 }
2931 return $result;
2932 }
293f42b6 2933}
61c8e0d7 2934