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