PageRenderTime 62ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/grade/lib.php

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