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