MDL-18125 - improve lang for options/choices
[moodle.git] / grade / lib.php
CommitLineData
3af29899 1<?php //$Id$
cbff94ba 2
8ad36f4c 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.com //
9// //
10// Copyright (C) 1999 onwards Martin Dougiamas http://moodle.com //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
7a6b7acf 26require_once $CFG->libdir.'/gradelib.php';
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.
0f5660f7 31 */
32class graded_users_iterator {
d24832f9 33 public $course;
34 public $grade_items;
35 public $groupid;
36 public $users_rs;
37 public $grades_rs;
38 public $gradestack;
39 public $sortfield1;
40 public $sortorder1;
41 public $sortfield2;
42 public $sortorder2;
0f5660f7 43
44 /**
45 * Constructor
d08bba83 46 * @param $course object
0f5660f7 47 * @param array grade_items array of grade items, if not specified only user info returned
48 * @param int $groupid iterate only group users if present
d08bba83 49 * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
50 * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
51 * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
52 * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
0f5660f7 53 */
d24832f9 54 public function graded_users_iterator($course, $grade_items=null, $groupid=0, $sortfield1='lastname', $sortorder1='ASC', $sortfield2='firstname', $sortorder2='ASC') {
0f5660f7 55 $this->course = $course;
56 $this->grade_items = $grade_items;
57 $this->groupid = $groupid;
d08bba83 58 $this->sortfield1 = $sortfield1;
59 $this->sortorder1 = $sortorder1;
60 $this->sortfield2 = $sortfield2;
61 $this->sortorder2 = $sortorder2;
0f5660f7 62
63 $this->gradestack = array();
64 }
65
66 /**
67 * Initialise the iterator
68 * @return boolean success
69 */
d24832f9 70 public function init() {
71 global $CFG, $DB;
0f5660f7 72
73 $this->close();
74
75 grade_regrade_final_grades($this->course->id);
76 $course_item = grade_item::fetch_course_item($this->course->id);
77 if ($course_item->needsupdate) {
78 // can not calculate all final grades - sorry
79 return false;
80 }
81
e58fcb35 82 list($gradebookroles_sql, $params) = $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr0');
0f5660f7 83
84 $relatedcontexts = get_related_contexts_string(get_context_instance(CONTEXT_COURSE, $this->course->id));
85
86 if ($this->groupid) {
d24832f9 87 $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
e58fcb35 88 $groupwheresql = "AND gm.groupid = :groupid";
d24832f9 89 // $params contents: gradebookroles
e58fcb35 90 $params['groupid'] = $this->groupid;
0f5660f7 91 } else {
92 $groupsql = "";
93 $groupwheresql = "";
94 }
95
345674ca 96 if (empty($this->sortfield1)) {
97 // we must do some sorting even if not specified
98 $ofields = ", u.id AS usrt";
99 $order = "usrt ASC";
100
101 } else {
102 $ofields = ", u.$this->sortfield1 AS usrt1";
103 $order = "usrt1 $this->sortorder1";
104 if (!empty($this->sortfield2)) {
105 $ofields .= ", u.$this->sortfield1 AS usrt2";
106 $order .= ", usrt2 $this->sortorder2";
107 }
108 if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
109 // user order MUST be the same in both queries, must include the only unique user->id if not already present
110 $ofields .= ", u.id AS usrt";
111 $order .= ", usrt ASC";
112 }
113 }
114
d24832f9 115 // $params contents: gradebookroles and groupid (for $groupwheresql)
345674ca 116 $users_sql = "SELECT u.* $ofields
d24832f9 117 FROM {user} u
118 INNER JOIN {role_assignments} ra ON u.id = ra.userid
0f5660f7 119 $groupsql
5c75a0a3 120 WHERE ra.roleid $gradebookroles_sql
0f5660f7 121 AND ra.contextid $relatedcontexts
345674ca 122 $groupwheresql
123 ORDER BY $order";
d08bba83 124
d24832f9 125 $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
0f5660f7 126
127 if (!empty($this->grade_items)) {
128 $itemids = array_keys($this->grade_items);
e58fcb35 129 list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items0');
d24832f9 130 $params = array_merge($params, $grades_params);
0f5660f7 131
d24832f9 132 // $params contents: gradebookroles, groupid (for $groupwheresql) and itemids
345674ca 133 $grades_sql = "SELECT g.* $ofields
d24832f9 134 FROM {grade_grades} g
135 INNER JOIN {user} u ON g.userid = u.id
136 INNER JOIN {role_assignments} ra ON u.id = ra.userid
0f5660f7 137 $groupsql
d24832f9 138 WHERE ra.roleid $gradebookroles_sql
0f5660f7 139 AND ra.contextid $relatedcontexts
0f5660f7 140 $groupwheresql
d24832f9 141 AND g.itemid $itemidsql
345674ca 142 ORDER BY $order, g.itemid ASC";
d24832f9 143 $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
345674ca 144 } else {
145 $this->grades_rs = false;
0f5660f7 146 }
345674ca 147
0f5660f7 148 return true;
149 }
150
151 /**
152 * Returns information about the next user
153 * @return mixed array of user info, all grades and feedback or null when no more users found
154 */
155 function next_user() {
03cedd62 156 if (!$this->users_rs) {
0f5660f7 157 return false; // no users present
158 }
159
5c75a0a3 160 if (!$this->users_rs->valid()) {
345674ca 161 if ($current = $this->_pop()) {
162 // this is not good - user or grades updated between the two reads above :-(
163 }
164
0f5660f7 165 return false; // no more users
5c75a0a3 166 } else {
167 $user = $this->users_rs->current();
168 $this->users_rs->next();
0f5660f7 169 }
170
345674ca 171 // find grades of this user
0f5660f7 172 $grade_records = array();
173 while (true) {
174 if (!$current = $this->_pop()) {
175 break; // no more grades
176 }
177
5c75a0a3 178 if (empty($current->userid)) {
179 break;
180 }
181
345674ca 182 if ($current->userid != $user->id) {
183 // grade of the next user, we have all for this user
0f5660f7 184 $this->_push($current);
185 break;
186 }
187
188 $grade_records[$current->itemid] = $current;
189 }
190
191 $grades = array();
192 $feedbacks = array();
193
d08bba83 194 if (!empty($this->grade_items)) {
345674ca 195 foreach ($this->grade_items as $grade_item) {
196 if (array_key_exists($grade_item->id, $grade_records)) {
197 $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
198 $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
199 unset($grade_records[$grade_item->id]->feedback);
200 unset($grade_records[$grade_item->id]->feedbackformat);
201 $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
202 } else {
203 $feedbacks[$grade_item->id]->feedback = '';
204 $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
205 $grades[$grade_item->id] = new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
206 }
0f5660f7 207 }
208 }
209
210 $result = new object();
211 $result->user = $user;
212 $result->grades = $grades;
213 $result->feedbacks = $feedbacks;
214
215 return $result;
216 }
217
218 /**
219 * Close the iterator, do not forget to call this function.
220 * @return void
221 */
222 function close() {
caffc55a 223 if ($this->users_rs) {
d24832f9 224 $this->users_rs->close();
caffc55a 225 $this->users_rs = null;
0f5660f7 226 }
caffc55a 227 if ($this->grades_rs) {
d24832f9 228 $this->grades_rs->close();
caffc55a 229 $this->grades_rs = null;
0f5660f7 230 }
231 $this->gradestack = array();
232 }
233
234 /**
235 * Internal function
236 */
237 function _push($grade) {
238 array_push($this->gradestack, $grade);
239 }
240
241 /**
242 * Internal function
243 */
244 function _pop() {
d24832f9 245 global $DB;
0f5660f7 246 if (empty($this->gradestack)) {
03cedd62 247 if (!$this->grades_rs) {
0f5660f7 248 return NULL; // no grades present
249 }
250
5c75a0a3 251 if ($this->grades_rs->next()) {
0f5660f7 252 return NULL; // no more grades
253 }
254
5c75a0a3 255 return $this->grades_rs->current();
0f5660f7 256 } else {
257 return array_pop($this->gradestack);
258 }
259 }
260}
261
d08bba83 262/**
263 * Print a selection popup form of the graded users in a course.
264 *
265 * @param int $courseid id of the course
266 * @param string $actionpage The page receiving the data from the popoup form
267 * @param int $userid id of the currently selected user (or 'all' if they are all selected)
268 * @param bool $return If true, will return the HTML, otherwise, will print directly
269 * @return null
270 */
879c99bb 271function print_graded_users_selector($course, $actionpage, $userid=null, $return=false) {
272 global $CFG, $USER;
345674ca 273
879c99bb 274 if (is_null($userid)) {
275 $userid = $USER->id;
276 }
d08bba83 277
278 $context = get_context_instance(CONTEXT_COURSE, $course->id);
279
280 $menu = array(); // Will be a list of userid => user name
281
282 $gui = new graded_users_iterator($course);
283 $gui->init();
345674ca 284
879c99bb 285 if ($userid !== 0) {
286 $menu[0] = get_string('allusers', 'grades');
d08bba83 287 }
345674ca 288
5c75a0a3 289 $nextuser = $gui->next_user();
290
d08bba83 291 while ($userdata = $gui->next_user()) {
292 $user = $userdata->user;
293 $menu[$user->id] = fullname($user);
294 }
295
296 $gui->close();
297
879c99bb 298 if ($userid !== 0) {
299 $menu[0] .= " (" . (count($menu) - 1) . ")";
300 }
301
345674ca 302 return popup_form($CFG->wwwroot.'/grade/' . $actionpage . '&amp;userid=', $menu, 'choosegradeduser', $userid, 'choose', '', '',
303 $return, 'self', get_string('selectalloroneuser', 'grades'));
d08bba83 304}
305
0610812a 306/**
307 * Print grading plugin selection popup form.
308 *
309 * @param int $courseid id of course
310 * @param string $active_type type of plugin on current page - import, export, report or edit
311 * @param string $active_plugin active plugin type - grader, user, cvs, ...
312 * @param boolean $return return as string
313 * @return nothing or string if $return true
314 */
3af29899 315function print_grade_plugin_selector($courseid, $active_type, $active_plugin, $return=false) {
cbff94ba 316 global $CFG;
cbff94ba 317
3af29899 318 $context = get_context_instance(CONTEXT_COURSE, $courseid);
cbff94ba 319
3af29899 320 $menu = array();
6e2f3121 321 $count = 0;
3af29899 322 $active = '';
cbff94ba 323
3af29899 324/// report plugins with its special structure
325 if ($reports = get_list_of_plugins('grade/report', 'CVS')) { // Get all installed reports
326 foreach ($reports as $key => $plugin) { // Remove ones we can't see
327 if (!has_capability('gradereport/'.$plugin.':view', $context)) {
328 unset($reports[$key]);
cbff94ba 329 }
330 }
04678d8e 331 }
3af29899 332 $reportnames = array();
333 if (!empty($reports)) {
334 foreach ($reports as $plugin) {
65dd61bd 335 $url = 'report/'.$plugin.'/index.php?id='.$courseid;
3af29899 336 if ($active_type == 'report' and $active_plugin == $plugin ) {
337 $active = $url;
cbff94ba 338 }
6e2f3121 339 $reportnames[$url] = get_string('modulename', 'gradereport_'.$plugin);
340 $count++;
cbff94ba 341 }
3af29899 342 asort($reportnames);
cbff94ba 343 }
3af29899 344 if (!empty($reportnames)) {
4d526fb1 345 $menu['reportgroup']='--'.get_string('view');
3af29899 346 $menu = $menu+$reportnames;
cbff94ba 347 }
cbff94ba 348
3af29899 349/// standard import plugins
e2008be2 350 if ($imports = get_list_of_plugins('grade/import', 'CVS')) { // Get all installed import plugins
3af29899 351 foreach ($imports as $key => $plugin) { // Remove ones we can't see
352 if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
353 unset($imports[$key]);
cbff94ba 354 }
355 }
356 }
3af29899 357 $importnames = array();
358 if (!empty($imports)) {
359 foreach ($imports as $plugin) {
360 $url = 'import/'.$plugin.'/index.php?id='.$courseid;
65dd61bd 361 if ($active_type == 'import' and $active_plugin == $plugin ) {
3af29899 362 $active = $url;
363 }
6e2f3121 364 $importnames[$url] = get_string('modulename', 'gradeimport_'.$plugin);
365 $count++;
281ffa4a 366 }
3af29899 367 asort($importnames);
281ffa4a 368 }
3af29899 369 if (!empty($importnames)) {
4d526fb1 370 $menu['importgroup']='--'.get_string('importfrom', 'grades');
3af29899 371 $menu = $menu+$importnames;
281ffa4a 372 }
281ffa4a 373
3af29899 374/// standard export plugins
e2008be2 375 if ($exports = get_list_of_plugins('grade/export', 'CVS')) { // Get all installed export plugins
3af29899 376 foreach ($exports as $key => $plugin) { // Remove ones we can't see
377 if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
378 unset($exports[$key]);
281ffa4a 379 }
380 }
cbff94ba 381 }
3af29899 382 $exportnames = array();
383 if (!empty($exports)) {
384 foreach ($exports as $plugin) {
385 $url = 'export/'.$plugin.'/index.php?id='.$courseid;
65dd61bd 386 if ($active_type == 'export' and $active_plugin == $plugin ) {
3af29899 387 $active = $url;
388 }
6e2f3121 389 $exportnames[$url] = get_string('modulename', 'gradeexport_'.$plugin);
390 $count++;
281ffa4a 391 }
3af29899 392 asort($exportnames);
cbff94ba 393 }
3af29899 394 if (!empty($exportnames)) {
4d526fb1 395 $menu['exportgroup']='--'.get_string('exportto', 'grades');
3af29899 396 $menu = $menu+$exportnames;
281ffa4a 397 }
cbff94ba 398
3af29899 399/// editing scripts - not real plugins
78ad5f3f 400 if (has_capability('moodle/grade:manage', $context)
9376f5a6 401 or has_capability('moodle/grade:manageletters', $context)
04259694 402 or has_capability('moodle/course:managescales', $context)
403 or has_capability('moodle/course:update', $context)) {
3af29899 404 $menu['edit']='--'.get_string('edit');
78ad5f3f 405
406 if (has_capability('moodle/grade:manage', $context)) {
407 $url = 'edit/tree/index.php?id='.$courseid;
408 if ($active_type == 'edit' and $active_plugin == 'tree' ) {
409 $active = $url;
410 }
411 $menu[$url] = get_string('edittree', 'grades');
6e2f3121 412 $count++;
78ad5f3f 413 }
414
415 if (has_capability('moodle/course:managescales', $context)) {
416 $url = 'edit/scale/index.php?id='.$courseid;
417 if ($active_type == 'edit' and $active_plugin == 'scale' ) {
418 $active = $url;
419 }
420 $menu[$url] = get_string('scales');
6e2f3121 421 $count++;
78ad5f3f 422 }
423
2b0f65e2 424 if (!empty($CFG->enableoutcomes) && (has_capability('moodle/grade:manage', $context) or
2a598439 425 has_capability('moodle/course:update', $context))) {
426 if (has_capability('moodle/course:update', $context)) { // Default to course assignment
04259694 427 $url = 'edit/outcome/course.php?id='.$courseid;
2a598439 428 } else {
429 $url = 'edit/outcome/index.php?id='.$courseid;
04259694 430 }
78ad5f3f 431 if ($active_type == 'edit' and $active_plugin == 'outcome' ) {
432 $active = $url;
433 }
434 $menu[$url] = get_string('outcomes', 'grades');
6e2f3121 435 $count++;
cbff94ba 436 }
284abb09 437
9376f5a6 438 if (has_capability('moodle/grade:manage', $context) or has_capability('moodle/grade:manageletters', $context)) {
284abb09 439 $url = 'edit/letter/index.php?id='.$courseid;
440 if ($active_type == 'edit' and $active_plugin == 'letter' ) {
441 $active = $url;
442 }
443 $menu[$url] = get_string('letters', 'grades');
6e2f3121 444 $count++;
284abb09 445 }
446
e0724506 447 if (has_capability('moodle/grade:manage', $context)) {
448 $url = 'edit/settings/index.php?id='.$courseid;
449 if ($active_type == 'edit' and $active_plugin == 'settings' ) {
450 $active = $url;
451 }
452 $menu[$url] = get_string('coursesettings', 'grades');
6e2f3121 453 $count++;
e0724506 454 }
455
e58fcb35 456 if (has_capability('moodle/grade:manage', $context)) {
457 $url = 'edit/weights/index.php?id='.$courseid;
458 if ($active_type == 'edit' and $active_plugin == 'weights' ) {
459 $active = $url;
460 }
461 $menu[$url] = get_string('weights', 'grades');
462 $count++;
463 }
281ffa4a 464 }
465
3af29899 466/// finally print/return the popup form
6e2f3121 467 if ($count > 1) {
4d526fb1 468 return popup_form($CFG->wwwroot.'/grade/', $menu, 'choosepluginreport', '',
469 get_string('chooseaction', 'grades'), '', '', $return, 'self');
6e2f3121 470 } else {
471 // only one option - no plugin selector needed
472 return '';
473 }
cbff94ba 474}
475
0610812a 476/**
7a6b7acf 477 * Utility class used for return tracking when using edit and other forms in grade plugins
0610812a 478 */
3af29899 479class grade_plugin_return {
d24832f9 480 public $type;
481 public $plugin;
482 public $courseid;
483 public $userid;
484 public $page;
281ffa4a 485
0610812a 486 /**
487 * Constructor
488 * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
489 */
d24832f9 490 public function grade_plugin_return ($params=null) {
3af29899 491 if (empty($params)) {
492 $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
493 $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
494 $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
495 $this->userid = optional_param('gpr_userid', null, PARAM_INT);
496 $this->page = optional_param('gpr_page', null, PARAM_INT);
a983b6ec 497
a983b6ec 498 } else {
3af29899 499 foreach ($params as $key=>$value) {
500 if (array_key_exists($key, $this)) {
501 $this->$key = $value;
502 }
cbff94ba 503 }
504 }
6cd8c592 505 }
506
0610812a 507 /**
508 * Returns return parameters as options array suitable for buttons.
509 * @return array options
510 */
d24832f9 511 public function get_options() {
7a6b7acf 512 if (empty($this->type)) {
3af29899 513 return array();
865e9a82 514 }
6cd8c592 515
3af29899 516 $params = array();
6cd8c592 517
7a6b7acf 518 if (!empty($this->plugin)) {
519 $params['plugin'] = $this->plugin;
520 }
6cd8c592 521
3af29899 522 if (!empty($this->courseid)) {
523 $params['id'] = $this->courseid;
6cd8c592 524 }
9c61ba4d 525
3af29899 526 if (!empty($this->userid)) {
527 $params['userid'] = $this->userid;
9c61ba4d 528 }
9c61ba4d 529
3af29899 530 if (!empty($this->page)) {
531 $params['page'] = $this->page;
cbff94ba 532 }
865e9a82 533
3af29899 534 return $params;
cbff94ba 535 }
cbff94ba 536
0610812a 537 /**
538 * Returns return url
539 * @param string $default default url when params not set
540 * @return string url
541 */
d24832f9 542 public function get_return_url($default, $extras=null) {
3af29899 543 global $CFG;
cbff94ba 544
3af29899 545 if (empty($this->type) or empty($this->plugin)) {
546 return $default;
cbff94ba 547 }
548
65dd61bd 549 $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
550 $glue = '?';
cbff94ba 551
3af29899 552 if (!empty($this->courseid)) {
553 $url .= $glue.'id='.$this->courseid;
554 $glue = '&amp;';
cbff94ba 555 }
cbff94ba 556
3af29899 557 if (!empty($this->userid)) {
558 $url .= $glue.'userid='.$this->userid;
559 $glue = '&amp;';
cbff94ba 560 }
7e2d7c92 561
3af29899 562 if (!empty($this->page)) {
563 $url .= $glue.'page='.$this->page;
65dd61bd 564 $glue = '&amp;';
565 }
566
567 if (!empty($extras)) {
568 foreach($extras as $key=>$value) {
569 $url .= $glue.$key.'='.$value;
570 $glue = '&amp;';
7a6b7acf 571 }
cbff94ba 572 }
cbff94ba 573
3af29899 574 return $url;
cbff94ba 575 }
cbff94ba 576
0610812a 577 /**
578 * Returns string with hidden return tracking form elements.
579 * @return string
580 */
d24832f9 581 public function get_form_fields() {
7a6b7acf 582 if (empty($this->type)) {
3af29899 583 return '';
cbff94ba 584 }
cbff94ba 585
3af29899 586 $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
7a6b7acf 587
588 if (!empty($this->plugin)) {
589 $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
590 }
0ca5abd6 591
3af29899 592 if (!empty($this->courseid)) {
593 $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
cbff94ba 594 }
cbff94ba 595
3af29899 596 if (!empty($this->userid)) {
597 $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
cbff94ba 598 }
cbff94ba 599
3af29899 600 if (!empty($this->page)) {
601 $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
cbff94ba 602 }
603 }
cbff94ba 604
0610812a 605 /**
606 * Add hidden elements into mform
607 * @param object $mform moodle form object
608 * @return void
609 */
d24832f9 610 public function add_mform_elements(&$mform) {
7a6b7acf 611 if (empty($this->type)) {
3af29899 612 return;
cbff94ba 613 }
cbff94ba 614
3af29899 615 $mform->addElement('hidden', 'gpr_type', $this->type);
616 $mform->setType('gpr_type', PARAM_SAFEDIR);
cbff94ba 617
7a6b7acf 618 if (!empty($this->plugin)) {
619 $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
620 $mform->setType('gpr_plugin', PARAM_SAFEDIR);
621 }
97033c86 622
3af29899 623 if (!empty($this->courseid)) {
624 $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
625 $mform->setType('gpr_courseid', PARAM_INT);
cbff94ba 626 }
cbff94ba 627
3af29899 628 if (!empty($this->userid)) {
629 $mform->addElement('hidden', 'gpr_userid', $this->userid);
630 $mform->setType('gpr_userid', PARAM_INT);
cbff94ba 631 }
cbff94ba 632
3af29899 633 if (!empty($this->page)) {
634 $mform->addElement('hidden', 'gpr_page', $this->page);
635 $mform->setType('gpr_page', PARAM_INT);
cbff94ba 636 }
637 }
281ffa4a 638
0610812a 639 /**
640 * Add return tracking params into url
641 * @param string $url
642 * @return string $url with erturn tracking params
643 */
d24832f9 644 public function add_url_params($url) {
7a6b7acf 645 if (empty($this->type)) {
3af29899 646 return $url;
cbff94ba 647 }
5609f9e6 648
3af29899 649 if (strpos($url, '?') === false) {
650 $url .= '?gpr_type='.$this->type;
651 } else {
652 $url .= '&amp;gpr_type='.$this->type;
cbff94ba 653 }
cbff94ba 654
7a6b7acf 655 if (!empty($this->plugin)) {
656 $url .= '&amp;gpr_plugin='.$this->plugin;
657 }
cbff94ba 658
3af29899 659 if (!empty($this->courseid)) {
660 $url .= '&amp;gpr_courseid='.$this->courseid;
cbff94ba 661 }
cbff94ba 662
3af29899 663 if (!empty($this->userid)) {
664 $url .= '&amp;gpr_userid='.$this->userid;
cbff94ba 665 }
0a8a95c9 666
3af29899 667 if (!empty($this->page)) {
668 $url .= '&amp;gpr_page='.$this->page;
0a8a95c9 669 }
5a412dbf 670
3af29899 671 return $url;
5a412dbf 672 }
5a412dbf 673}
7a6b7acf 674
826c5f86 675/**
676 * Function central to gradebook for building and printing the navigation (breadcrumb trail).
677 * @param string $path The path of the calling script (using __FILE__?)
678 * @param string $pagename The language string to use as the last part of the navigation (non-link)
679 * @param mixed $id Either a plain integer (assuming the key is 'id') or an array of keys and values (e.g courseid => $courseid, itemid...)
680 * @return string
681 */
682function grade_build_nav($path, $pagename=null, $id=null) {
683 global $CFG, $COURSE;
684
685 $strgrades = get_string('grades', 'grades');
686
687 // Parse the path and build navlinks from its elements
688 $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
689 $path = substr($path, $dirroot_length);
690 $path = str_replace('\\', '/', $path);
691
692 $path_elements = explode('/', $path);
693
694 $path_elements_count = count($path_elements);
695
826c5f86 696 // First link is always 'grade'
697 $navlinks = array();
698 $navlinks[] = array('name' => $strgrades,
699 'link' => $CFG->wwwroot.'/grade/index.php?id='.$COURSE->id,
700 'type' => 'misc');
701
702 $link = '';
703 $numberofelements = 3;
704
705 // Prepare URL params string
706 $id_string = '?';
707 if (!is_null($id)) {
708 if (is_array($id)) {
709 foreach ($id as $idkey => $idvalue) {
710 $id_string .= "$idkey=$idvalue&amp;";
711 }
712 } else {
713 $id_string .= "id=$id";
714 }
715 }
716
717 $navlink4 = null;
718
0f78c4de 719 // Remove file extensions from filenames
720 foreach ($path_elements as $key => $filename) {
721 $path_elements[$key] = str_replace('.php', '', $filename);
722 }
723
826c5f86 724 // Second level links
725 switch ($path_elements[1]) {
726 case 'edit': // No link
727 if ($path_elements[3] != 'index.php') {
728 $numberofelements = 4;
729 }
730 break;
731 case 'import': // No link
732 break;
733 case 'export': // No link
734 break;
735 case 'report':
736 // $id is required for this link. Do not print it if $id isn't given
737 if (!is_null($id)) {
738 $link = $CFG->wwwroot . '/grade/report/index.php' . $id_string;
739 }
740
741 if ($path_elements[2] == 'grader') {
742 $numberofelements = 4;
743 }
744 break;
745
746 default:
747 // If this element isn't among the ones already listed above, it isn't supported, throw an error.
748 debugging("grade_build_nav() doesn't support ". $path_elements[1] . " as the second path element after 'grade'.");
749 return false;
750 }
751
752 $navlinks[] = array('name' => get_string($path_elements[1], 'grades'), 'link' => $link, 'type' => 'misc');
753
754 // Third level links
755 if (empty($pagename)) {
756 $pagename = get_string($path_elements[2], 'grades');
757 }
758
759 switch ($numberofelements) {
760 case 3:
761 $navlinks[] = array('name' => $pagename, 'link' => $link, 'type' => 'misc');
762 break;
763 case 4:
764
765 if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
3cf6a6d5 766 $navlinks[] = array('name' => get_string('modulename', 'gradereport_grader'),
826c5f86 767 'link' => "$CFG->wwwroot/grade/report/grader/index.php$id_string",
768 'type' => 'misc');
769 }
770 $navlinks[] = array('name' => $pagename, 'link' => '', 'type' => 'misc');
771 break;
772 }
773 $navigation = build_navigation($navlinks);
774
775 return $navigation;
d4795a07 776}
7a6b7acf 777
e98871a2 778/**
6cc3e350 779 * General structure representing grade items in course
e98871a2 780 */
6cc3e350 781class grade_structure {
d24832f9 782 public $context;
e98871a2 783
d24832f9 784 public $courseid;
e98871a2 785
786 /**
787 * 1D array of grade items only
788 */
d24832f9 789 public $items;
e98871a2 790
6391ebe7 791 /**
6cc3e350 792 * Returns icon of element
793 * @param object $element
794 * @param bool $spacerifnone return spacer if no icon found
795 * @return string icon or spacer
6391ebe7 796 */
d24832f9 797 public function get_element_icon(&$element, $spacerifnone=false) {
6cc3e350 798 global $CFG;
799
800 switch ($element['type']) {
801 case 'item':
802 case 'courseitem':
803 case 'categoryitem':
804 if ($element['object']->is_calculated()) {
805 return '<img src="'.$CFG->pixpath.'/i/calc.gif" class="icon itemicon" alt="'.get_string('calculation', 'grades').'"/>';
806
807 } else if (($element['object']->is_course_item() or $element['object']->is_category_item())
808 and ($element['object']->gradetype == GRADE_TYPE_SCALE or $element['object']->gradetype == GRADE_TYPE_VALUE)) {
809 if ($category = $element['object']->get_item_category()) {
810 switch ($category->aggregation) {
811 case GRADE_AGGREGATE_MEAN:
812 case GRADE_AGGREGATE_MEDIAN:
813 case GRADE_AGGREGATE_WEIGHTED_MEAN:
1426edac 814 case GRADE_AGGREGATE_WEIGHTED_MEAN2:
6cc3e350 815 case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
816 return '<img src="'.$CFG->pixpath.'/i/agg_mean.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
0758a08e 817 case GRADE_AGGREGATE_SUM:
818 return '<img src="'.$CFG->pixpath.'/i/agg_sum.gif" class="icon itemicon" alt="'.get_string('aggregation', 'grades').'"/>';
6cc3e350 819 }
820 }
821
822 } else if ($element['object']->itemtype == 'mod') {
823 return '<img src="'.$CFG->modpixpath.'/'.$element['object']->itemmodule.'/icon.gif" class="icon itemicon" alt="'
824 .get_string('modulename', $element['object']->itemmodule).'"/>';
825
826 } else if ($element['object']->itemtype == 'manual') {
827 if ($element['object']->is_outcome_item()) {
828 return '<img src="'.$CFG->pixpath.'/i/outcomes.gif" class="icon itemicon" alt="'.get_string('outcome', 'grades').'"/>';
829 } else {
a1f21902 830 return '<img src="'.$CFG->pixpath.'/t/manual_item.gif" class="icon itemicon" alt="'.get_string('manualitem', 'grades').'"/>';
6cc3e350 831 }
832 }
833 break;
834
835 case 'category':
836 return '<img src="'.$CFG->pixpath.'/f/folder.gif" class="icon itemicon" alt="'.get_string('category', 'grades').'"/>';
837 }
838
839 if ($spacerifnone) {
840 return '<img src="'.$CFG->wwwroot.'/pix/spacer.gif" class="icon itemicon" alt=""/>';
841 } else {
842 return '';
843 }
844 }
6391ebe7 845
e98871a2 846 /**
6cc3e350 847 * Returns name of element optionally with icon and link
848 * @param object $element
849 * @param bool $withlinks
850 * @param bool $icons
851 * @param bool $spacerifnone return spacer if no icon found
852 * @return header string
e98871a2 853 */
d24832f9 854 public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
6cc3e350 855 global $CFG;
856
857 $header = '';
858
859 if ($icon) {
860 $header .= $this->get_element_icon($element, $spacerifnone);
861 }
862
dab9f423 863 $title = $element['object']->get_name();
864 $header .= $title;
6cc3e350 865
866 if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and $element['type'] != 'courseitem') {
867 return $header;
868 }
869
870 $itemtype = $element['object']->itemtype;
871 $itemmodule = $element['object']->itemmodule;
872 $iteminstance = $element['object']->iteminstance;
873
874 if ($withlink and $itemtype=='mod' and $iteminstance and $itemmodule) {
46d1af82 875 if ($cm = get_coursemodule_from_instance($itemmodule, $iteminstance, $this->courseid)) {
6cc3e350 876
46d1af82 877 $dir = $CFG->dirroot.'/mod/'.$itemmodule;
6cc3e350 878
46d1af82 879 if (file_exists($dir.'/grade.php')) {
880 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/grade.php?id='.$cm->id;
881 } else {
882 $url = $CFG->wwwroot.'/mod/'.$itemmodule.'/view.php?id='.$cm->id;
883 }
6cc3e350 884
dab9f423 885 $header = '<a href="'.$url.'" title="'.$title.'">'.$header.'</a>';
46d1af82 886 }
6cc3e350 887 }
888
889 return $header;
890 }
891
892 /**
893 * Returns the grade eid - the grade may not exist yet.
894 * @param $grade_grade object
895 * @return string eid
896 */
d24832f9 897 public function get_grade_eid($grade_grade) {
6cc3e350 898 if (empty($grade_grade->id)) {
899 return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
900 } else {
901 return 'g'.$grade_grade->id;
902 }
903 }
904
905 /**
906 * Returns the grade_item eid
907 * @param $grade_item object
908 * @return string eid
909 */
d24832f9 910 public function get_item_eid($grade_item) {
6cc3e350 911 return 'i'.$grade_item->id;
912 }
913
9ecd4386 914 function get_params_for_iconstr($element) {
915 $strparams = new stdClass();
916 $strparams->category = '';
917 $strparams->itemname = '';
918 $strparams->itemmodule = '';
919 if (!method_exists($element['object'], 'get_name')) {
920 return $strparams;
921 }
345674ca 922
9ecd4386 923 $strparams->itemname = $element['object']->get_name();
924
925 // If element name is categorytotal, get the name of the parent category
926 if ($strparams->itemname == get_string('categorytotal', 'grades')) {
927 $parent = $element['object']->get_parent_category();
928 $strparams->category = $parent->get_name() . ' ';
929 } else {
930 $strparams->category = '';
931 }
932
933 $strparams->itemmodule = null;
934 if (isset($element['object']->itemmodule)) {
935 $strparams->itemmodule = $element['object']->itemmodule;
345674ca 936 }
9ecd4386 937 return $strparams;
938 }
939
6cc3e350 940 /**
941 * Return edit icon for give element
942 * @param object $element
943 * @return string
944 */
d24832f9 945 public function get_edit_icon($element, $gpr) {
6cc3e350 946 global $CFG;
947
948 if (!has_capability('moodle/grade:manage', $this->context)) {
949 if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
950 // oki - let them override grade
951 } else {
952 return '';
953 }
954 }
955
05aba805 956 static $strfeedback = null;
957 static $streditgrade = null;
958 if (is_null($streditgrade)) {
959 $streditgrade = get_string('editgrade', 'grades');
960 $strfeedback = get_string('feedback');
6cc3e350 961 }
962
9ecd4386 963 $strparams = $this->get_params_for_iconstr($element);
345674ca 964 if ($element['type'] == 'item' or $element['type'] == 'category') {
9ecd4386 965 }
345674ca 966
6cc3e350 967 $object = $element['object'];
968 $overlib = '';
969
970 switch ($element['type']) {
971 case 'item':
972 case 'categoryitem':
973 case 'courseitem':
9ecd4386 974 $stredit = get_string('editverbose', 'grades', $strparams);
6cc3e350 975 if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
976 $url = $CFG->wwwroot.'/grade/edit/tree/item.php?courseid='.$this->courseid.'&amp;id='.$object->id;
977 } else {
978 $url = $CFG->wwwroot.'/grade/edit/tree/outcomeitem.php?courseid='.$this->courseid.'&amp;id='.$object->id;
979 }
980 $url = $gpr->add_url_params($url);
981 break;
982
983 case 'category':
9ecd4386 984 $stredit = get_string('editverbose', 'grades', $strparams);
6cc3e350 985 $url = $CFG->wwwroot.'/grade/edit/tree/category.php?courseid='.$this->courseid.'&amp;id='.$object->id;
986 $url = $gpr->add_url_params($url);
987 break;
988
989 case 'grade':
05aba805 990 $stredit = $streditgrade;
6cc3e350 991 if (empty($object->id)) {
992 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;itemid='.$object->itemid.'&amp;userid='.$object->userid;
993 } else {
994 $url = $CFG->wwwroot.'/grade/edit/tree/grade.php?courseid='.$this->courseid.'&amp;id='.$object->id;
995 }
996 $url = $gpr->add_url_params($url);
997 if (!empty($object->feedback)) {
998 $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
999 $function = "return overlib('$feedback', BORDER, 0, FGCLASS, 'feedback', "
1000 ."CAPTIONFONTCLASS, 'caption', CAPTION, '$strfeedback');";
1001 $overlib = 'onmouseover="'.s($function).'" onmouseout="return nd();"';
1002 }
1003 break;
1004
1005 default:
1006 $url = null;
1007 }
1008
1009 if ($url) {
b244b9b7 1010 return '<a href="'.$url.'" class="edit"><img '.$overlib.' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.$stredit.'" title="'.$stredit.'"/></a>';
6cc3e350 1011
1012 } else {
1013 return '';
1014 }
1015 }
1016
1017 /**
1018 * Return hiding icon for give element
1019 * @param object $element
1020 * @return string
1021 */
d24832f9 1022 public function get_hiding_icon($element, $gpr) {
6cc3e350 1023 global $CFG;
1024
1025 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:hide', $this->context)) {
1026 return '';
1027 }
1028
345674ca 1029 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1030 $strshow = get_string('showverbose', 'grades', $strparams);
345674ca 1031 $strhide = get_string('hideverbose', 'grades', $strparams);
6cc3e350 1032
1033 if ($element['object']->is_hidden()) {
1034 $icon = 'show';
1035 $tooltip = $strshow;
1036
1037 if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) { // Change the icon and add a tooltip showing the date
1038 $icon = 'hiddenuntil';
1039 $tooltip = get_string('hiddenuntildate', 'grades', userdate($element['object']->get_hidden()));
1040 }
1041
1042 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=show&amp;sesskey='.sesskey()
1043 . '&amp;eid='.$element['eid'];
1044 $url = $gpr->add_url_params($url);
b244b9b7 1045 $action = '<a href="'.$url.'" class="hide"><img alt="'.$strshow.'" src="'.$CFG->pixpath.'/t/'.$icon.'.gif" class="iconsmall" title="'.$tooltip.'"/></a>';
6cc3e350 1046
1047 } else {
1048 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=hide&amp;sesskey='.sesskey()
1049 . '&amp;eid='.$element['eid'];
1050 $url = $gpr->add_url_params($url);
b244b9b7 1051 $action = '<a href="'.$url.'" class="hide"><img src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.$strhide.'" title="'.$strhide.'"/></a>';
6cc3e350 1052 }
1053 return $action;
1054 }
1055
1056 /**
2673c733 1057 * Return locking icon for given element
6cc3e350 1058 * @param object $element
1059 * @return string
1060 */
d24832f9 1061 public function get_locking_icon($element, $gpr) {
6cc3e350 1062 global $CFG;
1063
345674ca 1064 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1065 $strunlock = get_string('unlockverbose', 'grades', $strparams);
1066 $strlock = get_string('lockverbose', 'grades', $strparams);
d24832f9 1067
2673c733 1068 // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
1069 if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
1070 $strparamobj = new stdClass();
1071 $strparamobj->itemname = $element['object']->grade_item->itemname;
1072 $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
d24832f9 1073 $action = '<img src="'.$CFG->pixpath.'/t/unlock_gray.gif" alt="'.$strnonunlockable.'" class="iconsmall" title="'.$strnonunlockable.'"/>';
2673c733 1074 } elseif ($element['object']->is_locked()) {
6cc3e350 1075 $icon = 'unlock';
1076 $tooltip = $strunlock;
1077
1078 if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) { // Change the icon and add a tooltip showing the date
1079 $icon = 'locktime';
1080 $tooltip = get_string('locktimedate', 'grades', userdate($element['object']->get_locktime()));
1081 }
1082
1083 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
1084 return '';
1085 }
1086 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=unlock&amp;sesskey='.sesskey()
1087 . '&amp;eid='.$element['eid'];
1088 $url = $gpr->add_url_params($url);
b244b9b7 1089 $action = '<a href="'.$url.'" class="lock"><img src="'.$CFG->pixpath.'/t/'.$icon.'.gif" alt="'.$strunlock.'" class="iconsmall" title="'.$tooltip.'"/></a>';
6cc3e350 1090
1091 } else {
1092 if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
1093 return '';
1094 }
1095 $url = $CFG->wwwroot.'/grade/edit/tree/action.php?id='.$this->courseid.'&amp;action=lock&amp;sesskey='.sesskey()
1096 . '&amp;eid='.$element['eid'];
1097 $url = $gpr->add_url_params($url);
b244b9b7 1098 $action = '<a href="'.$url.'" class="lock"><img src="'.$CFG->pixpath.'/t/lock.gif" class="iconsmall" alt="'.$strlock.'" title="'
6cc3e350 1099 . $strlock.'"/></a>';
1100 }
1101 return $action;
1102 }
1103
1104 /**
1105 * Return calculation icon for given element
1106 * @param object $element
1107 * @return string
1108 */
d24832f9 1109 public function get_calculation_icon($element, $gpr) {
6cc3e350 1110 global $CFG;
1111 if (!has_capability('moodle/grade:manage', $this->context)) {
1112 return '';
1113 }
1114
1115 $calculation_icon = '';
1116
1117 $type = $element['type'];
1118 $object = $element['object'];
1119
9ecd4386 1120
6cc3e350 1121 if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
345674ca 1122 $strparams = $this->get_params_for_iconstr($element);
9ecd4386 1123 $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
6cc3e350 1124
1125 // show calculation icon only when calculation possible
ff1bc603 1126 if (!$object->is_external_item() and ($object->gradetype == GRADE_TYPE_SCALE or $object->gradetype == GRADE_TYPE_VALUE)) {
6cc3e350 1127 if ($object->is_calculated()) {
1128 $icon = 'calc.gif';
1129 } else {
1130 $icon = 'calc_off.gif';
1131 }
1132 $url = $CFG->wwwroot.'/grade/edit/tree/calculation.php?courseid='.$this->courseid.'&amp;id='.$object->id;
1133 $url = $gpr->add_url_params($url);
b244b9b7 1134 $calculation_icon = '<a href="'. $url.'" class="calculation"><img src="'.$CFG->pixpath.'/t/'.$icon.'" class="iconsmall" alt="'
6cc3e350 1135 . $streditcalculation.'" title="'.$streditcalculation.'" /></a>'. "\n";
1136 }
1137 }
1138
1139 return $calculation_icon;
1140 }
1141}
1142
1143/**
1144 * Flat structure similar to grade tree.
1145 */
1146class grade_seq extends grade_structure {
1147
1148 /**
1149 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
1150 * @var string $commonvars
1151 */
d24832f9 1152 public $commonvars;
6cc3e350 1153
1154 /**
1155 * 1D array of elements
1156 */
d24832f9 1157 public $elements;
e98871a2 1158
1159 /**
1160 * Constructor, retrieves and stores array of all grade_category and grade_item
1161 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
1162 * @param int $courseid
1163 * @param boolean $category_grade_last category grade item is the last child
1164 * @param array $collapsed array of collapsed categories
1165 */
d24832f9 1166 public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
e98871a2 1167 global $USER, $CFG;
1168
1169 $this->courseid = $courseid;
973d2660 1170 $this->commonvars = "&amp;sesskey=".sesskey()."&amp;id=$this->courseid";
e98871a2 1171 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
1172
1173 // get course grade tree
1174 $top_element = grade_category::fetch_course_tree($courseid, true);
1175
6391ebe7 1176 $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
1177
1178 foreach ($this->elements as $key=>$unused) {
b89a70ce 1179 $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
6391ebe7 1180 }
e98871a2 1181 }
1182
1183 /**
1184 * Static recursive helper - makes the grade_item for category the last children
1185 * @static
1186 * @param array $element The seed of the recursion
1187 * @return void
1188 */
d24832f9 1189 public function flatten(&$element, $category_grade_last, $nooutcomes) {
e98871a2 1190 if (empty($element['children'])) {
1191 return array();
1192 }
1193 $children = array();
1194
1195 foreach ($element['children'] as $sortorder=>$unused) {
1196 if ($nooutcomes and $element['type'] != 'category' and $element['children'][$sortorder]['object']->is_outcome_item()) {
1197 continue;
1198 }
1199 $children[] = $element['children'][$sortorder];
1200 }
1201 unset($element['children']);
1202
1203 if ($category_grade_last and count($children) > 1) {
1204 $cat_item = array_shift($children);
1205 array_push($children, $cat_item);
1206 }
1207
1208 $result = array();
1209 foreach ($children as $child) {
e0724506 1210 if ($child['type'] == 'category') {
6391ebe7 1211 $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
e98871a2 1212 } else {
1213 $child['eid'] = 'i'.$child['object']->id;
6391ebe7 1214 $result[$child['object']->id] = $child;
e98871a2 1215 }
1216 }
1217
1218 return $result;
1219 }
1220
1221 /**
1222 * Parses the array in search of a given eid and returns a element object with
1223 * information about the element it has found.
1224 * @param int $eid
1225 * @return object element
1226 */
d24832f9 1227 public function locate_element($eid) {
e98871a2 1228 // it is a grade - construct a new object
1229 if (strpos($eid, 'n') === 0) {
1230 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1231 return null;
1232 }
1233
1234 $itemid = $matches[1];
1235 $userid = $matches[2];
1236
1237 //extra security check - the grade item must be in this tree
1238 if (!$item_el = $this->locate_element('i'.$itemid)) {
1239 return null;
1240 }
1241
1242 // $gradea->id may be null - means does not exist yet
1243 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1244
1245 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1246 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1247
1248 } else if (strpos($eid, 'g') === 0) {
1249 $id = (int)substr($eid, 1);
1250 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1251 return null;
1252 }
1253 //extra security check - the grade item must be in this tree
1254 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1255 return null;
1256 }
1257 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1258 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1259 }
1260
1261 // it is a category or item
6391ebe7 1262 foreach ($this->elements as $element) {
6cc3e350 1263 if ($element['eid'] == $eid) {
1264 return $element;
1265 }
e98871a2 1266 }
6cc3e350 1267
1268 return null;
e98871a2 1269 }
e98871a2 1270}
1271
7a6b7acf 1272/**
1273 * This class represents a complete tree of categories, grade_items and final grades,
1274 * organises as an array primarily, but which can also be converted to other formats.
1275 * It has simple method calls with complex implementations, allowing for easy insertion,
1276 * deletion and moving of items and categories within the tree.
1277 */
6cc3e350 1278class grade_tree extends grade_structure {
7a6b7acf 1279
1280 /**
1281 * The basic representation of the tree as a hierarchical, 3-tiered array.
1282 * @var object $top_element
1283 */
d24832f9 1284 public $top_element;
7a6b7acf 1285
1286 /**
1287 * A string of GET URL variables, namely courseid and sesskey, used in most URLs built by this class.
1288 * @var string $commonvars
1289 */
d24832f9 1290 public $commonvars;
7a6b7acf 1291
1292 /**
1293 * 2D array of grade items and categories
1294 */
d24832f9 1295 public $levels;
7a6b7acf 1296
b89a70ce 1297 /**
1298 * Grade items
1299 */
d24832f9 1300 public $items;
b89a70ce 1301
7a6b7acf 1302 /**
1303 * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
e98871a2 1304 * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
7a6b7acf 1305 * @param int $courseid
1306 * @param boolean $fillers include fillers and colspans, make the levels var "rectangular"
1307 * @param boolean $category_grade_last category grade item is the last child
4faf5f99 1308 * @param array $collapsed array of collapsed categories
7a6b7acf 1309 */
d24832f9 1310 public function grade_tree($courseid, $fillers=true, $category_grade_last=false, $collapsed=null, $nooutcomes=false) {
7a6b7acf 1311 global $USER, $CFG;
1312
1313 $this->courseid = $courseid;
973d2660 1314 $this->commonvars = "&amp;sesskey=".sesskey()."&amp;id=$this->courseid";
7a6b7acf 1315 $this->levels = array();
2cc773f5 1316 $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
7a6b7acf 1317
1318 // get course grade tree
1319 $this->top_element = grade_category::fetch_course_tree($courseid, true);
1320
4faf5f99 1321 // collapse the categories if requested
1322 if (!empty($collapsed)) {
1323 grade_tree::category_collapse($this->top_element, $collapsed);
1324 }
1325
aea4df41 1326 // no otucomes if requested
1327 if (!empty($nooutcomes)) {
1328 grade_tree::no_outcomes($this->top_element);
1329 }
1330
4faf5f99 1331 // move category item to last position in category
7a6b7acf 1332 if ($category_grade_last) {
1333 grade_tree::category_grade_last($this->top_element);
1334 }
1335
1336 if ($fillers) {
1337 // inject fake categories == fillers
1338 grade_tree::inject_fillers($this->top_element, 0);
1339 // add colspans to categories and fillers
1340 grade_tree::inject_colspans($this->top_element);
1341 }
1342
1343 grade_tree::fill_levels($this->levels, $this->top_element, 0);
d297269d 1344
7a6b7acf 1345 }
1346
4faf5f99 1347 /**
1348 * Static recursive helper - removes items from collapsed categories
1349 * @static
1350 * @param array $element The seed of the recursion
1351 * @param array $collapsed array of collapsed categories
1352 * @return void
1353 */
d24832f9 1354 public function category_collapse(&$element, $collapsed) {
4faf5f99 1355 if ($element['type'] != 'category') {
1356 return;
1357 }
1358 if (empty($element['children']) or count($element['children']) < 2) {
1359 return;
1360 }
1361
384960dd 1362 if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
4faf5f99 1363 $category_item = reset($element['children']); //keep only category item
1364 $element['children'] = array(key($element['children'])=>$category_item);
1365
1366 } else {
384960dd 1367 if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
1368 reset($element['children']);
1369 $first_key = key($element['children']);
1370 unset($element['children'][$first_key]);
1371 }
1372 foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
4faf5f99 1373 grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
1374 }
1375 }
1376 }
7a6b7acf 1377
aea4df41 1378 /**
1379 * Static recursive helper - removes all outcomes
1380 * @static
1381 * @param array $element The seed of the recursion
1382 * @return void
1383 */
d24832f9 1384 public function no_outcomes(&$element) {
aea4df41 1385 if ($element['type'] != 'category') {
1386 return;
1387 }
1388 foreach ($element['children'] as $sortorder=>$child) {
1389 if ($element['children'][$sortorder]['type'] == 'item'
1390 and $element['children'][$sortorder]['object']->is_outcome_item()) {
1391 unset($element['children'][$sortorder]);
1392
d4795a07 1393 } else if ($element['children'][$sortorder]['type'] == 'category') {
aea4df41 1394 grade_tree::no_outcomes($element['children'][$sortorder]);
1395 }
1396 }
1397 }
1398
7a6b7acf 1399 /**
1400 * Static recursive helper - makes the grade_item for category the last children
1401 * @static
1402 * @param array $element The seed of the recursion
1403 * @return void
1404 */
d24832f9 1405 public function category_grade_last(&$element) {
7a6b7acf 1406 if (empty($element['children'])) {
1407 return;
1408 }
1409 if (count($element['children']) < 2) {
1410 return;
1411 }
3e0e2436 1412 $first_item = reset($element['children']);
4a3dfd9a 1413 if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
3e0e2436 1414 // the category item might have been already removed
1415 $order = key($element['children']);
1416 unset($element['children'][$order]);
1417 $element['children'][$order] =& $first_item;
1418 }
206f9953 1419 foreach ($element['children'] as $sortorder => $child) {
7a6b7acf 1420 grade_tree::category_grade_last($element['children'][$sortorder]);
1421 }
1422 }
1423
1424 /**
1425 * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
1426 * @static
1427 * @param int $levels
1428 * @param array $element The seed of the recursion
1429 * @param int $depth
1430 * @return void
1431 */
d24832f9 1432 public function fill_levels(&$levels, &$element, $depth) {
7a6b7acf 1433 if (!array_key_exists($depth, $levels)) {
1434 $levels[$depth] = array();
1435 }
1436
1437 // prepare unique identifier
1438 if ($element['type'] == 'category') {
1439 $element['eid'] = 'c'.$element['object']->id;
1440 } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
1441 $element['eid'] = 'i'.$element['object']->id;
b89a70ce 1442 $this->items[$element['object']->id] =& $element['object'];
7a6b7acf 1443 }
1444
1445 $levels[$depth][] =& $element;
1446 $depth++;
1447 if (empty($element['children'])) {
1448 return;
1449 }
1450 $prev = 0;
1451 foreach ($element['children'] as $sortorder=>$child) {
1452 grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
1453 $element['children'][$sortorder]['prev'] = $prev;
1454 $element['children'][$sortorder]['next'] = 0;
1455 if ($prev) {
1456 $element['children'][$prev]['next'] = $sortorder;
1457 }
1458 $prev = $sortorder;
1459 }
1460 }
1461
1462 /**
1463 * Static recursive helper - makes full tree (all leafes are at the same level)
1464 */
d24832f9 1465 public function inject_fillers(&$element, $depth) {
7a6b7acf 1466 $depth++;
1467
1468 if (empty($element['children'])) {
1469 return $depth;
1470 }
1471 $chdepths = array();
1472 $chids = array_keys($element['children']);
1473 $last_child = end($chids);
1474 $first_child = reset($chids);
1475
1476 foreach ($chids as $chid) {
1477 $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
1478 }
1479 arsort($chdepths);
1480
1481 $maxdepth = reset($chdepths);
1482 foreach ($chdepths as $chid=>$chd) {
1483 if ($chd == $maxdepth) {
1484 continue;
1485 }
1486 for ($i=0; $i < $maxdepth-$chd; $i++) {
1487 if ($chid == $first_child) {
1488 $type = 'fillerfirst';
1489 } else if ($chid == $last_child) {
1490 $type = 'fillerlast';
1491 } else {
1492 $type = 'filler';
1493 }
1494 $oldchild =& $element['children'][$chid];
1495 $element['children'][$chid] = array('object'=>'filler', 'type'=>$type, 'eid'=>'', 'depth'=>$element['object']->depth,'children'=>array($oldchild));
1496 }
1497 }
1498
1499 return $maxdepth;
1500 }
1501
1502 /**
1503 * Static recursive helper - add colspan information into categories
1504 */
d24832f9 1505 public function inject_colspans(&$element) {
7a6b7acf 1506 if (empty($element['children'])) {
1507 return 1;
1508 }
1509 $count = 0;
1510 foreach ($element['children'] as $key=>$child) {
1511 $count += grade_tree::inject_colspans($element['children'][$key]);
1512 }
1513 $element['colspan'] = $count;
1514 return $count;
1515 }
1516
1517 /**
1518 * Parses the array in search of a given eid and returns a element object with
1519 * information about the element it has found.
1520 * @param int $eid
1521 * @return object element
1522 */
d24832f9 1523 public function locate_element($eid) {
d3c3da1b 1524 // it is a grade - construct a new object
1525 if (strpos($eid, 'n') === 0) {
1526 if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
1527 return null;
1528 }
1529
1530 $itemid = $matches[1];
1531 $userid = $matches[2];
1532
1533 //extra security check - the grade item must be in this tree
1534 if (!$item_el = $this->locate_element('i'.$itemid)) {
1535 return null;
1536 }
1537
1538 // $gradea->id may be null - means does not exist yet
1539 $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
1540
1541 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1542 return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
1543
1544 } else if (strpos($eid, 'g') === 0) {
7a6b7acf 1545 $id = (int)substr($eid, 1);
1546 if (!$grade = grade_grade::fetch(array('id'=>$id))) {
1547 return null;
1548 }
1549 //extra security check - the grade item must be in this tree
1550 if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
1551 return null;
1552 }
1553 $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
1554 return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
1555 }
1556
1557 // it is a category or item
1558 foreach ($this->levels as $row) {
1559 foreach ($row as $element) {
1560 if ($element['type'] == 'filler') {
1561 continue;
1562 }
1563 if ($element['eid'] == $eid) {
1564 return $element;
1565 }
1566 }
1567 }
1568
1569 return null;
1570 }
d24832f9 1571
b244b9b7 1572 /**
1573 * Returns a well-formed XML representation of the grade-tree using recursion.
1574 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
1575 * @return string $xml
1576 */
d24832f9 1577 public function exportToXML($root=null, $tabs="\t") {
b244b9b7 1578 $xml = null;
1579 $first = false;
1580 if (is_null($root)) {
1581 $root = $this->top_element;
1582 $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
1583 $xml .= "<gradetree>\n";
1584 $first = true;
1585 }
d24832f9 1586
b244b9b7 1587 $type = 'undefined';
1588 if (strpos($root['object']->table, 'grade_categories') !== false) {
1589 $type = 'category';
1590 } elseif (strpos($root['object']->table, 'grade_items') !== false) {
1591 $type = 'item';
1592 } elseif (strpos($root['object']->table, 'grade_outcomes') !== false) {
1593 $type = 'outcome';
1594 }
d24832f9 1595
b244b9b7 1596 $xml .= "$tabs<element type=\"$type\">\n";
1597 foreach ($root['object'] as $var => $value) {
1598 if (!is_object($value) && !is_array($value) && !empty($value)) {
1599 $xml .= "$tabs\t<$var>$value</$var>\n";
1600 }
1601 }
1602
1603 if (!empty($root['children'])) {
1604 $xml .= "$tabs\t<children>\n";
1605 foreach ($root['children'] as $sortorder => $child) {
1606 $xml .= $this->exportToXML($child, $tabs."\t\t");
1607 }
1608 $xml .= "$tabs\t</children>\n";
1609 }
d24832f9 1610
b244b9b7 1611 $xml .= "$tabs</element>\n";
1612
1613 if ($first) {
1614 $xml .= "</gradetree>";
1615 }
d24832f9 1616
b244b9b7 1617 return $xml;
1618 }
d24832f9 1619
b244b9b7 1620 /**
1621 * Returns a JSON representation of the grade-tree using recursion.
1622 * @param array $root The current element in the recursion. If null, starts at the top of the tree.
1623 * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
1624 * @param int $switch The position (first or last) of the aggregations
1625 * @return string $xml
1626 */
d24832f9 1627 public function exportToJSON($root=null, $tabs="\t") {
b244b9b7 1628 $json = null;
1629 $first = false;
1630 if (is_null($root)) {
1631 $root = $this->top_element;
1632 $first = true;
1633 }
d24832f9 1634
b244b9b7 1635 $name = '';
1636
1637
1638 if (strpos($root['object']->table, 'grade_categories') !== false) {
1639 $name = $root['object']->fullname;
1640 if ($name == '?') {
d24832f9 1641 $name = $root['object']->get_name();
b244b9b7 1642 }
1643 } elseif (strpos($root['object']->table, 'grade_items') !== false) {
1644 $name = $root['object']->itemname;
1645 } elseif (strpos($root['object']->table, 'grade_outcomes') !== false) {
1646 $name = $root['object']->itemname;
1647 }
d24832f9 1648
b244b9b7 1649 $json .= "$tabs {\n";
1650 $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
1651 $json .= "$tabs\t \"name\": \"$name\",\n";
1652
1653 foreach ($root['object'] as $var => $value) {
1654 if (!is_object($value) && !is_array($value) && !empty($value)) {
1655 $json .= "$tabs\t \"$var\": \"$value\",\n";
1656 }
1657 }
d24832f9 1658
b244b9b7 1659 $json = substr($json, 0, strrpos($json, ','));
d24832f9 1660
b244b9b7 1661 if (!empty($root['children'])) {
1662 $json .= ",\n$tabs\t\"children\": [\n";
1663 foreach ($root['children'] as $sortorder => $child) {
1664 $json .= $this->exportToJSON($child, $tabs."\t\t");
1665 }
1666 $json = substr($json, 0, strrpos($json, ','));
1667 $json .= "\n$tabs\t]\n";
d24832f9 1668 }
b244b9b7 1669
1670 if ($first) {
1671 $json .= "\n}";
1672 } else {
1673 $json .= "\n$tabs},\n";
1674 }
d24832f9 1675
b244b9b7 1676 return $json;
1677 }
d24832f9 1678
1679 public function get_levels() {
1680 return $this->levels;
1681 }
1682
1683 public function get_items() {
1684 return $this->items;
1685 }
1686
1687 public function get_item($itemid) {
1688 if (array_key_exists($itemid, $this->items)) {
1689 return $this->items[$itemid];
1690 } else {
1691 return false;
1692 }
1693 }
7a6b7acf 1694}
1695
e2008be2 1696?>