PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/grade/lib.php

https://bitbucket.org/bmbrands/swets
PHP | 2509 lines | 1705 code | 257 blank | 547 comment | 314 complexity | 7ffc0bbce945897a71ac25bcbb57bef3 MD5 | raw file
Possible License(s): Apache-2.0, GPL-3.0, GPL-2.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception
  1. <?php
  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. /**
  17. * Functions used by gradebook plugins and reports.
  18. *
  19. * @package moodlecore
  20. * @copyright 2009 Petr Skoda and Nicolas Connault
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. require_once $CFG->libdir.'/gradelib.php';
  24. /**
  25. * This class iterates over all users that are graded in a course.
  26. * Returns detailed info about users and their grades.
  27. *
  28. * @author Petr Skoda <skodak@moodle.org>
  29. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  30. */
  31. class graded_users_iterator {
  32. public $course;
  33. public $grade_items;
  34. public $groupid;
  35. public $users_rs;
  36. public $grades_rs;
  37. public $gradestack;
  38. public $sortfield1;
  39. public $sortorder1;
  40. public $sortfield2;
  41. public $sortorder2;
  42. /**
  43. * Constructor
  44. *
  45. * @param object $course A course object
  46. * @param array $grade_items array of grade items, if not specified only user info returned
  47. * @param int $groupid iterate only group users if present
  48. * @param string $sortfield1 The first field of the users table by which the array of users will be sorted
  49. * @param string $sortorder1 The order in which the first sorting field will be sorted (ASC or DESC)
  50. * @param string $sortfield2 The second field of the users table by which the array of users will be sorted
  51. * @param string $sortorder2 The order in which the second sorting field will be sorted (ASC or DESC)
  52. */
  53. public function graded_users_iterator($course, $grade_items=null, $groupid=0,
  54. $sortfield1='lastname', $sortorder1='ASC',
  55. $sortfield2='firstname', $sortorder2='ASC') {
  56. $this->course = $course;
  57. $this->grade_items = $grade_items;
  58. $this->groupid = $groupid;
  59. $this->sortfield1 = $sortfield1;
  60. $this->sortorder1 = $sortorder1;
  61. $this->sortfield2 = $sortfield2;
  62. $this->sortorder2 = $sortorder2;
  63. $this->gradestack = array();
  64. }
  65. /**
  66. * Initialise the iterator
  67. * @return boolean success
  68. */
  69. public function init() {
  70. global $CFG, $DB;
  71. $this->close();
  72. grade_regrade_final_grades($this->course->id);
  73. $course_item = grade_item::fetch_course_item($this->course->id);
  74. if ($course_item->needsupdate) {
  75. // can not calculate all final grades - sorry
  76. return false;
  77. }
  78. $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
  79. $relatedcontexts = get_related_contexts_string($coursecontext);
  80. list($gradebookroles_sql, $params) =
  81. $DB->get_in_or_equal(explode(',', $CFG->gradebookroles), SQL_PARAMS_NAMED, 'grbr');
  82. //limit to users with an active enrolment
  83. list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext);
  84. $params = array_merge($params, $enrolledparams);
  85. if ($this->groupid) {
  86. $groupsql = "INNER JOIN {groups_members} gm ON gm.userid = u.id";
  87. $groupwheresql = "AND gm.groupid = :groupid";
  88. // $params contents: gradebookroles
  89. $params['groupid'] = $this->groupid;
  90. } else {
  91. $groupsql = "";
  92. $groupwheresql = "";
  93. }
  94. if (empty($this->sortfield1)) {
  95. // we must do some sorting even if not specified
  96. $ofields = ", u.id AS usrt";
  97. $order = "usrt ASC";
  98. } else {
  99. $ofields = ", u.$this->sortfield1 AS usrt1";
  100. $order = "usrt1 $this->sortorder1";
  101. if (!empty($this->sortfield2)) {
  102. $ofields .= ", u.$this->sortfield2 AS usrt2";
  103. $order .= ", usrt2 $this->sortorder2";
  104. }
  105. if ($this->sortfield1 != 'id' and $this->sortfield2 != 'id') {
  106. // user order MUST be the same in both queries,
  107. // must include the only unique user->id if not already present
  108. $ofields .= ", u.id AS usrt";
  109. $order .= ", usrt ASC";
  110. }
  111. }
  112. // $params contents: gradebookroles and groupid (for $groupwheresql)
  113. $users_sql = "SELECT u.* $ofields
  114. FROM {user} u
  115. JOIN ($enrolledsql) je ON je.id = u.id
  116. $groupsql
  117. JOIN (
  118. SELECT DISTINCT ra.userid
  119. FROM {role_assignments} ra
  120. WHERE ra.roleid $gradebookroles_sql
  121. AND ra.contextid $relatedcontexts
  122. ) rainner ON rainner.userid = u.id
  123. WHERE u.deleted = 0
  124. $groupwheresql
  125. ORDER BY $order";
  126. $this->users_rs = $DB->get_recordset_sql($users_sql, $params);
  127. if (!empty($this->grade_items)) {
  128. $itemids = array_keys($this->grade_items);
  129. list($itemidsql, $grades_params) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED, 'items');
  130. $params = array_merge($params, $grades_params);
  131. // $params contents: gradebookroles, enrolledparams, groupid (for $groupwheresql) and itemids
  132. $grades_sql = "SELECT g.* $ofields
  133. FROM {grade_grades} g
  134. JOIN {user} u ON g.userid = u.id
  135. JOIN ($enrolledsql) je ON je.id = u.id
  136. $groupsql
  137. JOIN (
  138. SELECT DISTINCT ra.userid
  139. FROM {role_assignments} ra
  140. WHERE ra.roleid $gradebookroles_sql
  141. AND ra.contextid $relatedcontexts
  142. ) rainner ON rainner.userid = u.id
  143. WHERE u.deleted = 0
  144. AND g.itemid $itemidsql
  145. $groupwheresql
  146. ORDER BY $order, g.itemid ASC";
  147. $this->grades_rs = $DB->get_recordset_sql($grades_sql, $params);
  148. } else {
  149. $this->grades_rs = false;
  150. }
  151. return true;
  152. }
  153. /**
  154. * Returns information about the next user
  155. * @return mixed array of user info, all grades and feedback or null when no more users found
  156. */
  157. function next_user() {
  158. if (!$this->users_rs) {
  159. return false; // no users present
  160. }
  161. if (!$this->users_rs->valid()) {
  162. if ($current = $this->_pop()) {
  163. // this is not good - user or grades updated between the two reads above :-(
  164. }
  165. return false; // no more users
  166. } else {
  167. $user = $this->users_rs->current();
  168. $this->users_rs->next();
  169. }
  170. // find grades of this user
  171. $grade_records = array();
  172. while (true) {
  173. if (!$current = $this->_pop()) {
  174. break; // no more grades
  175. }
  176. if (empty($current->userid)) {
  177. break;
  178. }
  179. if ($current->userid != $user->id) {
  180. // grade of the next user, we have all for this user
  181. $this->_push($current);
  182. break;
  183. }
  184. $grade_records[$current->itemid] = $current;
  185. }
  186. $grades = array();
  187. $feedbacks = array();
  188. if (!empty($this->grade_items)) {
  189. foreach ($this->grade_items as $grade_item) {
  190. if (array_key_exists($grade_item->id, $grade_records)) {
  191. $feedbacks[$grade_item->id]->feedback = $grade_records[$grade_item->id]->feedback;
  192. $feedbacks[$grade_item->id]->feedbackformat = $grade_records[$grade_item->id]->feedbackformat;
  193. unset($grade_records[$grade_item->id]->feedback);
  194. unset($grade_records[$grade_item->id]->feedbackformat);
  195. $grades[$grade_item->id] = new grade_grade($grade_records[$grade_item->id], false);
  196. } else {
  197. $feedbacks[$grade_item->id]->feedback = '';
  198. $feedbacks[$grade_item->id]->feedbackformat = FORMAT_MOODLE;
  199. $grades[$grade_item->id] =
  200. new grade_grade(array('userid'=>$user->id, 'itemid'=>$grade_item->id), false);
  201. }
  202. }
  203. }
  204. $result = new stdClass();
  205. $result->user = $user;
  206. $result->grades = $grades;
  207. $result->feedbacks = $feedbacks;
  208. return $result;
  209. }
  210. /**
  211. * Close the iterator, do not forget to call this function.
  212. * @return void
  213. */
  214. function close() {
  215. if ($this->users_rs) {
  216. $this->users_rs->close();
  217. $this->users_rs = null;
  218. }
  219. if ($this->grades_rs) {
  220. $this->grades_rs->close();
  221. $this->grades_rs = null;
  222. }
  223. $this->gradestack = array();
  224. }
  225. /**
  226. * _push
  227. *
  228. * @param grade_grade $grade Grade object
  229. *
  230. * @return void
  231. */
  232. function _push($grade) {
  233. array_push($this->gradestack, $grade);
  234. }
  235. /**
  236. * _pop
  237. *
  238. * @return object current grade object
  239. */
  240. function _pop() {
  241. global $DB;
  242. if (empty($this->gradestack)) {
  243. if (empty($this->grades_rs) || !$this->grades_rs->valid()) {
  244. return null; // no grades present
  245. }
  246. $current = $this->grades_rs->current();
  247. $this->grades_rs->next();
  248. return $current;
  249. } else {
  250. return array_pop($this->gradestack);
  251. }
  252. }
  253. }
  254. /**
  255. * Print a selection popup form of the graded users in a course.
  256. *
  257. * @deprecated since 2.0
  258. *
  259. * @param int $course id of the course
  260. * @param string $actionpage The page receiving the data from the popoup form
  261. * @param int $userid id of the currently selected user (or 'all' if they are all selected)
  262. * @param int $groupid id of requested group, 0 means all
  263. * @param int $includeall bool include all option
  264. * @param bool $return If true, will return the HTML, otherwise, will print directly
  265. * @return null
  266. */
  267. function print_graded_users_selector($course, $actionpage, $userid=0, $groupid=0, $includeall=true, $return=false) {
  268. global $CFG, $USER, $OUTPUT;
  269. return $OUTPUT->render(grade_get_graded_users_select(substr($actionpage, 0, strpos($actionpage, '/')), $course, $userid, $groupid, $includeall));
  270. }
  271. function grade_get_graded_users_select($report, $course, $userid, $groupid, $includeall) {
  272. global $USER;
  273. if (is_null($userid)) {
  274. $userid = $USER->id;
  275. }
  276. $menu = array(); // Will be a list of userid => user name
  277. $gui = new graded_users_iterator($course, null, $groupid);
  278. $gui->init();
  279. $label = get_string('selectauser', 'grades');
  280. if ($includeall) {
  281. $menu[0] = get_string('allusers', 'grades');
  282. $label = get_string('selectalloroneuser', 'grades');
  283. }
  284. while ($userdata = $gui->next_user()) {
  285. $user = $userdata->user;
  286. $menu[$user->id] = fullname($user);
  287. }
  288. $gui->close();
  289. if ($includeall) {
  290. $menu[0] .= " (" . (count($menu) - 1) . ")";
  291. }
  292. $select = new single_select(new moodle_url('/grade/report/'.$report.'/index.php', array('id'=>$course->id)), 'userid', $menu, $userid);
  293. $select->label = $label;
  294. $select->formid = 'choosegradeuser';
  295. return $select;
  296. }
  297. /**
  298. * Print grading plugin selection popup form.
  299. *
  300. * @param array $plugin_info An array of plugins containing information for the selector
  301. * @param boolean $return return as string
  302. *
  303. * @return nothing or string if $return true
  304. */
  305. function print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return=false) {
  306. global $CFG, $OUTPUT, $PAGE;
  307. $menu = array();
  308. $count = 0;
  309. $active = '';
  310. foreach ($plugin_info as $plugin_type => $plugins) {
  311. if ($plugin_type == 'strings') {
  312. continue;
  313. }
  314. $first_plugin = reset($plugins);
  315. $sectionname = $plugin_info['strings'][$plugin_type];
  316. $section = array();
  317. foreach ($plugins as $plugin) {
  318. $link = $plugin->link->out(false);
  319. $section[$link] = $plugin->string;
  320. $count++;
  321. if ($plugin_type === $active_type and $plugin->id === $active_plugin) {
  322. $active = $link;
  323. }
  324. }
  325. if ($section) {
  326. $menu[] = array($sectionname=>$section);
  327. }
  328. }
  329. // finally print/return the popup form
  330. if ($count > 1) {
  331. $select = new url_select($menu, $active, null, 'choosepluginreport');
  332. if ($return) {
  333. return $OUTPUT->render($select);
  334. } else {
  335. echo $OUTPUT->render($select);
  336. }
  337. } else {
  338. // only one option - no plugin selector needed
  339. return '';
  340. }
  341. }
  342. /**
  343. * Print grading plugin selection tab-based navigation.
  344. *
  345. * @param string $active_type type of plugin on current page - import, export, report or edit
  346. * @param string $active_plugin active plugin type - grader, user, cvs, ...
  347. * @param array $plugin_info Array of plugins
  348. * @param boolean $return return as string
  349. *
  350. * @return nothing or string if $return true
  351. */
  352. function grade_print_tabs($active_type, $active_plugin, $plugin_info, $return=false) {
  353. global $CFG, $COURSE;
  354. if (!isset($currenttab)) { //TODO: this is weird
  355. $currenttab = '';
  356. }
  357. $tabs = array();
  358. $top_row = array();
  359. $bottom_row = array();
  360. $inactive = array($active_plugin);
  361. $activated = array();
  362. $count = 0;
  363. $active = '';
  364. foreach ($plugin_info as $plugin_type => $plugins) {
  365. if ($plugin_type == 'strings') {
  366. continue;
  367. }
  368. // If $plugins is actually the definition of a child-less parent link:
  369. if (!empty($plugins->id)) {
  370. $string = $plugins->string;
  371. if (!empty($plugin_info[$active_type]->parent)) {
  372. $string = $plugin_info[$active_type]->parent->string;
  373. }
  374. $top_row[] = new tabobject($plugin_type, $plugins->link, $string);
  375. continue;
  376. }
  377. $first_plugin = reset($plugins);
  378. $url = $first_plugin->link;
  379. if ($plugin_type == 'report') {
  380. $url = $CFG->wwwroot.'/grade/report/index.php?id='.$COURSE->id;
  381. }
  382. $top_row[] = new tabobject($plugin_type, $url, $plugin_info['strings'][$plugin_type]);
  383. if ($active_type == $plugin_type) {
  384. foreach ($plugins as $plugin) {
  385. $bottom_row[] = new tabobject($plugin->id, $plugin->link, $plugin->string);
  386. if ($plugin->id == $active_plugin) {
  387. $inactive = array($plugin->id);
  388. }
  389. }
  390. }
  391. }
  392. $tabs[] = $top_row;
  393. $tabs[] = $bottom_row;
  394. if ($return) {
  395. return print_tabs($tabs, $active_type, $inactive, $activated, true);
  396. } else {
  397. print_tabs($tabs, $active_type, $inactive, $activated);
  398. }
  399. }
  400. /**
  401. * grade_get_plugin_info
  402. *
  403. * @param int $courseid The course id
  404. * @param string $active_type type of plugin on current page - import, export, report or edit
  405. * @param string $active_plugin active plugin type - grader, user, cvs, ...
  406. *
  407. * @return array
  408. */
  409. function grade_get_plugin_info($courseid, $active_type, $active_plugin) {
  410. global $CFG, $SITE;
  411. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  412. $plugin_info = array();
  413. $count = 0;
  414. $active = '';
  415. $url_prefix = $CFG->wwwroot . '/grade/';
  416. // Language strings
  417. $plugin_info['strings'] = grade_helper::get_plugin_strings();
  418. if ($reports = grade_helper::get_plugins_reports($courseid)) {
  419. $plugin_info['report'] = $reports;
  420. }
  421. //showing grade categories and items make no sense if we're not within a course
  422. if ($courseid!=$SITE->id) {
  423. if ($edittree = grade_helper::get_info_edit_structure($courseid)) {
  424. $plugin_info['edittree'] = $edittree;
  425. }
  426. }
  427. if ($scale = grade_helper::get_info_scales($courseid)) {
  428. $plugin_info['scale'] = array('view'=>$scale);
  429. }
  430. if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
  431. $plugin_info['outcome'] = $outcomes;
  432. }
  433. if ($letters = grade_helper::get_info_letters($courseid)) {
  434. $plugin_info['letter'] = $letters;
  435. }
  436. if ($imports = grade_helper::get_plugins_import($courseid)) {
  437. $plugin_info['import'] = $imports;
  438. }
  439. if ($exports = grade_helper::get_plugins_export($courseid)) {
  440. $plugin_info['export'] = $exports;
  441. }
  442. foreach ($plugin_info as $plugin_type => $plugins) {
  443. if (!empty($plugins->id) && $active_plugin == $plugins->id) {
  444. $plugin_info['strings']['active_plugin_str'] = $plugins->string;
  445. break;
  446. }
  447. foreach ($plugins as $plugin) {
  448. if (is_a($plugin, 'grade_plugin_info')) {
  449. if ($active_plugin == $plugin->id) {
  450. $plugin_info['strings']['active_plugin_str'] = $plugin->string;
  451. }
  452. }
  453. }
  454. }
  455. //hide course settings if we're not in a course
  456. if ($courseid!=$SITE->id) {
  457. if ($setting = grade_helper::get_info_manage_settings($courseid)) {
  458. $plugin_info['settings'] = array('course'=>$setting);
  459. }
  460. }
  461. // Put preferences last
  462. if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
  463. $plugin_info['preferences'] = $preferences;
  464. }
  465. foreach ($plugin_info as $plugin_type => $plugins) {
  466. if (!empty($plugins->id) && $active_plugin == $plugins->id) {
  467. $plugin_info['strings']['active_plugin_str'] = $plugins->string;
  468. break;
  469. }
  470. foreach ($plugins as $plugin) {
  471. if (is_a($plugin, 'grade_plugin_info')) {
  472. if ($active_plugin == $plugin->id) {
  473. $plugin_info['strings']['active_plugin_str'] = $plugin->string;
  474. }
  475. }
  476. }
  477. }
  478. return $plugin_info;
  479. }
  480. /**
  481. * A simple class containing info about grade plugins.
  482. * Can be subclassed for special rules
  483. *
  484. * @package moodlecore
  485. * @copyright 2009 Nicolas Connault
  486. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  487. */
  488. class grade_plugin_info {
  489. /**
  490. * A unique id for this plugin
  491. *
  492. * @var mixed
  493. */
  494. public $id;
  495. /**
  496. * A URL to access this plugin
  497. *
  498. * @var mixed
  499. */
  500. public $link;
  501. /**
  502. * The name of this plugin
  503. *
  504. * @var mixed
  505. */
  506. public $string;
  507. /**
  508. * Another grade_plugin_info object, parent of the current one
  509. *
  510. * @var mixed
  511. */
  512. public $parent;
  513. /**
  514. * Constructor
  515. *
  516. * @param int $id A unique id for this plugin
  517. * @param string $link A URL to access this plugin
  518. * @param string $string The name of this plugin
  519. * @param object $parent Another grade_plugin_info object, parent of the current one
  520. *
  521. * @return void
  522. */
  523. public function __construct($id, $link, $string, $parent=null) {
  524. $this->id = $id;
  525. $this->link = $link;
  526. $this->string = $string;
  527. $this->parent = $parent;
  528. }
  529. }
  530. /**
  531. * Prints the page headers, breadcrumb trail, page heading, (optional) dropdown navigation menu and
  532. * (optional) navigation tabs for any gradebook page. All gradebook pages MUST use these functions
  533. * in favour of the usual print_header(), print_header_simple(), print_heading() etc.
  534. * !IMPORTANT! Use of tabs.php file in gradebook pages is forbidden unless tabs are switched off at
  535. * the site level for the gradebook ($CFG->grade_navmethod = GRADE_NAVMETHOD_DROPDOWN).
  536. *
  537. * @param int $courseid Course id
  538. * @param string $active_type The type of the current page (report, settings,
  539. * import, export, scales, outcomes, letters)
  540. * @param string $active_plugin The plugin of the current page (grader, fullview etc...)
  541. * @param string $heading The heading of the page. Tries to guess if none is given
  542. * @param boolean $return Whether to return (true) or echo (false) the HTML generated by this function
  543. * @param string $bodytags Additional attributes that will be added to the <body> tag
  544. * @param string $buttons Additional buttons to display on the page
  545. *
  546. * @return string HTML code or nothing if $return == false
  547. */
  548. function print_grade_page_head($courseid, $active_type, $active_plugin=null,
  549. $heading = false, $return=false,
  550. $buttons=false, $shownavigation=true) {
  551. global $CFG, $OUTPUT, $PAGE;
  552. $plugin_info = grade_get_plugin_info($courseid, $active_type, $active_plugin);
  553. // Determine the string of the active plugin
  554. $stractive_plugin = ($active_plugin) ? $plugin_info['strings']['active_plugin_str'] : $heading;
  555. $stractive_type = $plugin_info['strings'][$active_type];
  556. if (empty($plugin_info[$active_type]->id) || !empty($plugin_info[$active_type]->parent)) {
  557. $title = $PAGE->course->fullname.': ' . $stractive_type . ': ' . $stractive_plugin;
  558. } else {
  559. $title = $PAGE->course->fullname.': ' . $stractive_plugin;
  560. }
  561. if ($active_type == 'report') {
  562. $PAGE->set_pagelayout('report');
  563. } else {
  564. $PAGE->set_pagelayout('admin');
  565. }
  566. $PAGE->set_title(get_string('grades') . ': ' . $stractive_type);
  567. $PAGE->set_heading($title);
  568. if ($buttons instanceof single_button) {
  569. $buttons = $OUTPUT->render($buttons);
  570. }
  571. $PAGE->set_button($buttons);
  572. grade_extend_settings($plugin_info, $courseid);
  573. $returnval = $OUTPUT->header();
  574. if (!$return) {
  575. echo $returnval;
  576. }
  577. // Guess heading if not given explicitly
  578. if (!$heading) {
  579. $heading = $stractive_plugin;
  580. }
  581. if ($shownavigation) {
  582. if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_DROPDOWN) {
  583. $returnval .= print_grade_plugin_selector($plugin_info, $active_type, $active_plugin, $return);
  584. }
  585. $returnval .= $OUTPUT->heading($heading);
  586. if ($CFG->grade_navmethod == GRADE_NAVMETHOD_COMBO || $CFG->grade_navmethod == GRADE_NAVMETHOD_TABS) {
  587. $returnval .= grade_print_tabs($active_type, $active_plugin, $plugin_info, $return);
  588. }
  589. }
  590. if ($return) {
  591. return $returnval;
  592. }
  593. }
  594. /**
  595. * Utility class used for return tracking when using edit and other forms in grade plugins
  596. *
  597. * @package moodlecore
  598. * @copyright 2009 Nicolas Connault
  599. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  600. */
  601. class grade_plugin_return {
  602. public $type;
  603. public $plugin;
  604. public $courseid;
  605. public $userid;
  606. public $page;
  607. /**
  608. * Constructor
  609. *
  610. * @param array $params - associative array with return parameters, if null parameter are taken from _GET or _POST
  611. */
  612. public function grade_plugin_return($params = null) {
  613. if (empty($params)) {
  614. $this->type = optional_param('gpr_type', null, PARAM_SAFEDIR);
  615. $this->plugin = optional_param('gpr_plugin', null, PARAM_SAFEDIR);
  616. $this->courseid = optional_param('gpr_courseid', null, PARAM_INT);
  617. $this->userid = optional_param('gpr_userid', null, PARAM_INT);
  618. $this->page = optional_param('gpr_page', null, PARAM_INT);
  619. } else {
  620. foreach ($params as $key=>$value) {
  621. if (property_exists($this, $key)) {
  622. $this->$key = $value;
  623. }
  624. }
  625. }
  626. }
  627. /**
  628. * Returns return parameters as options array suitable for buttons.
  629. * @return array options
  630. */
  631. public function get_options() {
  632. if (empty($this->type)) {
  633. return array();
  634. }
  635. $params = array();
  636. if (!empty($this->plugin)) {
  637. $params['plugin'] = $this->plugin;
  638. }
  639. if (!empty($this->courseid)) {
  640. $params['id'] = $this->courseid;
  641. }
  642. if (!empty($this->userid)) {
  643. $params['userid'] = $this->userid;
  644. }
  645. if (!empty($this->page)) {
  646. $params['page'] = $this->page;
  647. }
  648. return $params;
  649. }
  650. /**
  651. * Returns return url
  652. *
  653. * @param string $default default url when params not set
  654. * @param array $extras Extra URL parameters
  655. *
  656. * @return string url
  657. */
  658. public function get_return_url($default, $extras=null) {
  659. global $CFG;
  660. if (empty($this->type) or empty($this->plugin)) {
  661. return $default;
  662. }
  663. $url = $CFG->wwwroot.'/grade/'.$this->type.'/'.$this->plugin.'/index.php';
  664. $glue = '?';
  665. if (!empty($this->courseid)) {
  666. $url .= $glue.'id='.$this->courseid;
  667. $glue = '&amp;';
  668. }
  669. if (!empty($this->userid)) {
  670. $url .= $glue.'userid='.$this->userid;
  671. $glue = '&amp;';
  672. }
  673. if (!empty($this->page)) {
  674. $url .= $glue.'page='.$this->page;
  675. $glue = '&amp;';
  676. }
  677. if (!empty($extras)) {
  678. foreach ($extras as $key=>$value) {
  679. $url .= $glue.$key.'='.$value;
  680. $glue = '&amp;';
  681. }
  682. }
  683. return $url;
  684. }
  685. /**
  686. * Returns string with hidden return tracking form elements.
  687. * @return string
  688. */
  689. public function get_form_fields() {
  690. if (empty($this->type)) {
  691. return '';
  692. }
  693. $result = '<input type="hidden" name="gpr_type" value="'.$this->type.'" />';
  694. if (!empty($this->plugin)) {
  695. $result .= '<input type="hidden" name="gpr_plugin" value="'.$this->plugin.'" />';
  696. }
  697. if (!empty($this->courseid)) {
  698. $result .= '<input type="hidden" name="gpr_courseid" value="'.$this->courseid.'" />';
  699. }
  700. if (!empty($this->userid)) {
  701. $result .= '<input type="hidden" name="gpr_userid" value="'.$this->userid.'" />';
  702. }
  703. if (!empty($this->page)) {
  704. $result .= '<input type="hidden" name="gpr_page" value="'.$this->page.'" />';
  705. }
  706. }
  707. /**
  708. * Add hidden elements into mform
  709. *
  710. * @param object &$mform moodle form object
  711. *
  712. * @return void
  713. */
  714. public function add_mform_elements(&$mform) {
  715. if (empty($this->type)) {
  716. return;
  717. }
  718. $mform->addElement('hidden', 'gpr_type', $this->type);
  719. $mform->setType('gpr_type', PARAM_SAFEDIR);
  720. if (!empty($this->plugin)) {
  721. $mform->addElement('hidden', 'gpr_plugin', $this->plugin);
  722. $mform->setType('gpr_plugin', PARAM_SAFEDIR);
  723. }
  724. if (!empty($this->courseid)) {
  725. $mform->addElement('hidden', 'gpr_courseid', $this->courseid);
  726. $mform->setType('gpr_courseid', PARAM_INT);
  727. }
  728. if (!empty($this->userid)) {
  729. $mform->addElement('hidden', 'gpr_userid', $this->userid);
  730. $mform->setType('gpr_userid', PARAM_INT);
  731. }
  732. if (!empty($this->page)) {
  733. $mform->addElement('hidden', 'gpr_page', $this->page);
  734. $mform->setType('gpr_page', PARAM_INT);
  735. }
  736. }
  737. /**
  738. * Add return tracking params into url
  739. *
  740. * @param moodle_url $url A URL
  741. *
  742. * @return string $url with return tracking params
  743. */
  744. public function add_url_params(moodle_url $url) {
  745. if (empty($this->type)) {
  746. return $url;
  747. }
  748. $url->param('gpr_type', $this->type);
  749. if (!empty($this->plugin)) {
  750. $url->param('gpr_plugin', $this->plugin);
  751. }
  752. if (!empty($this->courseid)) {
  753. $url->param('gpr_courseid' ,$this->courseid);
  754. }
  755. if (!empty($this->userid)) {
  756. $url->param('gpr_userid', $this->userid);
  757. }
  758. if (!empty($this->page)) {
  759. $url->param('gpr_page', $this->page);
  760. }
  761. return $url;
  762. }
  763. }
  764. /**
  765. * Function central to gradebook for building and printing the navigation (breadcrumb trail).
  766. *
  767. * @param string $path The path of the calling script (using __FILE__?)
  768. * @param string $pagename The language string to use as the last part of the navigation (non-link)
  769. * @param mixed $id Either a plain integer (assuming the key is 'id') or
  770. * an array of keys and values (e.g courseid => $courseid, itemid...)
  771. *
  772. * @return string
  773. */
  774. function grade_build_nav($path, $pagename=null, $id=null) {
  775. global $CFG, $COURSE, $PAGE;
  776. $strgrades = get_string('grades', 'grades');
  777. // Parse the path and build navlinks from its elements
  778. $dirroot_length = strlen($CFG->dirroot) + 1; // Add 1 for the first slash
  779. $path = substr($path, $dirroot_length);
  780. $path = str_replace('\\', '/', $path);
  781. $path_elements = explode('/', $path);
  782. $path_elements_count = count($path_elements);
  783. // First link is always 'grade'
  784. $PAGE->navbar->add($strgrades, new moodle_url('/grade/index.php', array('id'=>$COURSE->id)));
  785. $link = null;
  786. $numberofelements = 3;
  787. // Prepare URL params string
  788. $linkparams = array();
  789. if (!is_null($id)) {
  790. if (is_array($id)) {
  791. foreach ($id as $idkey => $idvalue) {
  792. $linkparams[$idkey] = $idvalue;
  793. }
  794. } else {
  795. $linkparams['id'] = $id;
  796. }
  797. }
  798. $navlink4 = null;
  799. // Remove file extensions from filenames
  800. foreach ($path_elements as $key => $filename) {
  801. $path_elements[$key] = str_replace('.php', '', $filename);
  802. }
  803. // Second level links
  804. switch ($path_elements[1]) {
  805. case 'edit': // No link
  806. if ($path_elements[3] != 'index.php') {
  807. $numberofelements = 4;
  808. }
  809. break;
  810. case 'import': // No link
  811. break;
  812. case 'export': // No link
  813. break;
  814. case 'report':
  815. // $id is required for this link. Do not print it if $id isn't given
  816. if (!is_null($id)) {
  817. $link = new moodle_url('/grade/report/index.php', $linkparams);
  818. }
  819. if ($path_elements[2] == 'grader') {
  820. $numberofelements = 4;
  821. }
  822. break;
  823. default:
  824. // If this element isn't among the ones already listed above, it isn't supported, throw an error.
  825. debugging("grade_build_nav() doesn't support ". $path_elements[1] .
  826. " as the second path element after 'grade'.");
  827. return false;
  828. }
  829. $PAGE->navbar->add(get_string($path_elements[1], 'grades'), $link);
  830. // Third level links
  831. if (empty($pagename)) {
  832. $pagename = get_string($path_elements[2], 'grades');
  833. }
  834. switch ($numberofelements) {
  835. case 3:
  836. $PAGE->navbar->add($pagename, $link);
  837. break;
  838. case 4:
  839. if ($path_elements[2] == 'grader' AND $path_elements[3] != 'index.php') {
  840. $PAGE->navbar->add(get_string('pluginname', 'gradereport_grader'), new moodle_url('/grade/report/grader/index.php', $linkparams));
  841. }
  842. $PAGE->navbar->add($pagename);
  843. break;
  844. }
  845. return '';
  846. }
  847. /**
  848. * General structure representing grade items in course
  849. *
  850. * @package moodlecore
  851. * @copyright 2009 Nicolas Connault
  852. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  853. */
  854. class grade_structure {
  855. public $context;
  856. public $courseid;
  857. /**
  858. * Reference to modinfo for current course (for performance, to save
  859. * retrieving it from courseid every time). Not actually set except for
  860. * the grade_tree type.
  861. * @var course_modinfo
  862. */
  863. public $modinfo;
  864. /**
  865. * 1D array of grade items only
  866. */
  867. public $items;
  868. /**
  869. * Returns icon of element
  870. *
  871. * @param array &$element An array representing an element in the grade_tree
  872. * @param bool $spacerifnone return spacer if no icon found
  873. *
  874. * @return string icon or spacer
  875. */
  876. public function get_element_icon(&$element, $spacerifnone=false) {
  877. global $CFG, $OUTPUT;
  878. switch ($element['type']) {
  879. case 'item':
  880. case 'courseitem':
  881. case 'categoryitem':
  882. $is_course = $element['object']->is_course_item();
  883. $is_category = $element['object']->is_category_item();
  884. $is_scale = $element['object']->gradetype == GRADE_TYPE_SCALE;
  885. $is_value = $element['object']->gradetype == GRADE_TYPE_VALUE;
  886. $is_outcome = !empty($element['object']->outcomeid);
  887. if ($element['object']->is_calculated()) {
  888. $strcalc = get_string('calculatedgrade', 'grades');
  889. return '<img src="'.$OUTPUT->pix_url('i/calc') . '" class="icon itemicon" title="'.
  890. s($strcalc).'" alt="'.s($strcalc).'"/>';
  891. } else if (($is_course or $is_category) and ($is_scale or $is_value)) {
  892. if ($category = $element['object']->get_item_category()) {
  893. switch ($category->aggregation) {
  894. case GRADE_AGGREGATE_MEAN:
  895. case GRADE_AGGREGATE_MEDIAN:
  896. case GRADE_AGGREGATE_WEIGHTED_MEAN:
  897. case GRADE_AGGREGATE_WEIGHTED_MEAN2:
  898. case GRADE_AGGREGATE_EXTRACREDIT_MEAN:
  899. $stragg = get_string('aggregation', 'grades');
  900. return '<img src="'.$OUTPUT->pix_url('i/agg_mean') . '" ' .
  901. 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
  902. case GRADE_AGGREGATE_SUM:
  903. $stragg = get_string('aggregation', 'grades');
  904. return '<img src="'.$OUTPUT->pix_url('i/agg_sum') . '" ' .
  905. 'class="icon itemicon" title="'.s($stragg).'" alt="'.s($stragg).'"/>';
  906. }
  907. }
  908. } else if ($element['object']->itemtype == 'mod') {
  909. //prevent outcomes being displaying the same icon as the activity they are attached to
  910. if ($is_outcome) {
  911. $stroutcome = s(get_string('outcome', 'grades'));
  912. return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
  913. 'class="icon itemicon" title="'.$stroutcome.
  914. '" alt="'.$stroutcome.'"/>';
  915. } else {
  916. $strmodname = get_string('modulename', $element['object']->itemmodule);
  917. return '<img src="'.$OUTPUT->pix_url('icon',
  918. $element['object']->itemmodule) . '" ' .
  919. 'class="icon itemicon" title="' .s($strmodname).
  920. '" alt="' .s($strmodname).'"/>';
  921. }
  922. } else if ($element['object']->itemtype == 'manual') {
  923. if ($element['object']->is_outcome_item()) {
  924. $stroutcome = get_string('outcome', 'grades');
  925. return '<img src="'.$OUTPUT->pix_url('i/outcomes') . '" ' .
  926. 'class="icon itemicon" title="'.s($stroutcome).
  927. '" alt="'.s($stroutcome).'"/>';
  928. } else {
  929. $strmanual = get_string('manualitem', 'grades');
  930. return '<img src="'.$OUTPUT->pix_url('t/manual_item') . '" '.
  931. 'class="icon itemicon" title="'.s($strmanual).
  932. '" alt="'.s($strmanual).'"/>';
  933. }
  934. }
  935. break;
  936. case 'category':
  937. $strcat = get_string('category', 'grades');
  938. return '<img src="'.$OUTPUT->pix_url('f/folder') . '" class="icon itemicon" ' .
  939. 'title="'.s($strcat).'" alt="'.s($strcat).'" />';
  940. }
  941. if ($spacerifnone) {
  942. return $OUTPUT->spacer().' ';
  943. } else {
  944. return '';
  945. }
  946. }
  947. /**
  948. * Returns name of element optionally with icon and link
  949. *
  950. * @param array &$element An array representing an element in the grade_tree
  951. * @param bool $withlink Whether or not this header has a link
  952. * @param bool $icon Whether or not to display an icon with this header
  953. * @param bool $spacerifnone return spacer if no icon found
  954. *
  955. * @return string header
  956. */
  957. public function get_element_header(&$element, $withlink=false, $icon=true, $spacerifnone=false) {
  958. $header = '';
  959. if ($icon) {
  960. $header .= $this->get_element_icon($element, $spacerifnone);
  961. }
  962. $header .= $element['object']->get_name();
  963. if ($element['type'] != 'item' and $element['type'] != 'categoryitem' and
  964. $element['type'] != 'courseitem') {
  965. return $header;
  966. }
  967. if ($withlink) {
  968. $url = $this->get_activity_link($element);
  969. if ($url) {
  970. $a = new stdClass();
  971. $a->name = get_string('modulename', $element['object']->itemmodule);
  972. $title = get_string('linktoactivity', 'grades', $a);
  973. $header = html_writer::link($url, $header, array('title' => $title));
  974. }
  975. }
  976. return $header;
  977. }
  978. private function get_activity_link($element) {
  979. global $CFG;
  980. $itemtype = $element['object']->itemtype;
  981. $itemmodule = $element['object']->itemmodule;
  982. $iteminstance = $element['object']->iteminstance;
  983. // Links only for module items that have valid instance, module and are
  984. // called from grade_tree with valid modinfo
  985. if ($itemtype != 'mod' || !$iteminstance || !$itemmodule || !$this->modinfo) {
  986. return null;
  987. }
  988. // Get $cm efficiently and with visibility information using modinfo
  989. $instances = $this->modinfo->get_instances();
  990. if (empty($instances[$itemmodule][$iteminstance])) {
  991. return null;
  992. }
  993. $cm = $instances[$itemmodule][$iteminstance];
  994. // Do not add link if activity is not visible to the current user
  995. if (!$cm->uservisible) {
  996. return null;
  997. }
  998. // If module has grade.php, link to that, otherwise view.php
  999. $dir = $CFG->dirroot . '/mod/' . $itemmodule;
  1000. if (file_exists($dir.'/grade.php')) {
  1001. return new moodle_url('/mod/' . $itemmodule . '/grade.php', array('id' => $cm->id));
  1002. } else {
  1003. return new moodle_url('/mod/' . $itemmodule . '/view.php', array('id' => $cm->id));
  1004. }
  1005. }
  1006. /**
  1007. * Returns the grade eid - the grade may not exist yet.
  1008. *
  1009. * @param grade_grade $grade_grade A grade_grade object
  1010. *
  1011. * @return string eid
  1012. */
  1013. public function get_grade_eid($grade_grade) {
  1014. if (empty($grade_grade->id)) {
  1015. return 'n'.$grade_grade->itemid.'u'.$grade_grade->userid;
  1016. } else {
  1017. return 'g'.$grade_grade->id;
  1018. }
  1019. }
  1020. /**
  1021. * Returns the grade_item eid
  1022. * @param grade_item $grade_item A grade_item object
  1023. * @return string eid
  1024. */
  1025. public function get_item_eid($grade_item) {
  1026. return 'i'.$grade_item->id;
  1027. }
  1028. /**
  1029. * Given a grade_tree element, returns an array of parameters
  1030. * used to build an icon for that element.
  1031. *
  1032. * @param array $element An array representing an element in the grade_tree
  1033. *
  1034. * @return array
  1035. */
  1036. public function get_params_for_iconstr($element) {
  1037. $strparams = new stdClass();
  1038. $strparams->category = '';
  1039. $strparams->itemname = '';
  1040. $strparams->itemmodule = '';
  1041. if (!method_exists($element['object'], 'get_name')) {
  1042. return $strparams;
  1043. }
  1044. $strparams->itemname = html_to_text($element['object']->get_name());
  1045. // If element name is categorytotal, get the name of the parent category
  1046. if ($strparams->itemname == get_string('categorytotal', 'grades')) {
  1047. $parent = $element['object']->get_parent_category();
  1048. $strparams->category = $parent->get_name() . ' ';
  1049. } else {
  1050. $strparams->category = '';
  1051. }
  1052. $strparams->itemmodule = null;
  1053. if (isset($element['object']->itemmodule)) {
  1054. $strparams->itemmodule = $element['object']->itemmodule;
  1055. }
  1056. return $strparams;
  1057. }
  1058. /**
  1059. * Return edit icon for give element
  1060. *
  1061. * @param array $element An array representing an element in the grade_tree
  1062. * @param object $gpr A grade_plugin_return object
  1063. *
  1064. * @return string
  1065. */
  1066. public function get_edit_icon($element, $gpr) {
  1067. global $CFG, $OUTPUT;
  1068. if (!has_capability('moodle/grade:manage', $this->context)) {
  1069. if ($element['type'] == 'grade' and has_capability('moodle/grade:edit', $this->context)) {
  1070. // oki - let them override grade
  1071. } else {
  1072. return '';
  1073. }
  1074. }
  1075. static $strfeedback = null;
  1076. static $streditgrade = null;
  1077. if (is_null($streditgrade)) {
  1078. $streditgrade = get_string('editgrade', 'grades');
  1079. $strfeedback = get_string('feedback');
  1080. }
  1081. $strparams = $this->get_params_for_iconstr($element);
  1082. $object = $element['object'];
  1083. switch ($element['type']) {
  1084. case 'item':
  1085. case 'categoryitem':
  1086. case 'courseitem':
  1087. $stredit = get_string('editverbose', 'grades', $strparams);
  1088. if (empty($object->outcomeid) || empty($CFG->enableoutcomes)) {
  1089. $url = new moodle_url('/grade/edit/tree/item.php',
  1090. array('courseid' => $this->courseid, 'id' => $object->id));
  1091. } else {
  1092. $url = new moodle_url('/grade/edit/tree/outcomeitem.php',
  1093. array('courseid' => $this->courseid, 'id' => $object->id));
  1094. }
  1095. break;
  1096. case 'category':
  1097. $stredit = get_string('editverbose', 'grades', $strparams);
  1098. $url = new moodle_url('/grade/edit/tree/category.php',
  1099. array('courseid' => $this->courseid, 'id' => $object->id));
  1100. break;
  1101. case 'grade':
  1102. $stredit = $streditgrade;
  1103. if (empty($object->id)) {
  1104. $url = new moodle_url('/grade/edit/tree/grade.php',
  1105. array('courseid' => $this->courseid, 'itemid' => $object->itemid, 'userid' => $object->userid));
  1106. } else {
  1107. $url = new moodle_url('/grade/edit/tree/grade.php',
  1108. array('courseid' => $this->courseid, 'id' => $object->id));
  1109. }
  1110. if (!empty($object->feedback)) {
  1111. $feedback = addslashes_js(trim(format_string($object->feedback, $object->feedbackformat)));
  1112. }
  1113. break;
  1114. default:
  1115. $url = null;
  1116. }
  1117. if ($url) {
  1118. return $OUTPUT->action_icon($gpr->add_url_params($url), new pix_icon('t/edit', $stredit));
  1119. } else {
  1120. return '';
  1121. }
  1122. }
  1123. /**
  1124. * Return hiding icon for give element
  1125. *
  1126. * @param array $element An array representing an element in the grade_tree
  1127. * @param object $gpr A grade_plugin_return object
  1128. *
  1129. * @return string
  1130. */
  1131. public function get_hiding_icon($element, $gpr) {
  1132. global $CFG, $OUTPUT;
  1133. if (!has_capability('moodle/grade:manage', $this->context) and
  1134. !has_capability('moodle/grade:hide', $this->context)) {
  1135. return '';
  1136. }
  1137. $strparams = $this->get_params_for_iconstr($element);
  1138. $strshow = get_string('showverbose', 'grades', $strparams);
  1139. $strhide = get_string('hideverbose', 'grades', $strparams);
  1140. $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
  1141. $url = $gpr->add_url_params($url);
  1142. if ($element['object']->is_hidden()) {
  1143. $type = 'show';
  1144. $tooltip = $strshow;
  1145. // Change the icon and add a tooltip showing the date
  1146. if ($element['type'] != 'category' and $element['object']->get_hidden() > 1) {
  1147. $type = 'hiddenuntil';
  1148. $tooltip = get_string('hiddenuntildate', 'grades',
  1149. userdate($element['object']->get_hidden()));
  1150. }
  1151. $url->param('action', 'show');
  1152. $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strshow, 'class'=>'iconsmall')));
  1153. } else {
  1154. $url->param('action', 'hide');
  1155. $hideicon = $OUTPUT->action_icon($url, new pix_icon('t/hide', $strhide));
  1156. }
  1157. return $hideicon;
  1158. }
  1159. /**
  1160. * Return locking icon for given element
  1161. *
  1162. * @param array $element An array representing an element in the grade_tree
  1163. * @param object $gpr A grade_plugin_return object
  1164. *
  1165. * @return string
  1166. */
  1167. public function get_locking_icon($element, $gpr) {
  1168. global $CFG, $OUTPUT;
  1169. $strparams = $this->get_params_for_iconstr($element);
  1170. $strunlock = get_string('unlockverbose', 'grades', $strparams);
  1171. $strlock = get_string('lockverbose', 'grades', $strparams);
  1172. $url = new moodle_url('/grade/edit/tree/action.php', array('id' => $this->courseid, 'sesskey' => sesskey(), 'eid' => $element['eid']));
  1173. $url = $gpr->add_url_params($url);
  1174. // Don't allow an unlocking action for a grade whose grade item is locked: just print a state icon
  1175. if ($element['type'] == 'grade' && $element['object']->grade_item->is_locked()) {
  1176. $strparamobj = new stdClass();
  1177. $strparamobj->itemname = $element['object']->grade_item->itemname;
  1178. $strnonunlockable = get_string('nonunlockableverbose', 'grades', $strparamobj);
  1179. $action = $OUTPUT->pix_icon('t/unlock_gray', $strnonunlockable);
  1180. } else if ($element['object']->is_locked()) {
  1181. $type = 'unlock';
  1182. $tooltip = $strunlock;
  1183. // Change the icon and add a tooltip showing the date
  1184. if ($element['type'] != 'category' and $element['object']->get_locktime() > 1) {
  1185. $type = 'locktime';
  1186. $tooltip = get_string('locktimedate', 'grades',
  1187. userdate($element['object']->get_locktime()));
  1188. }
  1189. if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:unlock', $this->context)) {
  1190. $action = '';
  1191. } else {
  1192. $url->param('action', 'unlock');
  1193. $action = $OUTPUT->action_icon($url, new pix_icon('t/'.$type, $tooltip, 'moodle', array('alt'=>$strunlock, 'class'=>'smallicon')));
  1194. }
  1195. } else {
  1196. if (!has_capability('moodle/grade:manage', $this->context) and !has_capability('moodle/grade:lock', $this->context)) {
  1197. $action = '';
  1198. } else {
  1199. $url->param('action', 'lock');
  1200. $action = $OUTPUT->action_icon($url, new pix_icon('t/lock', $strlock));
  1201. }
  1202. }
  1203. return $action;
  1204. }
  1205. /**
  1206. * Return calculation icon for given element
  1207. *
  1208. * @param array $element An array representing an element in the grade_tree
  1209. * @param object $gpr A grade_plugin_return object
  1210. *
  1211. * @return string
  1212. */
  1213. public function get_calculation_icon($element, $gpr) {
  1214. global $CFG, $OUTPUT;
  1215. if (!has_capability('moodle/grade:manage', $this->context)) {
  1216. return '';
  1217. }
  1218. $type = $element['type'];
  1219. $object = $element['object'];
  1220. if ($type == 'item' or $type == 'courseitem' or $type == 'categoryitem') {
  1221. $strparams = $this->get_params_for_iconstr($element);
  1222. $streditcalculation = get_string('editcalculationverbose', 'grades', $strparams);
  1223. $is_scale = $object->gradetype == GRADE_TYPE_SCALE;
  1224. $is_value = $object->gradetype == GRADE_TYPE_VALUE;
  1225. // show calculation icon only when calculation possible
  1226. if (!$object->is_external_item() and ($is_scale or $is_value)) {
  1227. if ($object->is_calculated()) {
  1228. $icon = 't/calc';
  1229. } else {
  1230. $icon = 't/calc_off';
  1231. }
  1232. $url = new moodle_url('/grade/edit/tree/calculation.php', array('courseid' => $this->courseid, 'id' => $object->id));
  1233. $url = $gpr->add_url_params($url);
  1234. return $OUTPUT->action_icon($url, new pix_icon($icon, $streditcalculation)) . "\n";
  1235. }
  1236. }
  1237. return '';
  1238. }
  1239. }
  1240. /**
  1241. * Flat structure similar to grade tree.
  1242. *
  1243. * @uses grade_structure
  1244. * @package moodlecore
  1245. * @copyright 2009 Nicolas Connault
  1246. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1247. */
  1248. class grade_seq extends grade_structure {
  1249. /**
  1250. * 1D array of elements
  1251. */
  1252. public $elements;
  1253. /**
  1254. * Constructor, retrieves and stores array of all grade_category and grade_item
  1255. * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
  1256. *
  1257. * @param int $courseid The course id
  1258. * @param bool $category_grade_last category grade item is the last child
  1259. * @param bool $nooutcomes Whether or not outcomes should be included
  1260. */
  1261. public function grade_seq($courseid, $category_grade_last=false, $nooutcomes=false) {
  1262. global $USER, $CFG;
  1263. $this->courseid = $courseid;
  1264. $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
  1265. // get course grade tree
  1266. $top_element = grade_category::fetch_course_tree($courseid, true);
  1267. $this->elements = grade_seq::flatten($top_element, $category_grade_last, $nooutcomes);
  1268. foreach ($this->elements as $key=>$unused) {
  1269. $this->items[$this->elements[$key]['object']->id] =& $this->elements[$key]['object'];
  1270. }
  1271. }
  1272. /**
  1273. * Static recursive helper - makes the grade_item for category the last children
  1274. *
  1275. * @param array &$element The seed of the recursion
  1276. * @param bool $category_grade_last category grade item is the last child
  1277. * @param bool $nooutcomes Whether or not outcomes should be included
  1278. *
  1279. * @return array
  1280. */
  1281. public function flatten(&$element, $category_grade_last, $nooutcomes) {
  1282. if (empty($element['children'])) {
  1283. return array();
  1284. }
  1285. $children = array();
  1286. foreach ($element['children'] as $sortorder=>$unused) {
  1287. if ($nooutcomes and $element['type'] != 'category' and
  1288. $element['children'][$sortorder]['object']->is_outcome_item()) {
  1289. continue;
  1290. }
  1291. $children[] = $element['children'][$sortorder];
  1292. }
  1293. unset($element['children']);
  1294. if ($category_grade_last and count($children) > 1) {
  1295. $cat_item = array_shift($children);
  1296. array_push($children, $cat_item);
  1297. }
  1298. $result = array();
  1299. foreach ($children as $child) {
  1300. if ($child['type'] == 'category') {
  1301. $result = $result + grade_seq::flatten($child, $category_grade_last, $nooutcomes);
  1302. } else {
  1303. $child['eid'] = 'i'.$child['object']->id;
  1304. $result[$child['object']->id] = $child;
  1305. }
  1306. }
  1307. return $result;
  1308. }
  1309. /**
  1310. * Parses the array in search of a given eid and returns a element object with
  1311. * information about the element it has found.
  1312. *
  1313. * @param int $eid Gradetree Element ID
  1314. *
  1315. * @return object element
  1316. */
  1317. public function locate_element($eid) {
  1318. // it is a grade - construct a new object
  1319. if (strpos($eid, 'n') === 0) {
  1320. if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
  1321. return null;
  1322. }
  1323. $itemid = $matches[1];
  1324. $userid = $matches[2];
  1325. //extra security check - the grade item must be in this tree
  1326. if (!$item_el = $this->locate_element('i'.$itemid)) {
  1327. return null;
  1328. }
  1329. // $gradea->id may be null - means does not exist yet
  1330. $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
  1331. $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
  1332. return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
  1333. } else if (strpos($eid, 'g') === 0) {
  1334. $id = (int) substr($eid, 1);
  1335. if (!$grade = grade_grade::fetch(array('id'=>$id))) {
  1336. return null;
  1337. }
  1338. //extra security check - the grade item must be in this tree
  1339. if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
  1340. return null;
  1341. }
  1342. $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
  1343. return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
  1344. }
  1345. // it is a category or item
  1346. foreach ($this->elements as $element) {
  1347. if ($element['eid'] == $eid) {
  1348. return $element;
  1349. }
  1350. }
  1351. return null;
  1352. }
  1353. }
  1354. /**
  1355. * This class represents a complete tree of categories, grade_items and final grades,
  1356. * organises as an array primarily, but which can also be converted to other formats.
  1357. * It has simple method calls with complex implementations, allowing for easy insertion,
  1358. * deletion and moving of items and categories within the tree.
  1359. *
  1360. * @uses grade_structure
  1361. * @package moodlecore
  1362. * @copyright 2009 Nicolas Connault
  1363. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1364. */
  1365. class grade_tree extends grade_structure {
  1366. /**
  1367. * The basic representation of the tree as a hierarchical, 3-tiered array.
  1368. * @var object $top_element
  1369. */
  1370. public $top_element;
  1371. /**
  1372. * 2D array of grade items and categories
  1373. * @var array $levels
  1374. */
  1375. public $levels;
  1376. /**
  1377. * Grade items
  1378. * @var array $items
  1379. */
  1380. public $items;
  1381. /**
  1382. * Constructor, retrieves and stores a hierarchical array of all grade_category and grade_item
  1383. * objects for the given courseid. Full objects are instantiated. Ordering sequence is fixed if needed.
  1384. *
  1385. * @param int $courseid The Course ID
  1386. * @param bool $fillers include fillers and colspans, make the levels var "rectangular"
  1387. * @param bool $category_grade_last category grade item is the last child
  1388. * @param array $collapsed array of collapsed categories
  1389. * @param bool $nooutcomes Whether or not outcomes should be included
  1390. */
  1391. public function grade_tree($courseid, $fillers=true, $category_grade_last=false,
  1392. $collapsed=null, $nooutcomes=false) {
  1393. global $USER, $CFG, $COURSE, $DB;
  1394. $this->courseid = $courseid;
  1395. $this->levels = array();
  1396. $this->context = get_context_instance(CONTEXT_COURSE, $courseid);
  1397. if (!empty($COURSE->id) && $COURSE->id == $this->courseid) {
  1398. $course = $COURSE;
  1399. } else {
  1400. $course = $DB->get_record('course', array('id' => $this->courseid));
  1401. }
  1402. $this->modinfo = get_fast_modinfo($course);
  1403. // get course grade tree
  1404. $this->top_element = grade_category::fetch_course_tree($courseid, true);
  1405. // collapse the categories if requested
  1406. if (!empty($collapsed)) {
  1407. grade_tree::category_collapse($this->top_element, $collapsed);
  1408. }
  1409. // no otucomes if requested
  1410. if (!empty($nooutcomes)) {
  1411. grade_tree::no_outcomes($this->top_element);
  1412. }
  1413. // move category item to last position in category
  1414. if ($category_grade_last) {
  1415. grade_tree::category_grade_last($this->top_element);
  1416. }
  1417. if ($fillers) {
  1418. // inject fake categories == fillers
  1419. grade_tree::inject_fillers($this->top_element, 0);
  1420. // add colspans to categories and fillers
  1421. grade_tree::inject_colspans($this->top_element);
  1422. }
  1423. grade_tree::fill_levels($this->levels, $this->top_element, 0);
  1424. }
  1425. /**
  1426. * Static recursive helper - removes items from collapsed categories
  1427. *
  1428. * @param array &$element The seed of the recursion
  1429. * @param array $collapsed array of collapsed categories
  1430. *
  1431. * @return void
  1432. */
  1433. public function category_collapse(&$element, $collapsed) {
  1434. if ($element['type'] != 'category') {
  1435. return;
  1436. }
  1437. if (empty($element['children']) or count($element['children']) < 2) {
  1438. return;
  1439. }
  1440. if (in_array($element['object']->id, $collapsed['aggregatesonly'])) {
  1441. $category_item = reset($element['children']); //keep only category item
  1442. $element['children'] = array(key($element['children'])=>$category_item);
  1443. } else {
  1444. if (in_array($element['object']->id, $collapsed['gradesonly'])) { // Remove category item
  1445. reset($element['children']);
  1446. $first_key = key($element['children']);
  1447. unset($element['children'][$first_key]);
  1448. }
  1449. foreach ($element['children'] as $sortorder=>$child) { // Recurse through the element's children
  1450. grade_tree::category_collapse($element['children'][$sortorder], $collapsed);
  1451. }
  1452. }
  1453. }
  1454. /**
  1455. * Static recursive helper - removes all outcomes
  1456. *
  1457. * @param array &$element The seed of the recursion
  1458. *
  1459. * @return void
  1460. */
  1461. public function no_outcomes(&$element) {
  1462. if ($element['type'] != 'category') {
  1463. return;
  1464. }
  1465. foreach ($element['children'] as $sortorder=>$child) {
  1466. if ($element['children'][$sortorder]['type'] == 'item'
  1467. and $element['children'][$sortorder]['object']->is_outcome_item()) {
  1468. unset($element['children'][$sortorder]);
  1469. } else if ($element['children'][$sortorder]['type'] == 'category') {
  1470. grade_tree::no_outcomes($element['children'][$sortorder]);
  1471. }
  1472. }
  1473. }
  1474. /**
  1475. * Static recursive helper - makes the grade_item for category the last children
  1476. *
  1477. * @param array &$element The seed of the recursion
  1478. *
  1479. * @return void
  1480. */
  1481. public function category_grade_last(&$element) {
  1482. if (empty($element['children'])) {
  1483. return;
  1484. }
  1485. if (count($element['children']) < 2) {
  1486. return;
  1487. }
  1488. $first_item = reset($element['children']);
  1489. if ($first_item['type'] == 'categoryitem' or $first_item['type'] == 'courseitem') {
  1490. // the category item might have been already removed
  1491. $order = key($element['children']);
  1492. unset($element['children'][$order]);
  1493. $element['children'][$order] =& $first_item;
  1494. }
  1495. foreach ($element['children'] as $sortorder => $child) {
  1496. grade_tree::category_grade_last($element['children'][$sortorder]);
  1497. }
  1498. }
  1499. /**
  1500. * Static recursive helper - fills the levels array, useful when accessing tree elements of one level
  1501. *
  1502. * @param array &$levels The levels of the grade tree through which to recurse
  1503. * @param array &$element The seed of the recursion
  1504. * @param int $depth How deep are we?
  1505. * @return void
  1506. */
  1507. public function fill_levels(&$levels, &$element, $depth) {
  1508. if (!array_key_exists($depth, $levels)) {
  1509. $levels[$depth] = array();
  1510. }
  1511. // prepare unique identifier
  1512. if ($element['type'] == 'category') {
  1513. $element['eid'] = 'c'.$element['object']->id;
  1514. } else if (in_array($element['type'], array('item', 'courseitem', 'categoryitem'))) {
  1515. $element['eid'] = 'i'.$element['object']->id;
  1516. $this->items[$element['object']->id] =& $element['object'];
  1517. }
  1518. $levels[$depth][] =& $element;
  1519. $depth++;
  1520. if (empty($element['children'])) {
  1521. return;
  1522. }
  1523. $prev = 0;
  1524. foreach ($element['children'] as $sortorder=>$child) {
  1525. grade_tree::fill_levels($levels, $element['children'][$sortorder], $depth);
  1526. $element['children'][$sortorder]['prev'] = $prev;
  1527. $element['children'][$sortorder]['next'] = 0;
  1528. if ($prev) {
  1529. $element['children'][$prev]['next'] = $sortorder;
  1530. }
  1531. $prev = $sortorder;
  1532. }
  1533. }
  1534. /**
  1535. * Static recursive helper - makes full tree (all leafes are at the same level)
  1536. *
  1537. * @param array &$element The seed of the recursion
  1538. * @param int $depth How deep are we?
  1539. *
  1540. * @return int
  1541. */
  1542. public function inject_fillers(&$element, $depth) {
  1543. $depth++;
  1544. if (empty($element['children'])) {
  1545. return $depth;
  1546. }
  1547. $chdepths = array();
  1548. $chids = array_keys($element['children']);
  1549. $last_child = end($chids);
  1550. $first_child = reset($chids);
  1551. foreach ($chids as $chid) {
  1552. $chdepths[$chid] = grade_tree::inject_fillers($element['children'][$chid], $depth);
  1553. }
  1554. arsort($chdepths);
  1555. $maxdepth = reset($chdepths);
  1556. foreach ($chdepths as $chid=>$chd) {
  1557. if ($chd == $maxdepth) {
  1558. continue;
  1559. }
  1560. for ($i=0; $i < $maxdepth-$chd; $i++) {
  1561. if ($chid == $first_child) {
  1562. $type = 'fillerfirst';
  1563. } else if ($chid == $last_child) {
  1564. $type = 'fillerlast';
  1565. } else {
  1566. $type = 'filler';
  1567. }
  1568. $oldchild =& $element['children'][$chid];
  1569. $element['children'][$chid] = array('object'=>'filler', 'type'=>$type,
  1570. 'eid'=>'', 'depth'=>$element['object']->depth,
  1571. 'children'=>array($oldchild));
  1572. }
  1573. }
  1574. return $maxdepth;
  1575. }
  1576. /**
  1577. * Static recursive helper - add colspan information into categories
  1578. *
  1579. * @param array &$element The seed of the recursion
  1580. *
  1581. * @return int
  1582. */
  1583. public function inject_colspans(&$element) {
  1584. if (empty($element['children'])) {
  1585. return 1;
  1586. }
  1587. $count = 0;
  1588. foreach ($element['children'] as $key=>$child) {
  1589. $count += grade_tree::inject_colspans($element['children'][$key]);
  1590. }
  1591. $element['colspan'] = $count;
  1592. return $count;
  1593. }
  1594. /**
  1595. * Parses the array in search of a given eid and returns a element object with
  1596. * information about the element it has found.
  1597. * @param int $eid Gradetree Element ID
  1598. * @return object element
  1599. */
  1600. public function locate_element($eid) {
  1601. // it is a grade - construct a new object
  1602. if (strpos($eid, 'n') === 0) {
  1603. if (!preg_match('/n(\d+)u(\d+)/', $eid, $matches)) {
  1604. return null;
  1605. }
  1606. $itemid = $matches[1];
  1607. $userid = $matches[2];
  1608. //extra security check - the grade item must be in this tree
  1609. if (!$item_el = $this->locate_element('i'.$itemid)) {
  1610. return null;
  1611. }
  1612. // $gradea->id may be null - means does not exist yet
  1613. $grade = new grade_grade(array('itemid'=>$itemid, 'userid'=>$userid));
  1614. $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
  1615. return array('eid'=>'n'.$itemid.'u'.$userid,'object'=>$grade, 'type'=>'grade');
  1616. } else if (strpos($eid, 'g') === 0) {
  1617. $id = (int) substr($eid, 1);
  1618. if (!$grade = grade_grade::fetch(array('id'=>$id))) {
  1619. return null;
  1620. }
  1621. //extra security check - the grade item must be in this tree
  1622. if (!$item_el = $this->locate_element('i'.$grade->itemid)) {
  1623. return null;
  1624. }
  1625. $grade->grade_item =& $item_el['object']; // this may speedup grade_grade methods!
  1626. return array('eid'=>'g'.$id,'object'=>$grade, 'type'=>'grade');
  1627. }
  1628. // it is a category or item
  1629. foreach ($this->levels as $row) {
  1630. foreach ($row as $element) {
  1631. if ($element['type'] == 'filler') {
  1632. continue;
  1633. }
  1634. if ($element['eid'] == $eid) {
  1635. return $element;
  1636. }
  1637. }
  1638. }
  1639. return null;
  1640. }
  1641. /**
  1642. * Returns a well-formed XML representation of the grade-tree using recursion.
  1643. *
  1644. * @param array $root The current element in the recursion. If null, starts at the top of the tree.
  1645. * @param string $tabs The control character to use for tabs
  1646. *
  1647. * @return string $xml
  1648. */
  1649. public function exporttoxml($root=null, $tabs="\t") {
  1650. $xml = null;
  1651. $first = false;
  1652. if (is_null($root)) {
  1653. $root = $this->top_element;
  1654. $xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
  1655. $xml .= "<gradetree>\n";
  1656. $first = true;
  1657. }
  1658. $type = 'undefined';
  1659. if (strpos($root['object']->table, 'grade_categories') !== false) {
  1660. $type = 'category';
  1661. } else if (strpos($root['object']->table, 'grade_items') !== false) {
  1662. $type = 'item';
  1663. } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
  1664. $type = 'outcome';
  1665. }
  1666. $xml .= "$tabs<element type=\"$type\">\n";
  1667. foreach ($root['object'] as $var => $value) {
  1668. if (!is_object($value) && !is_array($value) && !empty($value)) {
  1669. $xml .= "$tabs\t<$var>$value</$var>\n";
  1670. }
  1671. }
  1672. if (!empty($root['children'])) {
  1673. $xml .= "$tabs\t<children>\n";
  1674. foreach ($root['children'] as $sortorder => $child) {
  1675. $xml .= $this->exportToXML($child, $tabs."\t\t");
  1676. }
  1677. $xml .= "$tabs\t</children>\n";
  1678. }
  1679. $xml .= "$tabs</element>\n";
  1680. if ($first) {
  1681. $xml .= "</gradetree>";
  1682. }
  1683. return $xml;
  1684. }
  1685. /**
  1686. * Returns a JSON representation of the grade-tree using recursion.
  1687. *
  1688. * @param array $root The current element in the recursion. If null, starts at the top of the tree.
  1689. * @param string $tabs Tab characters used to indent the string nicely for humans to enjoy
  1690. *
  1691. * @return string
  1692. */
  1693. public function exporttojson($root=null, $tabs="\t") {
  1694. $json = null;
  1695. $first = false;
  1696. if (is_null($root)) {
  1697. $root = $this->top_element;
  1698. $first = true;
  1699. }
  1700. $name = '';
  1701. if (strpos($root['object']->table, 'grade_categories') !== false) {
  1702. $name = $root['object']->fullname;
  1703. if ($name == '?') {
  1704. $name = $root['object']->get_name();
  1705. }
  1706. } else if (strpos($root['object']->table, 'grade_items') !== false) {
  1707. $name = $root['object']->itemname;
  1708. } else if (strpos($root['object']->table, 'grade_outcomes') !== false) {
  1709. $name = $root['object']->itemname;
  1710. }
  1711. $json .= "$tabs {\n";
  1712. $json .= "$tabs\t \"type\": \"{$root['type']}\",\n";
  1713. $json .= "$tabs\t \"name\": \"$name\",\n";
  1714. foreach ($root['object'] as $var => $value) {
  1715. if (!is_object($value) && !is_array($value) && !empty($value)) {
  1716. $json .= "$tabs\t \"$var\": \"$value\",\n";
  1717. }
  1718. }
  1719. $json = substr($json, 0, strrpos($json, ','));
  1720. if (!empty($root['children'])) {
  1721. $json .= ",\n$tabs\t\"children\": [\n";
  1722. foreach ($root['children'] as $sortorder => $child) {
  1723. $json .= $this->exportToJSON($child, $tabs."\t\t");
  1724. }
  1725. $json = substr($json, 0, strrpos($json, ','));
  1726. $json .= "\n$tabs\t]\n";
  1727. }
  1728. if ($first) {
  1729. $json .= "\n}";
  1730. } else {
  1731. $json .= "\n$tabs},\n";
  1732. }
  1733. return $json;
  1734. }
  1735. /**
  1736. * Returns the array of levels
  1737. *
  1738. * @return array
  1739. */
  1740. public function get_levels() {
  1741. return $this->levels;
  1742. }
  1743. /**
  1744. * Returns the array of grade items
  1745. *
  1746. * @return array
  1747. */
  1748. public function get_items() {
  1749. return $this->items;
  1750. }
  1751. /**
  1752. * Returns a specific Grade Item
  1753. *
  1754. * @param int $itemid The ID of the grade_item object
  1755. *
  1756. * @return grade_item
  1757. */
  1758. public function get_item($itemid) {
  1759. if (array_key_exists($itemid, $this->items)) {
  1760. return $this->items[$itemid];
  1761. } else {
  1762. return false;
  1763. }
  1764. }
  1765. }
  1766. /**
  1767. * Local shortcut function for creating an edit/delete button for a grade_* object.
  1768. * @param string $type 'edit' or 'delete'
  1769. * @param int $courseid The Course ID
  1770. * @param grade_* $object The grade_* object
  1771. * @return string html
  1772. */
  1773. function grade_button($type, $courseid, $object) {
  1774. global $CFG, $OUTPUT;
  1775. if (preg_match('/grade_(.*)/', get_class($object), $matches)) {
  1776. $objectidstring = $matches[1] . 'id';
  1777. } else {
  1778. throw new coding_exception('grade_button() only accepts grade_* objects as third parameter!');
  1779. }
  1780. $strdelete = get_string('delete');
  1781. $stredit = get_string('edit');
  1782. if ($type == 'delete') {
  1783. $url = new moodle_url('index.php', array('id' => $courseid, $objectidstring => $object->id, 'action' => 'delete', 'sesskey' => sesskey()));
  1784. } else if ($type == 'edit') {
  1785. $url = new moodle_url('edit.php', array('courseid' => $courseid, 'id' => $object->id));
  1786. }
  1787. return $OUTPUT->action_icon($url, new pix_icon('t/'.$type, ${'str'.$type}));
  1788. }
  1789. /**
  1790. * This method adds settings to the settings block for the grade system and its
  1791. * plugins
  1792. *
  1793. * @global moodle_page $PAGE
  1794. */
  1795. function grade_extend_settings($plugininfo, $courseid) {
  1796. global $PAGE;
  1797. $gradenode = $PAGE->settingsnav->prepend(get_string('gradeadministration', 'grades'), null, navigation_node::TYPE_CONTAINER);
  1798. $strings = array_shift($plugininfo);
  1799. if ($reports = grade_helper::get_plugins_reports($courseid)) {
  1800. foreach ($reports as $report) {
  1801. $gradenode->add($report->string, $report->link, navigation_node::TYPE_SETTING, null, $report->id, new pix_icon('i/report', ''));
  1802. }
  1803. }
  1804. if ($imports = grade_helper::get_plugins_import($courseid)) {
  1805. $importnode = $gradenode->add($strings['import'], null, navigation_node::TYPE_CONTAINER);
  1806. foreach ($imports as $import) {
  1807. $importnode->add($import->string, $import->link, navigation_node::TYPE_SETTING, null, $import->id, new pix_icon('i/restore', ''));
  1808. }
  1809. }
  1810. if ($exports = grade_helper::get_plugins_export($courseid)) {
  1811. $exportnode = $gradenode->add($strings['export'], null, navigation_node::TYPE_CONTAINER);
  1812. foreach ($exports as $export) {
  1813. $exportnode->add($export->string, $export->link, navigation_node::TYPE_SETTING, null, $export->id, new pix_icon('i/backup', ''));
  1814. }
  1815. }
  1816. if ($setting = grade_helper::get_info_manage_settings($courseid)) {
  1817. $gradenode->add(get_string('coursegradesettings', 'grades'), $setting->link, navigation_node::TYPE_SETTING, null, $setting->id, new pix_icon('i/settings', ''));
  1818. }
  1819. if ($preferences = grade_helper::get_plugins_report_preferences($courseid)) {
  1820. $preferencesnode = $gradenode->add(get_string('myreportpreferences', 'grades'), null, navigation_node::TYPE_CONTAINER);
  1821. foreach ($preferences as $preference) {
  1822. $preferencesnode->add($preference->string, $preference->link, navigation_node::TYPE_SETTING, null, $preference->id, new pix_icon('i/settings', ''));
  1823. }
  1824. }
  1825. if ($letters = grade_helper::get_info_letters($courseid)) {
  1826. $letters = array_shift($letters);
  1827. $gradenode->add($strings['letter'], $letters->link, navigation_node::TYPE_SETTING, null, $letters->id, new pix_icon('i/settings', ''));
  1828. }
  1829. if ($outcomes = grade_helper::get_info_outcomes($courseid)) {
  1830. $outcomes = array_shift($outcomes);
  1831. $gradenode->add($strings['outcome'], $outcomes->link, navigation_node::TYPE_SETTING, null, $outcomes->id, new pix_icon('i/outcomes', ''));
  1832. }
  1833. if ($scales = grade_helper::get_info_scales($courseid)) {
  1834. $gradenode->add($strings['scale'], $scales->link, navigation_node::TYPE_SETTING, null, $scales->id, new pix_icon('i/scales', ''));
  1835. }
  1836. if ($categories = grade_helper::get_info_edit_structure($courseid)) {
  1837. $categoriesnode = $gradenode->add(get_string('categoriesanditems','grades'), null, navigation_node::TYPE_CONTAINER);
  1838. foreach ($categories as $category) {
  1839. $categoriesnode->add($category->string, $category->link, navigation_node::TYPE_SETTING, null, $category->id, new pix_icon('i/report', ''));
  1840. }
  1841. }
  1842. if ($gradenode->contains_active_node()) {
  1843. // If the gradenode is active include the settings base node (gradeadministration) in
  1844. // the navbar, typcially this is ignored.
  1845. $PAGE->navbar->includesettingsbase = true;
  1846. // If we can get the course admin node make sure it is closed by default
  1847. // as in this case the gradenode will be opened
  1848. if ($coursenode = $PAGE->settingsnav->get('courseadmin', navigation_node::TYPE_COURSE)){
  1849. $coursenode->make_inactive();
  1850. $coursenode->forceopen = false;
  1851. }
  1852. }
  1853. }
  1854. /**
  1855. * Grade helper class
  1856. *
  1857. * This class provides several helpful functions that work irrespective of any
  1858. * current state.
  1859. *
  1860. * @copyright 2010 Sam Hemelryk
  1861. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1862. */
  1863. abstract class grade_helper {
  1864. /**
  1865. * Cached manage settings info {@see get_info_settings}
  1866. * @var grade_plugin_info|false
  1867. */
  1868. protected static $managesetting = null;
  1869. /**
  1870. * Cached grade report plugins {@see get_plugins_reports}
  1871. * @var array|false
  1872. */
  1873. protected static $gradereports = null;
  1874. /**
  1875. * Cached grade report plugins preferences {@see get_info_scales}
  1876. * @var array|false
  1877. */
  1878. protected static $gradereportpreferences = null;
  1879. /**
  1880. * Cached scale info {@see get_info_scales}
  1881. * @var grade_plugin_info|false
  1882. */
  1883. protected static $scaleinfo = null;
  1884. /**
  1885. * Cached outcome info {@see get_info_outcomes}
  1886. * @var grade_plugin_info|false
  1887. */
  1888. protected static $outcomeinfo = null;
  1889. /**
  1890. * Cached info on edit structure {@see get_info_edit_structure}
  1891. * @var array|false
  1892. */
  1893. protected static $edittree = null;
  1894. /**
  1895. * Cached leftter info {@see get_info_letters}
  1896. * @var grade_plugin_info|false
  1897. */
  1898. protected static $letterinfo = null;
  1899. /**
  1900. * Cached grade import plugins {@see get_plugins_import}
  1901. * @var array|false
  1902. */
  1903. protected static $importplugins = null;
  1904. /**
  1905. * Cached grade export plugins {@see get_plugins_export}
  1906. * @var array|false
  1907. */
  1908. protected static $exportplugins = null;
  1909. /**
  1910. * Cached grade plugin strings
  1911. * @var array
  1912. */
  1913. protected static $pluginstrings = null;
  1914. /**
  1915. * Gets strings commonly used by the describe plugins
  1916. *
  1917. * report => get_string('view'),
  1918. * edittree => get_string('edittree', 'grades'),
  1919. * scale => get_string('scales'),
  1920. * outcome => get_string('outcomes', 'grades'),
  1921. * letter => get_string('letters', 'grades'),
  1922. * export => get_string('export', 'grades'),
  1923. * import => get_string('import'),
  1924. * preferences => get_string('mypreferences', 'grades'),
  1925. * settings => get_string('settings')
  1926. *
  1927. * @return array
  1928. */
  1929. public static function get_plugin_strings() {
  1930. if (self::$pluginstrings === null) {
  1931. self::$pluginstrings = array(
  1932. 'report' => get_string('view'),
  1933. 'edittree' => get_string('edittree', 'grades'),
  1934. 'scale' => get_string('scales'),
  1935. 'outcome' => get_string('outcomes', 'grades'),
  1936. 'letter' => get_string('letters', 'grades'),
  1937. 'export' => get_string('export', 'grades'),
  1938. 'import' => get_string('import'),
  1939. 'preferences' => get_string('mypreferences', 'grades'),
  1940. 'settings' => get_string('settings')
  1941. );
  1942. }
  1943. return self::$pluginstrings;
  1944. }
  1945. /**
  1946. * Get grade_plugin_info object for managing settings if the user can
  1947. *
  1948. * @param int $courseid
  1949. * @return grade_plugin_info
  1950. */
  1951. public static function get_info_manage_settings($courseid) {
  1952. if (self::$managesetting !== null) {
  1953. return self::$managesetting;
  1954. }
  1955. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  1956. if (has_capability('moodle/course:update', $context)) {
  1957. self::$managesetting = new grade_plugin_info('coursesettings', new moodle_url('/grade/edit/settings/index.php', array('id'=>$courseid)), get_string('course'));
  1958. } else {
  1959. self::$managesetting = false;
  1960. }
  1961. return self::$managesetting;
  1962. }
  1963. /**
  1964. * Returns an array of plugin reports as grade_plugin_info objects
  1965. *
  1966. * @param int $courseid
  1967. * @return array
  1968. */
  1969. public static function get_plugins_reports($courseid) {
  1970. global $SITE;
  1971. if (self::$gradereports !== null) {
  1972. return self::$gradereports;
  1973. }
  1974. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  1975. $gradereports = array();
  1976. $gradepreferences = array();
  1977. foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
  1978. //some reports make no sense if we're not within a course
  1979. if ($courseid==$SITE->id && ($plugin=='grader' || $plugin=='user')) {
  1980. continue;
  1981. }
  1982. // Remove ones we can't see
  1983. if (!has_capability('gradereport/'.$plugin.':view', $context)) {
  1984. continue;
  1985. }
  1986. $pluginstr = get_string('pluginname', 'gradereport_'.$plugin);
  1987. $url = new moodle_url('/grade/report/'.$plugin.'/index.php', array('id'=>$courseid));
  1988. $gradereports[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
  1989. // Add link to preferences tab if such a page exists
  1990. if (file_exists($plugindir.'/preferences.php')) {
  1991. $url = new moodle_url('/grade/report/'.$plugin.'/preferences.php', array('id'=>$courseid));
  1992. $gradepreferences[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
  1993. }
  1994. }
  1995. if (count($gradereports) == 0) {
  1996. $gradereports = false;
  1997. $gradepreferences = false;
  1998. } else if (count($gradepreferences) == 0) {
  1999. $gradepreferences = false;
  2000. asort($gradereports);
  2001. } else {
  2002. asort($gradereports);
  2003. asort($gradepreferences);
  2004. }
  2005. self::$gradereports = $gradereports;
  2006. self::$gradereportpreferences = $gradepreferences;
  2007. return self::$gradereports;
  2008. }
  2009. /**
  2010. * Returns an array of grade plugin report preferences for plugin reports that
  2011. * support preferences
  2012. * @param int $courseid
  2013. * @return array
  2014. */
  2015. public static function get_plugins_report_preferences($courseid) {
  2016. if (self::$gradereportpreferences !== null) {
  2017. return self::$gradereportpreferences;
  2018. }
  2019. self::get_plugins_reports($courseid);
  2020. return self::$gradereportpreferences;
  2021. }
  2022. /**
  2023. * Get information on scales
  2024. * @param int $courseid
  2025. * @return grade_plugin_info
  2026. */
  2027. public static function get_info_scales($courseid) {
  2028. if (self::$scaleinfo !== null) {
  2029. return self::$scaleinfo;
  2030. }
  2031. if (has_capability('moodle/course:managescales', get_context_instance(CONTEXT_COURSE, $courseid))) {
  2032. $url = new moodle_url('/grade/edit/scale/index.php', array('id'=>$courseid));
  2033. self::$scaleinfo = new grade_plugin_info('scale', $url, get_string('view'));
  2034. } else {
  2035. self::$scaleinfo = false;
  2036. }
  2037. return self::$scaleinfo;
  2038. }
  2039. /**
  2040. * Get information on outcomes
  2041. * @param int $courseid
  2042. * @return grade_plugin_info
  2043. */
  2044. public static function get_info_outcomes($courseid) {
  2045. global $CFG, $SITE;
  2046. if (self::$outcomeinfo !== null) {
  2047. return self::$outcomeinfo;
  2048. }
  2049. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  2050. $canmanage = has_capability('moodle/grade:manage', $context);
  2051. $canupdate = has_capability('moodle/course:update', $context);
  2052. if (!empty($CFG->enableoutcomes) && ($canmanage || $canupdate)) {
  2053. $outcomes = array();
  2054. if ($canupdate) {
  2055. if ($courseid!=$SITE->id) {
  2056. $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
  2057. $outcomes['course'] = new grade_plugin_info('course', $url, get_string('outcomescourse', 'grades'));
  2058. }
  2059. $url = new moodle_url('/grade/edit/outcome/index.php', array('id'=>$courseid));
  2060. $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('editoutcomes', 'grades'));
  2061. $url = new moodle_url('/grade/edit/outcome/import.php', array('courseid'=>$courseid));
  2062. $outcomes['import'] = new grade_plugin_info('import', $url, get_string('importoutcomes', 'grades'));
  2063. } else {
  2064. if ($courseid!=$SITE->id) {
  2065. $url = new moodle_url('/grade/edit/outcome/course.php', array('id'=>$courseid));
  2066. $outcomes['edit'] = new grade_plugin_info('edit', $url, get_string('outcomescourse', 'grades'));
  2067. }
  2068. }
  2069. self::$outcomeinfo = $outcomes;
  2070. } else {
  2071. self::$outcomeinfo = false;
  2072. }
  2073. return self::$outcomeinfo;
  2074. }
  2075. /**
  2076. * Get information on editing structures
  2077. * @param int $courseid
  2078. * @return array
  2079. */
  2080. public static function get_info_edit_structure($courseid) {
  2081. if (self::$edittree !== null) {
  2082. return self::$edittree;
  2083. }
  2084. if (has_capability('moodle/grade:manage', get_context_instance(CONTEXT_COURSE, $courseid))) {
  2085. $url = new moodle_url('/grade/edit/tree/index.php', array('sesskey'=>sesskey(), 'showadvanced'=>'0', 'id'=>$courseid));
  2086. self::$edittree = array(
  2087. 'simpleview' => new grade_plugin_info('simpleview', $url, get_string('simpleview', 'grades')),
  2088. 'fullview' => new grade_plugin_info('fullview', new moodle_url($url, array('showadvanced'=>'1')), get_string('fullview', 'grades'))
  2089. );
  2090. } else {
  2091. self::$edittree = false;
  2092. }
  2093. return self::$edittree;
  2094. }
  2095. /**
  2096. * Get information on letters
  2097. * @param int $courseid
  2098. * @return array
  2099. */
  2100. public static function get_info_letters($courseid) {
  2101. if (self::$letterinfo !== null) {
  2102. return self::$letterinfo;
  2103. }
  2104. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  2105. $canmanage = has_capability('moodle/grade:manage', $context);
  2106. $canmanageletters = has_capability('moodle/grade:manageletters', $context);
  2107. if ($canmanage || $canmanageletters) {
  2108. self::$letterinfo = array(
  2109. 'view' => new grade_plugin_info('view', new moodle_url('/grade/edit/letter/index.php', array('id'=>$context->id)), get_string('view')),
  2110. 'edit' => new grade_plugin_info('edit', new moodle_url('/grade/edit/letter/index.php', array('edit'=>1,'id'=>$context->id)), get_string('edit'))
  2111. );
  2112. } else {
  2113. self::$letterinfo = false;
  2114. }
  2115. return self::$letterinfo;
  2116. }
  2117. /**
  2118. * Get information import plugins
  2119. * @param int $courseid
  2120. * @return array
  2121. */
  2122. public static function get_plugins_import($courseid) {
  2123. global $CFG;
  2124. if (self::$importplugins !== null) {
  2125. return self::$importplugins;
  2126. }
  2127. $importplugins = array();
  2128. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  2129. if (has_capability('moodle/grade:import', $context)) {
  2130. foreach (get_plugin_list('gradeimport') as $plugin => $plugindir) {
  2131. if (!has_capability('gradeimport/'.$plugin.':view', $context)) {
  2132. continue;
  2133. }
  2134. $pluginstr = get_string('pluginname', 'gradeimport_'.$plugin);
  2135. $url = new moodle_url('/grade/import/'.$plugin.'/index.php', array('id'=>$courseid));
  2136. $importplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
  2137. }
  2138. if ($CFG->gradepublishing) {
  2139. $url = new moodle_url('/grade/import/keymanager.php', array('id'=>$courseid));
  2140. $importplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
  2141. }
  2142. }
  2143. if (count($importplugins) > 0) {
  2144. asort($importplugins);
  2145. self::$importplugins = $importplugins;
  2146. } else {
  2147. self::$importplugins = false;
  2148. }
  2149. return self::$importplugins;
  2150. }
  2151. /**
  2152. * Get information export plugins
  2153. * @param int $courseid
  2154. * @return array
  2155. */
  2156. public static function get_plugins_export($courseid) {
  2157. global $CFG;
  2158. if (self::$exportplugins !== null) {
  2159. return self::$exportplugins;
  2160. }
  2161. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  2162. $exportplugins = array();
  2163. if (has_capability('moodle/grade:export', $context)) {
  2164. foreach (get_plugin_list('gradeexport') as $plugin => $plugindir) {
  2165. if (!has_capability('gradeexport/'.$plugin.':view', $context)) {
  2166. continue;
  2167. }
  2168. $pluginstr = get_string('pluginname', 'gradeexport_'.$plugin);
  2169. $url = new moodle_url('/grade/export/'.$plugin.'/index.php', array('id'=>$courseid));
  2170. $exportplugins[$plugin] = new grade_plugin_info($plugin, $url, $pluginstr);
  2171. }
  2172. if ($CFG->gradepublishing) {
  2173. $url = new moodle_url('/grade/export/keymanager.php', array('id'=>$courseid));
  2174. $exportplugins['keymanager'] = new grade_plugin_info('keymanager', $url, get_string('keymanager', 'grades'));
  2175. }
  2176. }
  2177. if (count($exportplugins) > 0) {
  2178. asort($exportplugins);
  2179. self::$exportplugins = $exportplugins;
  2180. } else {
  2181. self::$exportplugins = false;
  2182. }
  2183. return self::$exportplugins;
  2184. }
  2185. }