PageRenderTime 75ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/grade/lib.php

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