PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/grade/grading/form/guide/lib.php

https://bitbucket.org/moodle/moodle
PHP | 1017 lines | 646 code | 69 blank | 302 comment | 131 complexity | 3d8a3d356a07395d7f3f06291b6ce3fb 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. * Grading method controller for the guide plugin
  18. *
  19. * @package gradingform_guide
  20. * @copyright 2012 Dan Marsden <dan@danmarsden.com>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. require_once($CFG->dirroot.'/grade/grading/form/lib.php');
  25. /** guide: Used to compare our gradeitem_type against. */
  26. const MARKING_GUIDE = 'guide';
  27. /**
  28. * This controller encapsulates the guide grading logic
  29. *
  30. * @package gradingform_guide
  31. * @copyright 2012 Dan Marsden <dan@danmarsden.com>
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33. */
  34. class gradingform_guide_controller extends gradingform_controller {
  35. // Modes of displaying the guide (used in gradingform_guide_renderer).
  36. /** guide display mode: For editing (moderator or teacher creates a guide) */
  37. const DISPLAY_EDIT_FULL = 1;
  38. /** guide display mode: Preview the guide design with hidden fields */
  39. const DISPLAY_EDIT_FROZEN = 2;
  40. /** guide display mode: Preview the guide design (for person with manage permission) */
  41. const DISPLAY_PREVIEW = 3;
  42. /** guide display mode: Preview the guide (for people being graded) */
  43. const DISPLAY_PREVIEW_GRADED= 8;
  44. /** guide display mode: For evaluation, enabled (teacher grades a student) */
  45. const DISPLAY_EVAL = 4;
  46. /** guide display mode: For evaluation, with hidden fields */
  47. const DISPLAY_EVAL_FROZEN = 5;
  48. /** guide display mode: Teacher reviews filled guide */
  49. const DISPLAY_REVIEW = 6;
  50. /** guide display mode: Dispaly filled guide (i.e. students see their grades) */
  51. const DISPLAY_VIEW = 7;
  52. /** @var stdClass|false the definition structure */
  53. protected $moduleinstance = false;
  54. /**
  55. * Extends the module settings navigation with the guide grading settings
  56. *
  57. * This function is called when the context for the page is an activity module with the
  58. * FEATURE_ADVANCED_GRADING, the user has the permission moodle/grade:managegradingforms
  59. * and there is an area with the active grading method set to 'guide'.
  60. *
  61. * @param settings_navigation $settingsnav {@link settings_navigation}
  62. * @param navigation_node $node {@link navigation_node}
  63. */
  64. public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $node=null) {
  65. $node->add(get_string('definemarkingguide', 'gradingform_guide'),
  66. $this->get_editor_url(), settings_navigation::TYPE_CUSTOM,
  67. null, null, new pix_icon('icon', '', 'gradingform_guide'));
  68. }
  69. /**
  70. * Extends the module navigation
  71. *
  72. * This function is called when the context for the page is an activity module with the
  73. * FEATURE_ADVANCED_GRADING and there is an area with the active grading method set to the given plugin.
  74. *
  75. * @param global_navigation $navigation {@link global_navigation}
  76. * @param navigation_node $node {@link navigation_node}
  77. * @return void
  78. */
  79. public function extend_navigation(global_navigation $navigation, navigation_node $node=null) {
  80. if (has_capability('moodle/grade:managegradingforms', $this->get_context())) {
  81. // No need for preview if user can manage forms, he will have link to manage.php in settings instead.
  82. return;
  83. }
  84. if ($this->is_form_defined() && ($options = $this->get_options()) && !empty($options['alwaysshowdefinition'])) {
  85. $node->add(get_string('gradingof', 'gradingform_guide', get_grading_manager($this->get_areaid())->get_area_title()),
  86. new moodle_url('/grade/grading/form/'.$this->get_method_name().'/preview.php',
  87. array('areaid' => $this->get_areaid())), settings_navigation::TYPE_CUSTOM);
  88. }
  89. }
  90. /**
  91. * Saves the guide definition into the database
  92. *
  93. * @see parent::update_definition()
  94. * @param stdClass $newdefinition guide definition data as coming from gradingform_guide_editguide::get_data()
  95. * @param int $usermodified optional userid of the author of the definition, defaults to the current user
  96. */
  97. public function update_definition(stdClass $newdefinition, $usermodified = null) {
  98. $this->update_or_check_guide($newdefinition, $usermodified, true);
  99. if (isset($newdefinition->guide['regrade']) && $newdefinition->guide['regrade']) {
  100. $this->mark_for_regrade();
  101. }
  102. }
  103. /**
  104. * Either saves the guide definition into the database or check if it has been changed.
  105. *
  106. * Returns the level of changes:
  107. * 0 - no changes
  108. * 1 - only texts or criteria sortorders are changed, students probably do not require re-grading
  109. * 2 - added levels but maximum score on guide is the same, students still may not require re-grading
  110. * 3 - removed criteria or changed number of points, students require re-grading but may be re-graded automatically
  111. * 4 - removed levels - students require re-grading and not all students may be re-graded automatically
  112. * 5 - added criteria - all students require manual re-grading
  113. *
  114. * @param stdClass $newdefinition guide definition data as coming from gradingform_guide_editguide::get_data()
  115. * @param int|null $usermodified optional userid of the author of the definition, defaults to the current user
  116. * @param bool $doupdate if true actually updates DB, otherwise performs a check
  117. * @return int
  118. */
  119. public function update_or_check_guide(stdClass $newdefinition, $usermodified = null, $doupdate = false) {
  120. global $DB;
  121. // Firstly update the common definition data in the {grading_definition} table.
  122. if ($this->definition === false) {
  123. if (!$doupdate) {
  124. // If we create the new definition there is no such thing as re-grading anyway.
  125. return 5;
  126. }
  127. // If definition does not exist yet, create a blank one
  128. // (we need id to save files embedded in description).
  129. parent::update_definition(new stdClass(), $usermodified);
  130. parent::load_definition();
  131. }
  132. if (!isset($newdefinition->guide['options'])) {
  133. $newdefinition->guide['options'] = self::get_default_options();
  134. }
  135. $newdefinition->options = json_encode($newdefinition->guide['options']);
  136. $editoroptions = self::description_form_field_options($this->get_context());
  137. $newdefinition = file_postupdate_standard_editor($newdefinition, 'description', $editoroptions, $this->get_context(),
  138. 'grading', 'description', $this->definition->id);
  139. // Reload the definition from the database.
  140. $currentdefinition = $this->get_definition(true);
  141. // Update guide data.
  142. $haschanges = array();
  143. if (empty($newdefinition->guide['criteria'])) {
  144. $newcriteria = array();
  145. } else {
  146. $newcriteria = $newdefinition->guide['criteria']; // New ones to be saved.
  147. }
  148. $currentcriteria = $currentdefinition->guide_criteria;
  149. $criteriafields = array('sortorder', 'description', 'descriptionformat', 'descriptionmarkers',
  150. 'descriptionmarkersformat', 'shortname', 'maxscore');
  151. foreach ($newcriteria as $id => $criterion) {
  152. if (preg_match('/^NEWID\d+$/', $id)) {
  153. // Insert criterion into DB.
  154. $data = array('definitionid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE,
  155. 'descriptionmarkersformat' => FORMAT_MOODLE); // TODO format is not supported yet.
  156. foreach ($criteriafields as $key) {
  157. if (array_key_exists($key, $criterion)) {
  158. $data[$key] = $criterion[$key];
  159. }
  160. }
  161. if ($doupdate) {
  162. $id = $DB->insert_record('gradingform_guide_criteria', $data);
  163. }
  164. $haschanges[5] = true;
  165. } else {
  166. // Update criterion in DB.
  167. $data = array();
  168. foreach ($criteriafields as $key) {
  169. if (array_key_exists($key, $criterion) && $criterion[$key] != $currentcriteria[$id][$key]) {
  170. $data[$key] = $criterion[$key];
  171. }
  172. }
  173. if (!empty($data)) {
  174. // Update only if something is changed.
  175. $data['id'] = $id;
  176. if ($doupdate) {
  177. $DB->update_record('gradingform_guide_criteria', $data);
  178. }
  179. $haschanges[1] = true;
  180. }
  181. }
  182. }
  183. // Remove deleted criteria from DB.
  184. foreach (array_keys($currentcriteria) as $id) {
  185. if (!array_key_exists($id, $newcriteria)) {
  186. if ($doupdate) {
  187. $DB->delete_records('gradingform_guide_criteria', array('id' => $id));
  188. }
  189. $haschanges[3] = true;
  190. }
  191. }
  192. // Now handle comments.
  193. if (empty($newdefinition->guide['comments'])) {
  194. $newcomment = array();
  195. } else {
  196. $newcomment = $newdefinition->guide['comments']; // New ones to be saved.
  197. }
  198. $currentcomments = $currentdefinition->guide_comments;
  199. $commentfields = array('sortorder', 'description');
  200. foreach ($newcomment as $id => $comment) {
  201. if (preg_match('/^NEWID\d+$/', $id)) {
  202. // Insert criterion into DB.
  203. $data = array('definitionid' => $this->definition->id, 'descriptionformat' => FORMAT_MOODLE);
  204. foreach ($commentfields as $key) {
  205. if (array_key_exists($key, $comment)) {
  206. // Check if key is the comment's description.
  207. if ($key === 'description') {
  208. // Get a trimmed value for the comment description.
  209. $description = trim($comment[$key]);
  210. // Check if the comment description is empty.
  211. if (empty($description)) {
  212. // Continue to the next comment object if the description is empty.
  213. continue 2;
  214. }
  215. }
  216. $data[$key] = $comment[$key];
  217. }
  218. }
  219. if ($doupdate) {
  220. $id = $DB->insert_record('gradingform_guide_comments', $data);
  221. }
  222. } else {
  223. // Update criterion in DB.
  224. $data = array();
  225. foreach ($commentfields as $key) {
  226. if (array_key_exists($key, $comment) && $comment[$key] != $currentcomments[$id][$key]) {
  227. $data[$key] = $comment[$key];
  228. }
  229. }
  230. if (!empty($data)) {
  231. // Update only if something is changed.
  232. $data['id'] = $id;
  233. if ($doupdate) {
  234. $DB->update_record('gradingform_guide_comments', $data);
  235. }
  236. }
  237. }
  238. }
  239. // Remove deleted criteria from DB.
  240. foreach (array_keys($currentcomments) as $id) {
  241. if (!array_key_exists($id, $newcomment)) {
  242. if ($doupdate) {
  243. $DB->delete_records('gradingform_guide_comments', array('id' => $id));
  244. }
  245. }
  246. }
  247. // End comments handle.
  248. foreach (array('status', 'description', 'descriptionformat', 'name', 'options') as $key) {
  249. if (isset($newdefinition->$key) && $newdefinition->$key != $this->definition->$key) {
  250. $haschanges[1] = true;
  251. }
  252. }
  253. if ($usermodified && $usermodified != $this->definition->usermodified) {
  254. $haschanges[1] = true;
  255. }
  256. if (!count($haschanges)) {
  257. return 0;
  258. }
  259. if ($doupdate) {
  260. parent::update_definition($newdefinition, $usermodified);
  261. $this->load_definition();
  262. }
  263. // Return the maximum level of changes.
  264. $changelevels = array_keys($haschanges);
  265. sort($changelevels);
  266. return array_pop($changelevels);
  267. }
  268. /**
  269. * Marks all instances filled with this guide with the status INSTANCE_STATUS_NEEDUPDATE
  270. */
  271. public function mark_for_regrade() {
  272. global $DB;
  273. if ($this->has_active_instances()) {
  274. $conditions = array('definitionid' => $this->definition->id,
  275. 'status' => gradingform_instance::INSTANCE_STATUS_ACTIVE);
  276. $DB->set_field('grading_instances', 'status', gradingform_instance::INSTANCE_STATUS_NEEDUPDATE, $conditions);
  277. }
  278. }
  279. /**
  280. * Loads the guide form definition if it exists
  281. *
  282. * There is a new array called 'guide_criteria' appended to the list of parent's definition properties.
  283. */
  284. protected function load_definition() {
  285. global $DB;
  286. // Check to see if the user prefs have changed - putting here as this function is called on post even when
  287. // validation on the page fails. - hard to find a better place to locate this as it is specific to the guide.
  288. $showdesc = optional_param('showmarkerdesc', null, PARAM_BOOL); // Check if we need to change pref.
  289. $showdescstudent = optional_param('showstudentdesc', null, PARAM_BOOL); // Check if we need to change pref.
  290. if ($showdesc !== null) {
  291. set_user_preference('gradingform_guide-showmarkerdesc', $showdesc);
  292. }
  293. if ($showdescstudent !== null) {
  294. set_user_preference('gradingform_guide-showstudentdesc', $showdescstudent);
  295. }
  296. // Get definition.
  297. $definition = $DB->get_record('grading_definitions', array('areaid' => $this->areaid,
  298. 'method' => $this->get_method_name()), '*');
  299. if (!$definition) {
  300. // The definition doesn't have to exist. It may be that we are only now creating it.
  301. $this->definition = false;
  302. return false;
  303. }
  304. $this->definition = $definition;
  305. // Now get criteria.
  306. $this->definition->guide_criteria = array();
  307. $this->definition->guide_comments = array();
  308. $criteria = $DB->get_recordset('gradingform_guide_criteria', array('definitionid' => $this->definition->id), 'sortorder');
  309. foreach ($criteria as $criterion) {
  310. foreach (array('id', 'sortorder', 'description', 'descriptionformat',
  311. 'maxscore', 'descriptionmarkers', 'descriptionmarkersformat', 'shortname') as $fieldname) {
  312. if ($fieldname == 'maxscore') { // Strip any trailing 0.
  313. $this->definition->guide_criteria[$criterion->id][$fieldname] = (float)$criterion->{$fieldname};
  314. } else {
  315. $this->definition->guide_criteria[$criterion->id][$fieldname] = $criterion->{$fieldname};
  316. }
  317. }
  318. }
  319. $criteria->close();
  320. // Now get comments.
  321. $comments = $DB->get_recordset('gradingform_guide_comments', array('definitionid' => $this->definition->id), 'sortorder');
  322. foreach ($comments as $comment) {
  323. foreach (array('id', 'sortorder', 'description', 'descriptionformat') as $fieldname) {
  324. $this->definition->guide_comments[$comment->id][$fieldname] = $comment->{$fieldname};
  325. }
  326. }
  327. $comments->close();
  328. if (empty($this->moduleinstance)) { // Only set if empty.
  329. $modulename = $this->get_component();
  330. $context = $this->get_context();
  331. if (strpos($modulename, 'mod_') === 0) {
  332. $dbman = $DB->get_manager();
  333. $modulename = substr($modulename, 4);
  334. if ($dbman->table_exists($modulename)) {
  335. $cm = get_coursemodule_from_id($modulename, $context->instanceid);
  336. if (!empty($cm)) { // This should only occur when the course is being deleted.
  337. $this->moduleinstance = $DB->get_record($modulename, array("id"=>$cm->instance));
  338. }
  339. }
  340. }
  341. }
  342. }
  343. /**
  344. * Returns the default options for the guide display
  345. *
  346. * @return array
  347. */
  348. public static function get_default_options() {
  349. $options = array(
  350. 'alwaysshowdefinition' => 1,
  351. 'showmarkspercriterionstudents' => 1,
  352. );
  353. return $options;
  354. }
  355. /**
  356. * Gets the options of this guide definition, fills the missing options with default values
  357. *
  358. * @return array
  359. */
  360. public function get_options() {
  361. $options = self::get_default_options();
  362. if (!empty($this->definition->options)) {
  363. $thisoptions = json_decode($this->definition->options);
  364. foreach ($thisoptions as $option => $value) {
  365. $options[$option] = $value;
  366. }
  367. }
  368. return $options;
  369. }
  370. /**
  371. * Converts the current definition into an object suitable for the editor form's set_data()
  372. *
  373. * @param bool $addemptycriterion whether to add an empty criterion if the guide is completely empty (just being created)
  374. * @return stdClass
  375. */
  376. public function get_definition_for_editing($addemptycriterion = false) {
  377. $definition = $this->get_definition();
  378. $properties = new stdClass();
  379. $properties->areaid = $this->areaid;
  380. if (isset($this->moduleinstance->grade)) {
  381. $properties->modulegrade = $this->moduleinstance->grade;
  382. }
  383. if ($definition) {
  384. foreach (array('id', 'name', 'description', 'descriptionformat', 'status') as $key) {
  385. $properties->$key = $definition->$key;
  386. }
  387. $options = self::description_form_field_options($this->get_context());
  388. $properties = file_prepare_standard_editor($properties, 'description', $options, $this->get_context(),
  389. 'grading', 'description', $definition->id);
  390. }
  391. $properties->guide = array('criteria' => array(), 'options' => $this->get_options(), 'comments' => array());
  392. if (!empty($definition->guide_criteria)) {
  393. $properties->guide['criteria'] = $definition->guide_criteria;
  394. } else if (!$definition && $addemptycriterion) {
  395. $properties->guide['criteria'] = array('addcriterion' => 1);
  396. }
  397. if (!empty($definition->guide_comments)) {
  398. $properties->guide['comments'] = $definition->guide_comments;
  399. } else if (!$definition && $addemptycriterion) {
  400. $properties->guide['comments'] = array('addcomment' => 1);
  401. }
  402. return $properties;
  403. }
  404. /**
  405. * Returns the form definition suitable for cloning into another area
  406. *
  407. * @see parent::get_definition_copy()
  408. * @param gradingform_controller $target the controller of the new copy
  409. * @return stdClass definition structure to pass to the target's {@link update_definition()}
  410. */
  411. public function get_definition_copy(gradingform_controller $target) {
  412. $new = parent::get_definition_copy($target);
  413. $old = $this->get_definition_for_editing();
  414. $new->description_editor = $old->description_editor;
  415. $new->guide = array('criteria' => array(), 'options' => $old->guide['options'], 'comments' => array());
  416. $newcritid = 1;
  417. foreach ($old->guide['criteria'] as $oldcritid => $oldcrit) {
  418. unset($oldcrit['id']);
  419. $new->guide['criteria']['NEWID'.$newcritid] = $oldcrit;
  420. $newcritid++;
  421. }
  422. $newcomid = 1;
  423. foreach ($old->guide['comments'] as $oldcritid => $oldcom) {
  424. unset($oldcom['id']);
  425. $new->guide['comments']['NEWID'.$newcomid] = $oldcom;
  426. $newcomid++;
  427. }
  428. return $new;
  429. }
  430. /**
  431. * Options for displaying the guide description field in the form
  432. *
  433. * @param context $context
  434. * @return array options for the form description field
  435. */
  436. public static function description_form_field_options($context) {
  437. global $CFG;
  438. return array(
  439. 'maxfiles' => -1,
  440. 'maxbytes' => get_max_upload_file_size($CFG->maxbytes),
  441. 'context' => $context,
  442. );
  443. }
  444. /**
  445. * Formats the definition description for display on page
  446. *
  447. * @return string
  448. */
  449. public function get_formatted_description() {
  450. if (!isset($this->definition->description)) {
  451. return '';
  452. }
  453. $context = $this->get_context();
  454. $options = self::description_form_field_options($this->get_context());
  455. $description = file_rewrite_pluginfile_urls($this->definition->description, 'pluginfile.php', $context->id,
  456. 'grading', 'description', $this->definition->id, $options);
  457. $formatoptions = array(
  458. 'noclean' => false,
  459. 'trusted' => false,
  460. 'filter' => true,
  461. 'context' => $context
  462. );
  463. return format_text($description, $this->definition->descriptionformat, $formatoptions);
  464. }
  465. /**
  466. * Returns the guide plugin renderer
  467. *
  468. * @param moodle_page $page the target page
  469. * @return gradingform_guide_renderer
  470. */
  471. public function get_renderer(moodle_page $page) {
  472. return $page->get_renderer('gradingform_'. $this->get_method_name());
  473. }
  474. /**
  475. * Returns the HTML code displaying the preview of the grading form
  476. *
  477. * @param moodle_page $page the target page
  478. * @return string
  479. */
  480. public function render_preview(moodle_page $page) {
  481. if (!$this->is_form_defined()) {
  482. throw new coding_exception('It is the caller\'s responsibility to make sure that the form is actually defined');
  483. }
  484. // Check if current user is able to see preview
  485. $options = $this->get_options();
  486. if (empty($options['alwaysshowdefinition']) && !has_capability('moodle/grade:managegradingforms', $page->context)) {
  487. return '';
  488. }
  489. $criteria = $this->definition->guide_criteria;
  490. $comments = $this->definition->guide_comments;
  491. $output = $this->get_renderer($page);
  492. $guide = '';
  493. $guide .= $output->box($this->get_formatted_description(), 'gradingform_guide-description');
  494. if (has_capability('moodle/grade:managegradingforms', $page->context)) {
  495. $guide .= $output->display_guide_mapping_explained($this->get_min_max_score());
  496. $guide .= $output->display_guide($criteria, $comments, $options, self::DISPLAY_PREVIEW, 'guide');
  497. } else {
  498. $guide .= $output->display_guide($criteria, $comments, $options, self::DISPLAY_PREVIEW_GRADED, 'guide');
  499. }
  500. return $guide;
  501. }
  502. /**
  503. * Deletes the guide definition and all the associated information
  504. */
  505. protected function delete_plugin_definition() {
  506. global $DB;
  507. // Get the list of instances.
  508. $instances = array_keys($DB->get_records('grading_instances', array('definitionid' => $this->definition->id), '', 'id'));
  509. // Delete all fillings.
  510. $DB->delete_records_list('gradingform_guide_fillings', 'instanceid', $instances);
  511. // Delete instances.
  512. $DB->delete_records_list('grading_instances', 'id', $instances);
  513. // Get the list of criteria records.
  514. $criteria = array_keys($DB->get_records('gradingform_guide_criteria',
  515. array('definitionid' => $this->definition->id), '', 'id'));
  516. // Delete critera.
  517. $DB->delete_records_list('gradingform_guide_criteria', 'id', $criteria);
  518. // Delete comments.
  519. $DB->delete_records('gradingform_guide_comments', array('definitionid' => $this->definition->id));
  520. }
  521. /**
  522. * If instanceid is specified and grading instance exists and it is created by this rater for
  523. * this item, this instance is returned.
  524. * If there exists a draft for this raterid+itemid, take this draft (this is the change from parent)
  525. * Otherwise new instance is created for the specified rater and itemid
  526. *
  527. * @param int $instanceid
  528. * @param int $raterid
  529. * @param int $itemid
  530. * @return gradingform_instance
  531. */
  532. public function get_or_create_instance($instanceid, $raterid, $itemid) {
  533. global $DB;
  534. if ($instanceid &&
  535. $instance = $DB->get_record('grading_instances',
  536. array('id' => $instanceid, 'raterid' => $raterid, 'itemid' => $itemid), '*', IGNORE_MISSING)) {
  537. return $this->get_instance($instance);
  538. }
  539. if ($itemid && $raterid) {
  540. $params = array('definitionid' => $this->definition->id, 'raterid' => $raterid, 'itemid' => $itemid);
  541. if ($rs = $DB->get_records('grading_instances', $params, 'timemodified DESC', '*', 0, 1)) {
  542. $record = reset($rs);
  543. $currentinstance = $this->get_current_instance($raterid, $itemid);
  544. if ($record->status == gradingform_guide_instance::INSTANCE_STATUS_INCOMPLETE &&
  545. (!$currentinstance || $record->timemodified > $currentinstance->get_data('timemodified'))) {
  546. $record->isrestored = true;
  547. return $this->get_instance($record);
  548. }
  549. }
  550. }
  551. return $this->create_instance($raterid, $itemid);
  552. }
  553. /**
  554. * Returns html code to be included in student's feedback.
  555. *
  556. * @param moodle_page $page
  557. * @param int $itemid
  558. * @param array $gradinginfo result of function grade_get_grades
  559. * @param string $defaultcontent default string to be returned if no active grading is found
  560. * @param bool $cangrade whether current user has capability to grade in this context
  561. * @return string
  562. */
  563. public function render_grade($page, $itemid, $gradinginfo, $defaultcontent, $cangrade) {
  564. return $this->get_renderer($page)->display_instances($this->get_active_instances($itemid), $defaultcontent, $cangrade);
  565. }
  566. // Full-text search support.
  567. /**
  568. * Prepare the part of the search query to append to the FROM statement
  569. *
  570. * @param string $gdid the alias of grading_definitions.id column used by the caller
  571. * @return string
  572. */
  573. public static function sql_search_from_tables($gdid) {
  574. return " LEFT JOIN {gradingform_guide_criteria} gc ON (gc.definitionid = $gdid)";
  575. }
  576. /**
  577. * Prepare the parts of the SQL WHERE statement to search for the given token
  578. *
  579. * The returned array cosists of the list of SQL comparions and the list of
  580. * respective parameters for the comparisons. The returned chunks will be joined
  581. * with other conditions using the OR operator.
  582. *
  583. * @param string $token token to search for
  584. * @return array An array containing two more arrays
  585. * Array of search SQL fragments
  586. * Array of params for the search fragments
  587. */
  588. public static function sql_search_where($token) {
  589. global $DB;
  590. $subsql = array();
  591. $params = array();
  592. // Search in guide criteria description.
  593. $subsql[] = $DB->sql_like('gc.description', '?', false, false);
  594. $params[] = '%'.$DB->sql_like_escape($token).'%';
  595. return array($subsql, $params);
  596. }
  597. /**
  598. * Calculates and returns the possible minimum and maximum score (in points) for this guide
  599. *
  600. * @return array
  601. */
  602. public function get_min_max_score() {
  603. if (!$this->is_form_available()) {
  604. return null;
  605. }
  606. $returnvalue = array('minscore' => 0, 'maxscore' => 0);
  607. $maxscore = 0;
  608. foreach ($this->get_definition()->guide_criteria as $id => $criterion) {
  609. $maxscore += $criterion['maxscore'];
  610. }
  611. $returnvalue['maxscore'] = $maxscore;
  612. $returnvalue['minscore'] = 0;
  613. if (!$this->is_shared_template()) {
  614. $fieldname = \core_grades\component_gradeitems::get_field_name_for_itemname($this->component, $this->area, 'grade');
  615. if (!empty($this->moduleinstance->{$fieldname})) {
  616. $graderange = make_grades_menu($this->moduleinstance->{$fieldname});
  617. $returnvalue['modulegrade'] = count($graderange) - 1;
  618. }
  619. }
  620. return $returnvalue;
  621. }
  622. /**
  623. * @return array An array containing 2 key/value pairs which hold the external_multiple_structure
  624. * for the 'guide_criteria' and the 'guide_comments'.
  625. * @see gradingform_controller::get_external_definition_details()
  626. * @since Moodle 2.5
  627. */
  628. public static function get_external_definition_details() {
  629. $guide_criteria = new external_multiple_structure(
  630. new external_single_structure(
  631. array(
  632. 'id' => new external_value(PARAM_INT, 'criterion id', VALUE_OPTIONAL),
  633. 'sortorder' => new external_value(PARAM_INT, 'sortorder', VALUE_OPTIONAL),
  634. 'description' => new external_value(PARAM_RAW, 'description', VALUE_OPTIONAL),
  635. 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
  636. 'shortname' => new external_value(PARAM_TEXT, 'description'),
  637. 'descriptionmarkers' => new external_value(PARAM_RAW, 'markers description', VALUE_OPTIONAL),
  638. 'descriptionmarkersformat' => new external_format_value('descriptionmarkers', VALUE_OPTIONAL),
  639. 'maxscore' => new external_value(PARAM_FLOAT, 'maximum score')
  640. )
  641. )
  642. );
  643. $guide_comments = new external_multiple_structure(
  644. new external_single_structure(
  645. array(
  646. 'id' => new external_value(PARAM_INT, 'criterion id', VALUE_OPTIONAL),
  647. 'sortorder' => new external_value(PARAM_INT, 'sortorder', VALUE_OPTIONAL),
  648. 'description' => new external_value(PARAM_RAW, 'description', VALUE_OPTIONAL),
  649. 'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL)
  650. )
  651. ), 'comments', VALUE_OPTIONAL
  652. );
  653. return array('guide_criteria' => $guide_criteria, 'guide_comments' => $guide_comments);
  654. }
  655. /**
  656. * Returns an array that defines the structure of the guide's filling. This function is used by
  657. * the web service function core_grading_external::get_gradingform_instances().
  658. *
  659. * @return An array containing a single key/value pair with the 'criteria' external_multiple_structure
  660. * @see gradingform_controller::get_external_instance_filling_details()
  661. * @since Moodle 2.6
  662. */
  663. public static function get_external_instance_filling_details() {
  664. $criteria = new external_multiple_structure(
  665. new external_single_structure(
  666. array(
  667. 'id' => new external_value(PARAM_INT, 'filling id'),
  668. 'criterionid' => new external_value(PARAM_INT, 'criterion id'),
  669. 'levelid' => new external_value(PARAM_INT, 'level id', VALUE_OPTIONAL),
  670. 'remark' => new external_value(PARAM_RAW, 'remark', VALUE_OPTIONAL),
  671. 'remarkformat' => new external_format_value('remark', VALUE_OPTIONAL),
  672. 'score' => new external_value(PARAM_FLOAT, 'maximum score')
  673. )
  674. ), 'filling', VALUE_OPTIONAL
  675. );
  676. return array ('criteria' => $criteria);
  677. }
  678. }
  679. /**
  680. * Class to manage one guide grading instance. Stores information and performs actions like
  681. * update, copy, validate, submit, etc.
  682. *
  683. * @package gradingform_guide
  684. * @copyright 2012 Dan Marsden <dan@danmarsden.com>
  685. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  686. */
  687. class gradingform_guide_instance extends gradingform_instance {
  688. /** @var array */
  689. protected $guide;
  690. /** @var array An array of validation errors */
  691. protected $validationerrors = array();
  692. /**
  693. * Deletes this (INCOMPLETE) instance from database.
  694. */
  695. public function cancel() {
  696. global $DB;
  697. parent::cancel();
  698. $DB->delete_records('gradingform_guide_fillings', array('instanceid' => $this->get_id()));
  699. }
  700. /**
  701. * Duplicates the instance before editing (optionally substitutes raterid and/or itemid with
  702. * the specified values)
  703. *
  704. * @param int $raterid value for raterid in the duplicate
  705. * @param int $itemid value for itemid in the duplicate
  706. * @return int id of the new instance
  707. */
  708. public function copy($raterid, $itemid) {
  709. global $DB;
  710. $instanceid = parent::copy($raterid, $itemid);
  711. $currentgrade = $this->get_guide_filling();
  712. foreach ($currentgrade['criteria'] as $criterionid => $record) {
  713. $params = array('instanceid' => $instanceid, 'criterionid' => $criterionid,
  714. 'score' => $record['score'], 'remark' => $record['remark'], 'remarkformat' => $record['remarkformat']);
  715. $DB->insert_record('gradingform_guide_fillings', $params);
  716. }
  717. return $instanceid;
  718. }
  719. /**
  720. * Determines whether the submitted form was empty.
  721. *
  722. * @param array $elementvalue value of element submitted from the form
  723. * @return boolean true if the form is empty
  724. */
  725. public function is_empty_form($elementvalue) {
  726. $criteria = $this->get_controller()->get_definition()->guide_criteria;
  727. foreach ($criteria as $id => $criterion) {
  728. $score = $elementvalue['criteria'][$id]['score'];
  729. $remark = $elementvalue['criteria'][$id]['remark'];
  730. if ((isset($score) && $score !== '')
  731. || ((isset($remark) && $remark !== ''))) {
  732. return false;
  733. }
  734. }
  735. return true;
  736. }
  737. /**
  738. * Validates that guide is fully completed and contains valid grade on each criterion
  739. *
  740. * @param array $elementvalue value of element as came in form submit
  741. * @return boolean true if the form data is validated and contains no errors
  742. */
  743. public function validate_grading_element($elementvalue) {
  744. $criteria = $this->get_controller()->get_definition()->guide_criteria;
  745. if (!isset($elementvalue['criteria']) || !is_array($elementvalue['criteria']) ||
  746. count($elementvalue['criteria']) < count($criteria)) {
  747. return false;
  748. }
  749. // Reset validation errors.
  750. $this->validationerrors = null;
  751. foreach ($criteria as $id => $criterion) {
  752. if (!isset($elementvalue['criteria'][$id]['score'])
  753. || $criterion['maxscore'] < $elementvalue['criteria'][$id]['score']
  754. || !is_numeric($elementvalue['criteria'][$id]['score'])
  755. || $elementvalue['criteria'][$id]['score'] < 0) {
  756. $this->validationerrors[$id]['score'] = $elementvalue['criteria'][$id]['score'];
  757. }
  758. }
  759. if (!empty($this->validationerrors)) {
  760. return false;
  761. }
  762. return true;
  763. }
  764. /**
  765. * Retrieves from DB and returns the data how this guide was filled
  766. *
  767. * @param bool $force whether to force DB query even if the data is cached
  768. * @return array
  769. */
  770. public function get_guide_filling($force = false) {
  771. global $DB;
  772. if ($this->guide === null || $force) {
  773. $records = $DB->get_records('gradingform_guide_fillings', array('instanceid' => $this->get_id()));
  774. $this->guide = array('criteria' => array());
  775. foreach ($records as $record) {
  776. $record->score = (float)$record->score; // Strip trailing 0.
  777. $this->guide['criteria'][$record->criterionid] = (array)$record;
  778. }
  779. }
  780. return $this->guide;
  781. }
  782. /**
  783. * Updates the instance with the data received from grading form. This function may be
  784. * called via AJAX when grading is not yet completed, so it does not change the
  785. * status of the instance.
  786. *
  787. * @param array $data
  788. */
  789. public function update($data) {
  790. global $DB;
  791. $currentgrade = $this->get_guide_filling();
  792. parent::update($data);
  793. foreach ($data['criteria'] as $criterionid => $record) {
  794. if (!array_key_exists($criterionid, $currentgrade['criteria'])) {
  795. $newrecord = array('instanceid' => $this->get_id(), 'criterionid' => $criterionid,
  796. 'score' => $record['score'], 'remarkformat' => FORMAT_MOODLE);
  797. if (isset($record['remark'])) {
  798. $newrecord['remark'] = $record['remark'];
  799. }
  800. $DB->insert_record('gradingform_guide_fillings', $newrecord);
  801. } else {
  802. $newrecord = array('id' => $currentgrade['criteria'][$criterionid]['id']);
  803. foreach (array('score', 'remark'/*, 'remarkformat' TODO */) as $key) {
  804. if (isset($record[$key]) && $currentgrade['criteria'][$criterionid][$key] != $record[$key]) {
  805. $newrecord[$key] = $record[$key];
  806. }
  807. }
  808. if (count($newrecord) > 1) {
  809. $DB->update_record('gradingform_guide_fillings', $newrecord);
  810. }
  811. }
  812. }
  813. foreach ($currentgrade['criteria'] as $criterionid => $record) {
  814. if (!array_key_exists($criterionid, $data['criteria'])) {
  815. $DB->delete_records('gradingform_guide_fillings', array('id' => $record['id']));
  816. }
  817. }
  818. $this->get_guide_filling(true);
  819. }
  820. /**
  821. * Removes the attempt from the gradingform_guide_fillings table
  822. * @param array $data the attempt data
  823. */
  824. public function clear_attempt($data) {
  825. global $DB;
  826. foreach ($data['criteria'] as $criterionid => $record) {
  827. $DB->delete_records('gradingform_guide_fillings',
  828. array('criterionid' => $criterionid, 'instanceid' => $this->get_id()));
  829. }
  830. }
  831. /**
  832. * Calculates the grade to be pushed to the gradebook
  833. *
  834. * @return float|int the valid grade from $this->get_controller()->get_grade_range()
  835. */
  836. public function get_grade() {
  837. $grade = $this->get_guide_filling();
  838. if (!($scores = $this->get_controller()->get_min_max_score()) || $scores['maxscore'] <= $scores['minscore']) {
  839. return -1;
  840. }
  841. $graderange = array_keys($this->get_controller()->get_grade_range());
  842. if (empty($graderange)) {
  843. return -1;
  844. }
  845. sort($graderange);
  846. $mingrade = $graderange[0];
  847. $maxgrade = $graderange[count($graderange) - 1];
  848. $curscore = 0;
  849. foreach ($grade['criteria'] as $record) {
  850. $curscore += $record['score'];
  851. }
  852. $gradeoffset = ($curscore-$scores['minscore'])/($scores['maxscore']-$scores['minscore'])*
  853. ($maxgrade-$mingrade);
  854. if ($this->get_controller()->get_allow_grade_decimals()) {
  855. return $gradeoffset + $mingrade;
  856. }
  857. return round($gradeoffset, 0) + $mingrade;
  858. }
  859. /**
  860. * Returns html for form element of type 'grading'.
  861. *
  862. * @param moodle_page $page
  863. * @param MoodleQuickForm_grading $gradingformelement
  864. * @return string
  865. */
  866. public function render_grading_element($page, $gradingformelement) {
  867. if (!$gradingformelement->_flagFrozen) {
  868. $module = array('name'=>'gradingform_guide', 'fullpath'=>'/grade/grading/form/guide/js/guide.js');
  869. $page->requires->js_init_call('M.gradingform_guide.init', array(
  870. array('name' => $gradingformelement->getName())), true, $module);
  871. $mode = gradingform_guide_controller::DISPLAY_EVAL;
  872. } else {
  873. if ($gradingformelement->_persistantFreeze) {
  874. $mode = gradingform_guide_controller::DISPLAY_EVAL_FROZEN;
  875. } else {
  876. $mode = gradingform_guide_controller::DISPLAY_REVIEW;
  877. }
  878. }
  879. $criteria = $this->get_controller()->get_definition()->guide_criteria;
  880. $comments = $this->get_controller()->get_definition()->guide_comments;
  881. $options = $this->get_controller()->get_options();
  882. $value = $gradingformelement->getValue();
  883. $html = '';
  884. if ($value === null) {
  885. $value = $this->get_guide_filling();
  886. } else if (!$this->validate_grading_element($value)) {
  887. $html .= html_writer::tag('div', get_string('guidenotcompleted', 'gradingform_guide'),
  888. array('class' => 'gradingform_guide-error'));
  889. if (!empty($this->validationerrors)) {
  890. foreach ($this->validationerrors as $id => $err) {
  891. $a = new stdClass();
  892. $a->criterianame = s($criteria[$id]['shortname']);
  893. $a->maxscore = $criteria[$id]['maxscore'];
  894. if ($this->validationerrors[$id]['score'] < 0) {
  895. $html .= html_writer::tag('div', get_string('err_scoreisnegative', 'gradingform_guide', $a),
  896. array('class' => 'gradingform_guide-error'));
  897. } else {
  898. $html .= html_writer::tag('div', get_string('err_scoreinvalid', 'gradingform_guide', $a),
  899. array('class' => 'gradingform_guide-error'));
  900. }
  901. }
  902. }
  903. }
  904. $currentinstance = $this->get_current_instance();
  905. if ($currentinstance && $currentinstance->get_status() == gradingform_instance::INSTANCE_STATUS_NEEDUPDATE) {
  906. $html .= html_writer::tag('div', get_string('needregrademessage', 'gradingform_guide'),
  907. array('class' => 'gradingform_guide-regrade', 'role' => 'alert'));
  908. }
  909. $haschanges = false;
  910. if ($currentinstance) {
  911. $curfilling = $currentinstance->get_guide_filling();
  912. foreach ($curfilling['criteria'] as $criterionid => $curvalues) {
  913. $value['criteria'][$criterionid]['score'] = $curvalues['score'];
  914. $newremark = null;
  915. $newscore = null;
  916. if (isset($value['criteria'][$criterionid]['remark'])) {
  917. $newremark = $value['criteria'][$criterionid]['remark'];
  918. }
  919. if (isset($value['criteria'][$criterionid]['score'])) {
  920. $newscore = $value['criteria'][$criterionid]['score'];
  921. }
  922. if ($newscore != $curvalues['score'] || $newremark != $curvalues['remark']) {
  923. $haschanges = true;
  924. }
  925. }
  926. }
  927. if ($this->get_data('isrestored') && $haschanges) {
  928. $html .= html_writer::tag('div', get_string('restoredfromdraft', 'gradingform_guide'),
  929. array('class' => 'gradingform_guide-restored'));
  930. }
  931. $html .= html_writer::tag('div', $this->get_controller()->get_formatted_description(),
  932. array('class' => 'gradingform_guide-description'));
  933. $html .= $this->get_controller()->get_renderer($page)->display_guide($criteria, $comments, $options, $mode,
  934. $gradingformelement->getName(), $value, $this->validationerrors);
  935. return $html;
  936. }
  937. }
  938. /**
  939. * Get the icon mapping for font-awesome.
  940. *
  941. * @return array
  942. */
  943. function gradingform_guide_get_fontawesome_icon_map(): array {
  944. return [
  945. 'gradingform_guide:info' => 'fa-info-circle',
  946. 'gradingform_guide:plus' => 'fa-plus',
  947. ];
  948. }