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