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