behaviourbase.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. * Defines the question behaviour base class
  18. *
  19. * @package moodlecore
  20. * @subpackage questionbehaviours
  21. * @copyright 2009 The Open University
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. /**
  26. * The base class for question behaviours.
  27. *
  28. * A question behaviour is used by the question engine, specifically by
  29. * a {@link question_attempt} to manage the flow of actions a student can take
  30. * as they work through a question, and later, as a teacher manually grades it.
  31. * In turn, the behaviour will delegate certain processing to the
  32. * relevant {@link question_definition}.
  33. *
  34. * @copyright 2009 The Open University
  35. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36. */
  37. abstract class question_behaviour {
  38. /** @var question_attempt the question attempt we are managing. */
  39. protected $qa;
  40. /** @var question_definition shortcut to $qa->get_question(). */
  41. protected $question;
  42. /**
  43. * Normally you should not call this constuctor directly. The appropriate
  44. * behaviour object is created automatically as part of
  45. * {@link question_attempt::start()}.
  46. * @param question_attempt $qa the question attempt we will be managing.
  47. * @param string $preferredbehaviour the type of behaviour that was actually
  48. * requested. This information is not needed in most cases, the type of
  49. * subclass is enough, but occasionally it is needed.
  50. */
  51. public function __construct(question_attempt $qa, $preferredbehaviour) {
  52. $this->qa = $qa;
  53. $this->question = $qa->get_question();
  54. if (!$this->is_compatible_question($this->question)) {
  55. throw new coding_exception('This behaviour (' . $this->get_name() .
  56. ') cannot work with this question (' . get_class($this->question) . ')');
  57. }
  58. }
  59. /**
  60. * Some behaviours can only work with certing types of question. This method
  61. * allows the behaviour to verify that a question is compatible.
  62. *
  63. * This implementation is only provided for backwards-compatibility. You should
  64. * override this method if you are implementing a behaviour.
  65. *
  66. * @param question_definition $question the question.
  67. */
  68. public abstract function is_compatible_question(question_definition $question);
  69. /**
  70. * @return string the name of this behaviour. For example the name of
  71. * qbehaviour_mymodle is 'mymodel'.
  72. */
  73. public function get_name() {
  74. return substr(get_class($this), 11);
  75. }
  76. /**
  77. * Whether the current attempt at this question could be completed just by the
  78. * student interacting with the question, before $qa->finish() is called.
  79. *
  80. * @return boolean whether the attempt can finish naturally.
  81. */
  82. public function can_finish_during_attempt() {
  83. return false;
  84. }
  85. /**
  86. * Cause the question to be renderered. This gets the appropriate behaviour
  87. * renderer using {@link get_renderer()}, and adjusts the display
  88. * options using {@link adjust_display_options()} and then calls
  89. * {@link core_question_renderer::question()} to do the work.
  90. * @param question_display_options $options controls what should and should not be displayed.
  91. * @param unknown_type $number the question number to display.
  92. * @param core_question_renderer $qoutput the question renderer that will coordinate everything.
  93. * @param qtype_renderer $qtoutput the question type renderer that will be helping.
  94. * @return HTML fragment.
  95. */
  96. public function render(question_display_options $options, $number,
  97. core_question_renderer $qoutput, qtype_renderer $qtoutput) {
  98. $behaviouroutput = $this->get_renderer($qoutput->get_page());
  99. $options = clone($options);
  100. $this->adjust_display_options($options);
  101. return $qoutput->question($this->qa, $behaviouroutput, $qtoutput, $options, $number);
  102. }
  103. /**
  104. * Checks whether the users is allow to be served a particular file.
  105. * @param question_display_options $options the options that control display of the question.
  106. * @param string $component the name of the component we are serving files for.
  107. * @param string $filearea the name of the file area.
  108. * @param array $args the remaining bits of the file path.
  109. * @param bool $forcedownload whether the user must be forced to download the file.
  110. * @return bool true if the user can access this file.
  111. */
  112. public function check_file_access($options, $component, $filearea, $args, $forcedownload) {
  113. $this->adjust_display_options($options);
  114. return $this->question->check_file_access($this->qa, $options, $component,
  115. $filearea, $args, $forcedownload);
  116. }
  117. /**
  118. * @param moodle_page $page the page to render for.
  119. * @return qbehaviour_renderer get the appropriate renderer to use for this model.
  120. */
  121. public function get_renderer(moodle_page $page) {
  122. return $page->get_renderer(get_class($this));
  123. }
  124. /**
  125. * Make any changes to the display options before a question is rendered, so
  126. * that it can be displayed in a way that is appropriate for the statue it is
  127. * currently in. For example, by default, if the question is finished, we
  128. * ensure that it is only ever displayed read-only.
  129. * @param question_display_options $options the options to adjust. Just change
  130. * the properties of this object - objects are passed by referece.
  131. */
  132. public function adjust_display_options(question_display_options $options) {
  133. if (!$this->qa->has_marks()) {
  134. $options->correctness = false;
  135. $options->numpartscorrect = false;
  136. }
  137. if ($this->qa->get_state()->is_finished()) {
  138. $options->readonly = true;
  139. $options->numpartscorrect = $options->numpartscorrect &&
  140. $this->qa->get_state()->is_partially_correct() &&
  141. !empty($this->question->shownumcorrect);
  142. } else {
  143. $options->hide_all_feedback();
  144. }
  145. }
  146. /**
  147. * Get the most applicable hint for the question in its current state.
  148. * @return question_hint the most applicable hint, or null, if none.
  149. */
  150. public function get_applicable_hint() {
  151. return null;
  152. }
  153. /**
  154. * What is the minimum fraction that can be scored for this question.
  155. * Normally this will be based on $this->question->get_min_fraction(),
  156. * but may be modified in some way by the behaviour.
  157. *
  158. * @return number the minimum fraction when this question is attempted under
  159. * this behaviour.
  160. */
  161. public function get_min_fraction() {
  162. return 0;
  163. }
  164. /**
  165. * Return the maximum possible fraction that can be scored for this question.
  166. * Normally this will be based on $this->question->get_max_fraction(),
  167. * but may be modified in some way by the behaviour.
  168. *
  169. * @return number the maximum fraction when this question is attempted under
  170. * this behaviour.
  171. */
  172. public function get_max_fraction() {
  173. return $this->question->get_max_fraction();
  174. }
  175. /**
  176. * Return an array of the behaviour variables that could be submitted
  177. * as part of a question of this type, with their types, so they can be
  178. * properly cleaned.
  179. * @return array variable name => PARAM_... constant.
  180. */
  181. public function get_expected_data() {
  182. if (!$this->qa->get_state()->is_finished()) {
  183. return array();
  184. }
  185. $vars = array('comment' => PARAM_RAW, 'commentformat' => PARAM_INT);
  186. if ($this->qa->get_max_mark()) {
  187. $vars['mark'] = PARAM_RAW_TRIMMED;
  188. $vars['maxmark'] = PARAM_FLOAT;
  189. }
  190. return $vars;
  191. }
  192. /**
  193. * Return an array of question type variables for the question in its current
  194. * state. Normally, if {@link adjust_display_options()} would set
  195. * {@link question_display_options::$readonly} to true, then this method
  196. * should return an empty array, otherwise it should return
  197. * $this->question->get_expected_data(). Thus, there should be little need to
  198. * override this method.
  199. * @return array|string variable name => PARAM_... constant, or, as a special case
  200. * that should only be used in unavoidable, the constant question_attempt::USE_RAW_DATA
  201. * meaning take all the raw submitted data belonging to this question.
  202. */
  203. public function get_expected_qt_data() {
  204. $fakeoptions = new question_display_options();
  205. $fakeoptions->readonly = false;
  206. $this->adjust_display_options($fakeoptions);
  207. if ($fakeoptions->readonly) {
  208. return array();
  209. } else {
  210. return $this->question->get_expected_data();
  211. }
  212. }
  213. /**
  214. * Return an array of any im variables, and the value required to get full
  215. * marks.
  216. * @return array variable name => value.
  217. */
  218. public function get_correct_response() {
  219. return array();
  220. }
  221. /**
  222. * Generate a brief, plain-text, summary of this question. This is used by
  223. * various reports. This should show the particular variant of the question
  224. * as presented to students. For example, the calculated quetsion type would
  225. * fill in the particular numbers that were presented to the student.
  226. * This method will return null if such a summary is not possible, or
  227. * inappropriate.
  228. *
  229. * Normally, this method delegates to {question_definition::get_question_summary()}.
  230. *
  231. * @return string|null a plain text summary of this question.
  232. */
  233. public function get_question_summary() {
  234. return $this->question->get_question_summary();
  235. }
  236. /**
  237. * Generate a brief, plain-text, summary of the correct answer to this question.
  238. * This is used by various reports, and can also be useful when testing.
  239. * This method will return null if such a summary is not possible, or
  240. * inappropriate.
  241. *
  242. * @return string|null a plain text summary of the right answer to this question.
  243. */
  244. public function get_right_answer_summary() {
  245. return null;
  246. }
  247. /**
  248. * Used by {@link start_based_on()} to get the data needed to start a new
  249. * attempt from the point this attempt has go to.
  250. * @return array name => value pairs.
  251. */
  252. public function get_resume_data() {
  253. $olddata = $this->qa->get_step(0)->get_all_data();
  254. $olddata = $this->qa->get_last_qt_data() + $olddata;
  255. $olddata = $this->get_our_resume_data() + $olddata;
  256. return $olddata;
  257. }
  258. /**
  259. * Used by {@link start_based_on()} to get the data needed to start a new
  260. * attempt from the point this attempt has go to.
  261. * @return unknown_type
  262. */
  263. protected function get_our_resume_data() {
  264. return array();
  265. }
  266. /**
  267. * Classify responses for this question into a number of sub parts and response classes as defined by
  268. * {@link \question_type::get_possible_responses} for this question type.
  269. *
  270. * @param string $whichtries which tries to analyse for response analysis. Will be one of
  271. * question_attempt::FIRST_TRY, LAST_TRY or ALL_TRIES.
  272. * Defaults to question_attempt::LAST_TRY.
  273. * @return (question_classified_response|array)[] If $whichtries is question_attempt::FIRST_TRY or LAST_TRY index is subpartid
  274. * and values are question_classified_response instances.
  275. * If $whichtries is question_attempt::ALL_TRIES then first key is submitted response no
  276. * and the second key is subpartid.
  277. */
  278. public function classify_response($whichtries = question_attempt::LAST_TRY) {
  279. if ($whichtries == question_attempt::LAST_TRY) {
  280. return $this->question->classify_response($this->qa->get_last_qt_data());
  281. } else {
  282. $stepswithsubmit = $this->qa->get_steps_with_submitted_response_iterator();
  283. if ($whichtries == question_attempt::FIRST_TRY) {
  284. $firsttry = $stepswithsubmit[1];
  285. if ($firsttry) {
  286. return $this->question->classify_response($firsttry->get_qt_data());
  287. } else {
  288. return $this->question->classify_response(array());
  289. }
  290. } else {
  291. $classifiedresponses = array();
  292. foreach ($stepswithsubmit as $submittedresponseno => $step) {
  293. $classifiedresponses[$submittedresponseno] = $this->question->classify_response($step->get_qt_data());
  294. }
  295. return $classifiedresponses;
  296. }
  297. }
  298. }
  299. /**
  300. * Generate a brief textual description of the current state of the question,
  301. * normally displayed under the question number.
  302. *
  303. * @param bool $showcorrectness Whether right/partial/wrong states should
  304. * be distinguised.
  305. * @return string a brief summary of the current state of the qestion attempt.
  306. */
  307. public function get_state_string($showcorrectness) {
  308. return $this->qa->get_state()->default_string($showcorrectness);
  309. }
  310. public abstract function summarise_action(question_attempt_step $step);
  311. /**
  312. * Initialise the first step in a question attempt when a new
  313. * {@link question_attempt} is being started.
  314. *
  315. * This method must call $this->question->start_attempt($step, $variant), and may
  316. * perform additional processing if the behaviour requries it.
  317. *
  318. * @param question_attempt_step $step the first step of the
  319. * question_attempt being started.
  320. * @param int $variant which variant of the question to use.
  321. */
  322. public function init_first_step(question_attempt_step $step, $variant) {
  323. $this->question->start_attempt($step, $variant);
  324. $step->set_state(question_state::$todo);
  325. }
  326. /**
  327. * When an attempt is started based on a previous attempt (see
  328. * {@link question_attempt::start_based_on}) this method is called to setup
  329. * the new attempt.
  330. *
  331. * This method must call $this->question->apply_attempt_state($step), and may
  332. * perform additional processing if the behaviour requries it.
  333. *
  334. * @param question_attempt_step The first step of the {@link question_attempt}
  335. * being loaded.
  336. */
  337. public function apply_attempt_state(question_attempt_step $step) {
  338. $this->question->apply_attempt_state($step);
  339. $step->set_state(question_state::$todo);
  340. }
  341. /**
  342. * Checks whether two manual grading actions are the same. That is, whether
  343. * the comment, and the mark (if given) is the same.
  344. *
  345. * @param question_attempt_step $pendingstep contains the new responses.
  346. * @return bool whether the new response is the same as we already have.
  347. */
  348. protected function is_same_comment($pendingstep) {
  349. $previouscomment = $this->qa->get_last_behaviour_var('comment');
  350. $newcomment = $pendingstep->get_behaviour_var('comment');
  351. if (is_null($previouscomment) && !html_is_blank($newcomment) ||
  352. $previouscomment != $newcomment) {
  353. return false;
  354. }
  355. // So, now we know the comment is the same, so check the mark, if present.
  356. $previousfraction = $this->qa->get_fraction();
  357. $newmark = question_utils::clean_param_mark($pendingstep->get_behaviour_var('mark'));
  358. if (is_null($previousfraction)) {
  359. return is_null($newmark) || $newmark === '';
  360. } else if (is_null($newmark) || $newmark === '') {
  361. return false;
  362. }
  363. $newfraction = $newmark / $pendingstep->get_behaviour_var('maxmark');
  364. return abs($newfraction - $previousfraction) < 0.0000001;
  365. }
  366. /**
  367. * The main entry point for processing an action.
  368. *
  369. * All the various operations that can be performed on a
  370. * {@link question_attempt} get channeled through this function, except for
  371. * {@link question_attempt::start()} which goes to {@link init_first_step()}.
  372. * {@link question_attempt::finish()} becomes an action with im vars
  373. * finish => 1, and manual comment/grade becomes an action with im vars
  374. * comment => comment text, and mark => ..., max_mark => ... if the question
  375. * is graded.
  376. *
  377. * This method should first determine whether the action is significant. For
  378. * example, if no actual action is being performed, but instead the current
  379. * responses are being saved, and there has been no change since the last
  380. * set of responses that were saved, this the action is not significatn. In
  381. * this case, this method should return {@link question_attempt::DISCARD}.
  382. * Otherwise it should return {@link question_attempt::KEEP}.
  383. *
  384. * If the action is significant, this method should also perform any
  385. * necessary updates to $pendingstep. For example, it should call
  386. * {@link question_attempt_step::set_state()} to set the state that results
  387. * from this action, and if this is a grading action, it should call
  388. * {@link question_attempt_step::set_fraction()}.
  389. *
  390. * This method can also call {@link question_attempt_step::set_behaviour_var()} to
  391. * store additional infomation. There are two main uses for this. This can
  392. * be used to store the result of any randomisation done. It is important to
  393. * store the result of randomisation once, and then in future use the same
  394. * outcome if the actions are ever replayed. This is how regrading works.
  395. * The other use is to cache the result of expensive computations performed
  396. * on the raw response data, so that subsequent display and review of the
  397. * question does not have to repeat the same expensive computations.
  398. *
  399. * Often this method is implemented as a dispatching method that examines
  400. * the pending step to determine the kind of action being performed, and
  401. * then calls a more specific method like {@link process_save()} or
  402. * {@link process_comment()}. Look at some of the standard behaviours
  403. * for examples.
  404. *
  405. * @param question_attempt_pending_step $pendingstep a partially initialised step
  406. * containing all the information about the action that is being peformed. This
  407. * information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
  408. * @return bool either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
  409. */
  410. public abstract function process_action(question_attempt_pending_step $pendingstep);
  411. /**
  412. * Auto-saved data. By default this does nothing. interesting processing is
  413. * done in {@link question_behaviour_with_save}.
  414. *
  415. * @param question_attempt_pending_step $pendingstep a partially initialised step
  416. * containing all the information about the action that is being peformed. This
  417. * information can be accessed using {@link question_attempt_step::get_behaviour_var()}.
  418. * @return bool either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
  419. */
  420. public function process_autosave(question_attempt_pending_step $pendingstep) {
  421. return question_attempt::DISCARD;
  422. }
  423. /**
  424. * Implementation of processing a manual comment/grade action that should
  425. * be suitable for most subclasses.
  426. * @param question_attempt_pending_step $pendingstep a partially initialised step
  427. * containing all the information about the action that is being peformed.
  428. * @return bool either {@link question_attempt::KEEP}
  429. */
  430. public function process_comment(question_attempt_pending_step $pendingstep) {
  431. if (!$this->qa->get_state()->is_finished()) {
  432. throw new coding_exception('Cannot manually grade a question before it is finshed.');
  433. }
  434. if ($this->is_same_comment($pendingstep)) {
  435. return question_attempt::DISCARD;
  436. }
  437. if ($pendingstep->has_behaviour_var('mark')) {
  438. $mark = question_utils::clean_param_mark($pendingstep->get_behaviour_var('mark'));
  439. if ($mark === null) {
  440. throw new coding_exception('Inalid number format ' . $pendingstep->get_behaviour_var('mark') .
  441. ' when processing a manual grading action.', 'Question ' . $this->question->id .
  442. ', slot ' . $this->qa->get_slot());
  443. } else if ($mark === '') {
  444. $fraction = null;
  445. } else {
  446. $fraction = $mark / $pendingstep->get_behaviour_var('maxmark');
  447. if ($fraction > $this->qa->get_max_fraction() || $fraction < $this->qa->get_min_fraction()) {
  448. throw new coding_exception('Score out of range when processing ' .
  449. 'a manual grading action.', 'Question ' . $this->question->id .
  450. ', slot ' . $this->qa->get_slot() . ', fraction ' . $fraction);
  451. }
  452. }
  453. $pendingstep->set_fraction($fraction);
  454. }
  455. $pendingstep->set_state($this->qa->get_state()->corresponding_commented_state(
  456. $pendingstep->get_fraction()));
  457. return question_attempt::KEEP;
  458. }
  459. /**
  460. * @param $comment the comment text to format. If omitted,
  461. * $this->qa->get_manual_comment() is used.
  462. * @param $commentformat the format of the comment, one of the FORMAT_... constants.
  463. * @return string the comment, ready to be output.
  464. */
  465. public function format_comment($comment = null, $commentformat = null) {
  466. $formatoptions = new stdClass();
  467. $formatoptions->noclean = true;
  468. $formatoptions->para = false;
  469. if (is_null($comment)) {
  470. list($comment, $commentformat) = $this->qa->get_manual_comment();
  471. }
  472. return format_text($comment, $commentformat, $formatoptions);
  473. }
  474. /**
  475. * @return string a summary of a manual comment action.
  476. * @param unknown_type $step
  477. */
  478. protected function summarise_manual_comment($step) {
  479. $a = new stdClass();
  480. if ($step->has_behaviour_var('comment')) {
  481. $a->comment = shorten_text(html_to_text($this->format_comment(
  482. $step->get_behaviour_var('comment')), 0, false), 200);
  483. } else {
  484. $a->comment = '';
  485. }
  486. $mark = question_utils::clean_param_mark($step->get_behaviour_var('mark'));
  487. if (is_null($mark) || $mark === '') {
  488. return get_string('commented', 'question', $a->comment);
  489. } else {
  490. $a->mark = $mark / $step->get_behaviour_var('maxmark') * $this->qa->get_max_mark();
  491. return get_string('manuallygraded', 'question', $a);
  492. }
  493. }
  494. public function summarise_start($step) {
  495. return get_string('started', 'question');
  496. }
  497. public function summarise_finish($step) {
  498. return get_string('attemptfinished', 'question');
  499. }
  500. /**
  501. * Does this step include a response submitted by a student?
  502. *
  503. * This method should return true for any attempt explicitly submitted by a student. The question engine itself will also
  504. * automatically recognise any last saved response before the attempt is finished, you don't need to return true here for these
  505. * steps with responses which are not explicitly submitted by the student.
  506. *
  507. * @param question_attempt_step $step
  508. * @return bool is this a step within a question attempt that includes a submitted response by a student.
  509. */
  510. public function step_has_a_submitted_response($step) {
  511. return false;
  512. }
  513. }
  514. /**
  515. * A subclass of {@link question_behaviour} that implements a save
  516. * action that is suitable for most questions that implement the
  517. * {@link question_manually_gradable} interface.
  518. *
  519. * @copyright 2009 The Open University
  520. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  521. */
  522. abstract class question_behaviour_with_save extends question_behaviour {
  523. public function required_question_definition_type() {
  524. return 'question_manually_gradable';
  525. }
  526. public function apply_attempt_state(question_attempt_step $step) {
  527. parent::apply_attempt_state($step);
  528. if ($this->question->is_complete_response($step->get_qt_data())) {
  529. $step->set_state(question_state::$complete);
  530. }
  531. }
  532. /**
  533. * Work out whether the response in $pendingstep are significantly different
  534. * from the last set of responses we have stored.
  535. * @param question_attempt_step $pendingstep contains the new responses.
  536. * @return bool whether the new response is the same as we already have.
  537. */
  538. protected function is_same_response(question_attempt_step $pendingstep) {
  539. return $this->question->is_same_response(
  540. $this->qa->get_last_step()->get_qt_data(), $pendingstep->get_qt_data());
  541. }
  542. /**
  543. * Work out whether the response in $pendingstep represent a complete answer
  544. * to the question. Normally this will call
  545. * {@link question_manually_gradable::is_complete_response}, but some
  546. * behaviours, for example the CBM ones, have their own parts to the
  547. * response.
  548. * @param question_attempt_step $pendingstep contains the new responses.
  549. * @return bool whether the new response is complete.
  550. */
  551. protected function is_complete_response(question_attempt_step $pendingstep) {
  552. return $this->question->is_complete_response($pendingstep->get_qt_data());
  553. }
  554. public function process_autosave(question_attempt_pending_step $pendingstep) {
  555. // If already finished. Nothing to do.
  556. if ($this->qa->get_state()->is_finished()) {
  557. return question_attempt::DISCARD;
  558. }
  559. // If the new data is the same as we already have, then we don't need it.
  560. if ($this->is_same_response($pendingstep)) {
  561. return question_attempt::DISCARD;
  562. }
  563. // Repeat that test discarding any existing autosaved data.
  564. if ($this->qa->has_autosaved_step()) {
  565. $this->qa->discard_autosaved_step();
  566. if ($this->is_same_response($pendingstep)) {
  567. return question_attempt::DISCARD;
  568. }
  569. }
  570. // OK, we need to save.
  571. return $this->process_save($pendingstep);
  572. }
  573. /**
  574. * Implementation of processing a save action that should be suitable for
  575. * most subclasses.
  576. * @param question_attempt_pending_step $pendingstep a partially initialised step
  577. * containing all the information about the action that is being peformed.
  578. * @return bool either {@link question_attempt::KEEP} or {@link question_attempt::DISCARD}
  579. */
  580. public function process_save(question_attempt_pending_step $pendingstep) {
  581. if ($this->qa->get_state()->is_finished()) {
  582. return question_attempt::DISCARD;
  583. } else if (!$this->qa->get_state()->is_active()) {
  584. throw new coding_exception('Question is not active, cannot process_actions.');
  585. }
  586. if ($this->is_same_response($pendingstep)) {
  587. return question_attempt::DISCARD;
  588. }
  589. if ($this->is_complete_response($pendingstep)) {
  590. $pendingstep->set_state(question_state::$complete);
  591. } else {
  592. $pendingstep->set_state(question_state::$todo);
  593. }
  594. return question_attempt::KEEP;
  595. }
  596. public function summarise_submit(question_attempt_step $step) {
  597. return get_string('submitted', 'question',
  598. $this->question->summarise_response($step->get_qt_data()));
  599. }
  600. public function summarise_save(question_attempt_step $step) {
  601. $data = $step->get_submitted_data();
  602. if (empty($data)) {
  603. return $this->summarise_start($step);
  604. }
  605. return get_string('saved', 'question',
  606. $this->question->summarise_response($step->get_qt_data()));
  607. }
  608. public function summarise_finish($step) {
  609. $data = $step->get_qt_data();
  610. if ($data) {
  611. return get_string('attemptfinishedsubmitting', 'question',
  612. $this->question->summarise_response($data));
  613. }
  614. return get_string('attemptfinished', 'question');
  615. }
  616. }
  617. abstract class question_behaviour_with_multiple_tries extends question_behaviour_with_save {
  618. public function step_has_a_submitted_response($step) {
  619. return $step->has_behaviour_var('submit') && $step->get_state() != question_state::$invalid;
  620. }
  621. }
  622. /**
  623. * This helper class contains the constants and methods required for
  624. * manipulating scores for certainty based marking.
  625. *
  626. * @copyright 2009 The Open University
  627. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  628. */
  629. abstract class question_cbm {
  630. /**#@+ @var integer named constants for the certainty levels. */
  631. const LOW = 1;
  632. const MED = 2;
  633. const HIGH = 3;
  634. /**#@-*/
  635. /** @var array list of all the certainty levels. */
  636. public static $certainties = array(self::LOW, self::MED, self::HIGH);
  637. /**#@+ @var array coefficients used to adjust the fraction based on certainty. */
  638. protected static $rightscore = array(
  639. self::LOW => 1,
  640. self::MED => 2,
  641. self::HIGH => 3,
  642. );
  643. protected static $wrongscore = array(
  644. self::LOW => 0,
  645. self::MED => -2,
  646. self::HIGH => -6,
  647. );
  648. /**#@-*/
  649. /**#@+ @var array upper and lower limits of the optimal window. */
  650. protected static $lowlimit = array(
  651. self::LOW => 0,
  652. self::MED => 0.666666666666667,
  653. self::HIGH => 0.8,
  654. );
  655. protected static $highlimit = array(
  656. self::LOW => 0.666666666666667,
  657. self::MED => 0.8,
  658. self::HIGH => 1,
  659. );
  660. /**#@-*/
  661. /**
  662. * @return int the default certaintly level that should be assuemd if
  663. * the student does not choose one.
  664. */
  665. public static function default_certainty() {
  666. return self::LOW;
  667. }
  668. /**
  669. * Given a fraction, and a certainty, compute the adjusted fraction.
  670. * @param number $fraction the raw fraction for this question.
  671. * @param int $certainty one of the certainty level constants.
  672. * @return number the adjusted fraction taking the certainty into account.
  673. */
  674. public static function adjust_fraction($fraction, $certainty) {
  675. if ($certainty == -1) {
  676. // Certainty -1 has never been used in standard Moodle, but is
  677. // used in Tony-Gardiner Medwin's patches to mean 'No idea' which
  678. // we intend to implement: MDL-42077. In the mean time, avoid
  679. // errors for people who have used TGM's patches.
  680. return 0;
  681. }
  682. if ($fraction <= 0.00000005) {
  683. return self::$wrongscore[$certainty];
  684. } else {
  685. return self::$rightscore[$certainty] * $fraction;
  686. }
  687. }
  688. /**
  689. * @param int $certainty one of the LOW/MED/HIGH constants.
  690. * @return string a textual description of this certainty.
  691. */
  692. public static function get_string($certainty) {
  693. return get_string('certainty' . $certainty, 'qbehaviour_deferredcbm');
  694. }
  695. /**
  696. * @param int $certainty one of the LOW/MED/HIGH constants.
  697. * @return string a short textual description of this certainty.
  698. */
  699. public static function get_short_string($certainty) {
  700. return get_string('certaintyshort' . $certainty, 'qbehaviour_deferredcbm');
  701. }
  702. /**
  703. * Add information about certainty to a response summary.
  704. * @param string $summary the response summary.
  705. * @param int $certainty the level of certainty to add.
  706. * @return string the summary with information about the certainty added.
  707. */
  708. public static function summary_with_certainty($summary, $certainty) {
  709. if (is_null($certainty)) {
  710. return $summary;
  711. }
  712. return $summary . ' [' . self::get_short_string($certainty) . ']';
  713. }
  714. /**
  715. * @param int $certainty one of the LOW/MED/HIGH constants.
  716. * @return float the lower limit of the optimal probability range for this certainty.
  717. */
  718. public static function optimal_probablility_low($certainty) {
  719. return self::$lowlimit[$certainty];
  720. }
  721. /**
  722. * @param int $certainty one of the LOW/MED/HIGH constants.
  723. * @return float the upper limit of the optimal probability range for this certainty.
  724. */
  725. public static function optimal_probablility_high($certainty) {
  726. return self::$highlimit[$certainty];
  727. }
  728. }