lib.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. * This defines the core classes of the Moodle question engine.
  18. *
  19. * @package moodlecore
  20. * @subpackage questionengine
  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. require_once($CFG->libdir . '/filelib.php');
  26. require_once(__DIR__ . '/questionusage.php');
  27. require_once(__DIR__ . '/questionattempt.php');
  28. require_once(__DIR__ . '/questionattemptstep.php');
  29. require_once(__DIR__ . '/states.php');
  30. require_once(__DIR__ . '/datalib.php');
  31. require_once(__DIR__ . '/renderer.php');
  32. require_once(__DIR__ . '/bank.php');
  33. require_once(__DIR__ . '/../type/questiontypebase.php');
  34. require_once(__DIR__ . '/../type/questionbase.php');
  35. require_once(__DIR__ . '/../type/rendererbase.php');
  36. require_once(__DIR__ . '/../behaviour/behaviourtypebase.php');
  37. require_once(__DIR__ . '/../behaviour/behaviourbase.php');
  38. require_once(__DIR__ . '/../behaviour/rendererbase.php');
  39. require_once($CFG->libdir . '/questionlib.php');
  40. /**
  41. * This static class provides access to the other question engine classes.
  42. *
  43. * It provides functions for managing question behaviours), and for
  44. * creating, loading, saving and deleting {@link question_usage_by_activity}s,
  45. * which is the main class that is used by other code that wants to use questions.
  46. *
  47. * @copyright 2009 The Open University
  48. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  49. */
  50. abstract class question_engine {
  51. /** @var array behaviour name => 1. Records which behaviours have been loaded. */
  52. private static $loadedbehaviours = array();
  53. /** @var array behaviour name => question_behaviour_type for this behaviour. */
  54. private static $behaviourtypes = array();
  55. /**
  56. * Create a new {@link question_usage_by_activity}. The usage is
  57. * created in memory. If you want it to persist, you will need to call
  58. * {@link save_questions_usage_by_activity()}.
  59. *
  60. * @param string $component the plugin creating this attempt. For example mod_quiz.
  61. * @param object $context the context this usage belongs to.
  62. * @return question_usage_by_activity the newly created object.
  63. */
  64. public static function make_questions_usage_by_activity($component, $context) {
  65. return new question_usage_by_activity($component, $context);
  66. }
  67. /**
  68. * Load a {@link question_usage_by_activity} from the database, based on its id.
  69. * @param int $qubaid the id of the usage to load.
  70. * @param moodle_database $db a database connectoin. Defaults to global $DB.
  71. * @return question_usage_by_activity loaded from the database.
  72. */
  73. public static function load_questions_usage_by_activity($qubaid, moodle_database $db = null) {
  74. $dm = new question_engine_data_mapper($db);
  75. return $dm->load_questions_usage_by_activity($qubaid);
  76. }
  77. /**
  78. * Save a {@link question_usage_by_activity} to the database. This works either
  79. * if the usage was newly created by {@link make_questions_usage_by_activity()}
  80. * or loaded from the database using {@link load_questions_usage_by_activity()}
  81. * @param question_usage_by_activity the usage to save.
  82. * @param moodle_database $db a database connectoin. Defaults to global $DB.
  83. */
  84. public static function save_questions_usage_by_activity(question_usage_by_activity $quba, moodle_database $db = null) {
  85. $dm = new question_engine_data_mapper($db);
  86. $observer = $quba->get_observer();
  87. if ($observer instanceof question_engine_unit_of_work) {
  88. $observer->save($dm);
  89. } else {
  90. $dm->insert_questions_usage_by_activity($quba);
  91. }
  92. }
  93. /**
  94. * Delete a {@link question_usage_by_activity} from the database, based on its id.
  95. * @param int $qubaid the id of the usage to delete.
  96. */
  97. public static function delete_questions_usage_by_activity($qubaid) {
  98. self::delete_questions_usage_by_activities(new qubaid_list(array($qubaid)));
  99. }
  100. /**
  101. * Delete {@link question_usage_by_activity}s from the database.
  102. * @param qubaid_condition $qubaids identifies which questions usages to delete.
  103. */
  104. public static function delete_questions_usage_by_activities(qubaid_condition $qubaids) {
  105. $dm = new question_engine_data_mapper();
  106. $dm->delete_questions_usage_by_activities($qubaids);
  107. }
  108. /**
  109. * Change the maxmark for the question_attempt with number in usage $slot
  110. * for all the specified question_attempts.
  111. * @param qubaid_condition $qubaids Selects which usages are updated.
  112. * @param int $slot the number is usage to affect.
  113. * @param number $newmaxmark the new max mark to set.
  114. */
  115. public static function set_max_mark_in_attempts(qubaid_condition $qubaids,
  116. $slot, $newmaxmark) {
  117. $dm = new question_engine_data_mapper();
  118. $dm->set_max_mark_in_attempts($qubaids, $slot, $newmaxmark);
  119. }
  120. /**
  121. * Validate that the manual grade submitted for a particular question is in range.
  122. * @param int $qubaid the question_usage id.
  123. * @param int $slot the slot number within the usage.
  124. * @return bool whether the submitted data is in range.
  125. */
  126. public static function is_manual_grade_in_range($qubaid, $slot) {
  127. $prefix = 'q' . $qubaid . ':' . $slot . '_';
  128. $mark = question_utils::optional_param_mark($prefix . '-mark');
  129. $maxmark = optional_param($prefix . '-maxmark', null, PARAM_FLOAT);
  130. $minfraction = optional_param($prefix . ':minfraction', null, PARAM_FLOAT);
  131. $maxfraction = optional_param($prefix . ':maxfraction', null, PARAM_FLOAT);
  132. return $mark === '' ||
  133. ($mark !== null && $mark >= $minfraction * $maxmark && $mark <= $maxfraction * $maxmark) ||
  134. ($mark === null && $maxmark === null);
  135. }
  136. /**
  137. * @param array $questionids of question ids.
  138. * @param qubaid_condition $qubaids ids of the usages to consider.
  139. * @return boolean whether any of these questions are being used by any of
  140. * those usages.
  141. */
  142. public static function questions_in_use(array $questionids, qubaid_condition $qubaids = null) {
  143. if (is_null($qubaids)) {
  144. return false;
  145. }
  146. $dm = new question_engine_data_mapper();
  147. return $dm->questions_in_use($questionids, $qubaids);
  148. }
  149. /**
  150. * Get the number of times each variant has been used for each question in a list
  151. * in a set of usages.
  152. * @param array $questionids of question ids.
  153. * @param qubaid_condition $qubaids ids of the usages to consider.
  154. * @return array questionid => variant number => num uses.
  155. */
  156. public static function load_used_variants(array $questionids, qubaid_condition $qubaids) {
  157. $dm = new question_engine_data_mapper();
  158. return $dm->load_used_variants($questionids, $qubaids);
  159. }
  160. /**
  161. * Create an archetypal behaviour for a particular question attempt.
  162. * Used by {@link question_definition::make_behaviour()}.
  163. *
  164. * @param string $preferredbehaviour the type of model required.
  165. * @param question_attempt $qa the question attempt the model will process.
  166. * @return question_behaviour an instance of appropriate behaviour class.
  167. */
  168. public static function make_archetypal_behaviour($preferredbehaviour, question_attempt $qa) {
  169. if (!self::is_behaviour_archetypal($preferredbehaviour)) {
  170. throw new coding_exception('The requested behaviour is not actually ' .
  171. 'an archetypal one.');
  172. }
  173. self::load_behaviour_class($preferredbehaviour);
  174. $class = 'qbehaviour_' . $preferredbehaviour;
  175. return new $class($qa, $preferredbehaviour);
  176. }
  177. /**
  178. * @param string $behaviour the name of a behaviour.
  179. * @return array of {@link question_display_options} field names, that are
  180. * not relevant to this behaviour before a 'finish' action.
  181. */
  182. public static function get_behaviour_unused_display_options($behaviour) {
  183. return self::get_behaviour_type($behaviour)->get_unused_display_options();
  184. }
  185. /**
  186. * With this behaviour, is it possible that a question might finish as the student
  187. * interacts with it, without a call to the {@link question_attempt::finish()} method?
  188. * @param string $behaviour the name of a behaviour. E.g. 'deferredfeedback'.
  189. * @return bool whether with this behaviour, questions may finish naturally.
  190. */
  191. public static function can_questions_finish_during_the_attempt($behaviour) {
  192. return self::get_behaviour_type($behaviour)->can_questions_finish_during_the_attempt();
  193. }
  194. /**
  195. * Create a behaviour for a particular type. If that type cannot be
  196. * found, return an instance of qbehaviour_missing.
  197. *
  198. * Normally you should use {@link make_archetypal_behaviour()}, or
  199. * call the constructor of a particular model class directly. This method
  200. * is only intended for use by {@link question_attempt::load_from_records()}.
  201. *
  202. * @param string $behaviour the type of model to create.
  203. * @param question_attempt $qa the question attempt the model will process.
  204. * @param string $preferredbehaviour the preferred behaviour for the containing usage.
  205. * @return question_behaviour an instance of appropriate behaviour class.
  206. */
  207. public static function make_behaviour($behaviour, question_attempt $qa, $preferredbehaviour) {
  208. try {
  209. self::load_behaviour_class($behaviour);
  210. } catch (Exception $e) {
  211. self::load_behaviour_class('missing');
  212. return new qbehaviour_missing($qa, $preferredbehaviour);
  213. }
  214. $class = 'qbehaviour_' . $behaviour;
  215. return new $class($qa, $preferredbehaviour);
  216. }
  217. /**
  218. * Load the behaviour class(es) belonging to a particular model. That is,
  219. * include_once('/question/behaviour/' . $behaviour . '/behaviour.php'), with a bit
  220. * of checking.
  221. * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
  222. */
  223. public static function load_behaviour_class($behaviour) {
  224. global $CFG;
  225. if (isset(self::$loadedbehaviours[$behaviour])) {
  226. return;
  227. }
  228. $file = $CFG->dirroot . '/question/behaviour/' . $behaviour . '/behaviour.php';
  229. if (!is_readable($file)) {
  230. throw new coding_exception('Unknown question behaviour ' . $behaviour);
  231. }
  232. include_once($file);
  233. $class = 'qbehaviour_' . $behaviour;
  234. if (!class_exists($class)) {
  235. throw new coding_exception('Question behaviour ' . $behaviour .
  236. ' does not define the required class ' . $class . '.');
  237. }
  238. self::$loadedbehaviours[$behaviour] = 1;
  239. }
  240. /**
  241. * Create a behaviour for a particular type. If that type cannot be
  242. * found, return an instance of qbehaviour_missing.
  243. *
  244. * Normally you should use {@link make_archetypal_behaviour()}, or
  245. * call the constructor of a particular model class directly. This method
  246. * is only intended for use by {@link question_attempt::load_from_records()}.
  247. *
  248. * @param string $behaviour the type of model to create.
  249. * @param question_attempt $qa the question attempt the model will process.
  250. * @param string $preferredbehaviour the preferred behaviour for the containing usage.
  251. * @return question_behaviour_type an instance of appropriate behaviour class.
  252. */
  253. public static function get_behaviour_type($behaviour) {
  254. if (array_key_exists($behaviour, self::$behaviourtypes)) {
  255. return self::$behaviourtypes[$behaviour];
  256. }
  257. self::load_behaviour_type_class($behaviour);
  258. $class = 'qbehaviour_' . $behaviour . '_type';
  259. if (class_exists($class)) {
  260. self::$behaviourtypes[$behaviour] = new $class();
  261. } else {
  262. debugging('Question behaviour ' . $behaviour .
  263. ' does not define the required class ' . $class . '.', DEBUG_DEVELOPER);
  264. self::$behaviourtypes[$behaviour] = new question_behaviour_type_fallback($behaviour);
  265. }
  266. return self::$behaviourtypes[$behaviour];
  267. }
  268. /**
  269. * Load the behaviour type class for a particular behaviour. That is,
  270. * include_once('/question/behaviour/' . $behaviour . '/behaviourtype.php').
  271. * @param string $behaviour the behaviour name. For example 'interactive' or 'deferredfeedback'.
  272. */
  273. protected static function load_behaviour_type_class($behaviour) {
  274. global $CFG;
  275. if (isset(self::$behaviourtypes[$behaviour])) {
  276. return;
  277. }
  278. $file = $CFG->dirroot . '/question/behaviour/' . $behaviour . '/behaviourtype.php';
  279. if (!is_readable($file)) {
  280. debugging('Question behaviour ' . $behaviour .
  281. ' is missing the behaviourtype.php file.', DEBUG_DEVELOPER);
  282. }
  283. include_once($file);
  284. }
  285. /**
  286. * Return an array where the keys are the internal names of the archetypal
  287. * behaviours, and the values are a human-readable name. An
  288. * archetypal behaviour is one that is suitable to pass the name of to
  289. * {@link question_usage_by_activity::set_preferred_behaviour()}.
  290. *
  291. * @return array model name => lang string for this behaviour name.
  292. */
  293. public static function get_archetypal_behaviours() {
  294. $archetypes = array();
  295. $behaviours = core_component::get_plugin_list('qbehaviour');
  296. foreach ($behaviours as $behaviour => $notused) {
  297. if (self::is_behaviour_archetypal($behaviour)) {
  298. $archetypes[$behaviour] = self::get_behaviour_name($behaviour);
  299. }
  300. }
  301. asort($archetypes, SORT_LOCALE_STRING);
  302. return $archetypes;
  303. }
  304. /**
  305. * @param string $behaviour the name of a behaviour. E.g. 'deferredfeedback'.
  306. * @return bool whether this is an archetypal behaviour.
  307. */
  308. public static function is_behaviour_archetypal($behaviour) {
  309. return self::get_behaviour_type($behaviour)->is_archetypal();
  310. }
  311. /**
  312. * Return an array where the keys are the internal names of the behaviours
  313. * in preferred order and the values are a human-readable name.
  314. *
  315. * @param array $archetypes, array of behaviours
  316. * @param string $orderlist, a comma separated list of behaviour names
  317. * @param string $disabledlist, a comma separated list of behaviour names
  318. * @param string $current, current behaviour name
  319. * @return array model name => lang string for this behaviour name.
  320. */
  321. public static function sort_behaviours($archetypes, $orderlist, $disabledlist, $current=null) {
  322. // Get disabled behaviours
  323. if ($disabledlist) {
  324. $disabled = explode(',', $disabledlist);
  325. } else {
  326. $disabled = array();
  327. }
  328. if ($orderlist) {
  329. $order = explode(',', $orderlist);
  330. } else {
  331. $order = array();
  332. }
  333. foreach ($disabled as $behaviour) {
  334. if (array_key_exists($behaviour, $archetypes) && $behaviour != $current) {
  335. unset($archetypes[$behaviour]);
  336. }
  337. }
  338. // Get behaviours in preferred order
  339. $behaviourorder = array();
  340. foreach ($order as $behaviour) {
  341. if (array_key_exists($behaviour, $archetypes)) {
  342. $behaviourorder[$behaviour] = $archetypes[$behaviour];
  343. }
  344. }
  345. // Get the rest of behaviours and sort them alphabetically
  346. $leftover = array_diff_key($archetypes, $behaviourorder);
  347. asort($leftover, SORT_LOCALE_STRING);
  348. // Set up the final order to be displayed
  349. return $behaviourorder + $leftover;
  350. }
  351. /**
  352. * Return an array where the keys are the internal names of the behaviours
  353. * in preferred order and the values are a human-readable name.
  354. *
  355. * @param string $currentbehaviour
  356. * @return array model name => lang string for this behaviour name.
  357. */
  358. public static function get_behaviour_options($currentbehaviour) {
  359. $config = question_bank::get_config();
  360. $archetypes = self::get_archetypal_behaviours();
  361. // If no admin setting return all behavious
  362. if (empty($config->disabledbehaviours) && empty($config->behavioursortorder)) {
  363. return $archetypes;
  364. }
  365. if (empty($config->behavioursortorder)) {
  366. $order = '';
  367. } else {
  368. $order = $config->behavioursortorder;
  369. }
  370. if (empty($config->disabledbehaviours)) {
  371. $disabled = '';
  372. } else {
  373. $disabled = $config->disabledbehaviours;
  374. }
  375. return self::sort_behaviours($archetypes, $order, $disabled, $currentbehaviour);
  376. }
  377. /**
  378. * Get the translated name of a behaviour, for display in the UI.
  379. * @param string $behaviour the internal name of the model.
  380. * @return string name from the current language pack.
  381. */
  382. public static function get_behaviour_name($behaviour) {
  383. return get_string('pluginname', 'qbehaviour_' . $behaviour);
  384. }
  385. /**
  386. * @return array all the file area names that may contain response files.
  387. */
  388. public static function get_all_response_file_areas() {
  389. $variables = array();
  390. foreach (question_bank::get_all_qtypes() as $qtype) {
  391. $variables += $qtype->response_file_areas();
  392. }
  393. $areas = array();
  394. foreach (array_unique($variables) as $variable) {
  395. $areas[] = 'response_' . $variable;
  396. }
  397. return $areas;
  398. }
  399. /**
  400. * Returns the valid choices for the number of decimal places for showing
  401. * question marks. For use in the user interface.
  402. * @return array suitable for passing to {@link html_writer::select()} or similar.
  403. */
  404. public static function get_dp_options() {
  405. return question_display_options::get_dp_options();
  406. }
  407. /**
  408. * Initialise the JavaScript required on pages where questions will be displayed.
  409. */
  410. public static function initialise_js() {
  411. return question_flags::initialise_js();
  412. }
  413. }
  414. /**
  415. * This class contains all the options that controls how a question is displayed.
  416. *
  417. * Normally, what will happen is that the calling code will set up some display
  418. * options to indicate what sort of question display it wants, and then before the
  419. * question is rendered, the behaviour will be given a chance to modify the
  420. * display options, so that, for example, A question that is finished will only
  421. * be shown read-only, and a question that has not been submitted will not have
  422. * any sort of feedback displayed.
  423. *
  424. * @copyright 2009 The Open University
  425. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  426. */
  427. class question_display_options {
  428. /**#@+ @var integer named constants for the values that most of the options take. */
  429. const HIDDEN = 0;
  430. const VISIBLE = 1;
  431. const EDITABLE = 2;
  432. /**#@-*/
  433. /**#@+ @var integer named constants for the {@link $marks} option. */
  434. const MAX_ONLY = 1;
  435. const MARK_AND_MAX = 2;
  436. /**#@-*/
  437. /**
  438. * @var integer maximum value for the {@link $markpd} option. This is
  439. * effectively set by the database structure, which uses NUMBER(12,7) columns
  440. * for question marks/fractions.
  441. */
  442. const MAX_DP = 7;
  443. /**
  444. * @var boolean whether the question should be displayed as a read-only review,
  445. * or in an active state where you can change the answer.
  446. */
  447. public $readonly = false;
  448. /**
  449. * @var boolean whether the question type should output hidden form fields
  450. * to reset any incorrect parts of the resonse to blank.
  451. */
  452. public $clearwrong = false;
  453. /**
  454. * Should the student have what they got right and wrong clearly indicated.
  455. * This includes the green/red hilighting of the bits of their response,
  456. * whether the one-line summary of the current state of the question says
  457. * correct/incorrect or just answered.
  458. * @var integer {@link question_display_options::HIDDEN} or
  459. * {@link question_display_options::VISIBLE}
  460. */
  461. public $correctness = self::VISIBLE;
  462. /**
  463. * The the mark and/or the maximum available mark for this question be visible?
  464. * @var integer {@link question_display_options::HIDDEN},
  465. * {@link question_display_options::MAX_ONLY} or {@link question_display_options::MARK_AND_MAX}
  466. */
  467. public $marks = self::MARK_AND_MAX;
  468. /** @var number of decimal places to use when formatting marks for output. */
  469. public $markdp = 2;
  470. /**
  471. * Should the flag this question UI element be visible, and if so, should the
  472. * flag state be changable?
  473. * @var integer {@link question_display_options::HIDDEN},
  474. * {@link question_display_options::VISIBLE} or {@link question_display_options::EDITABLE}
  475. */
  476. public $flags = self::VISIBLE;
  477. /**
  478. * Should the specific feedback be visible.
  479. * @var integer {@link question_display_options::HIDDEN} or
  480. * {@link question_display_options::VISIBLE}
  481. */
  482. public $feedback = self::VISIBLE;
  483. /**
  484. * For questions with a number of sub-parts (like matching, or
  485. * multiple-choice, multiple-reponse) display the number of sub-parts that
  486. * were correct.
  487. * @var integer {@link question_display_options::HIDDEN} or
  488. * {@link question_display_options::VISIBLE}
  489. */
  490. public $numpartscorrect = self::VISIBLE;
  491. /**
  492. * Should the general feedback be visible?
  493. * @var integer {@link question_display_options::HIDDEN} or
  494. * {@link question_display_options::VISIBLE}
  495. */
  496. public $generalfeedback = self::VISIBLE;
  497. /**
  498. * Should the automatically generated display of what the correct answer is
  499. * be visible?
  500. * @var integer {@link question_display_options::HIDDEN} or
  501. * {@link question_display_options::VISIBLE}
  502. */
  503. public $rightanswer = self::VISIBLE;
  504. /**
  505. * Should the manually added marker's comment be visible. Should the link for
  506. * adding/editing the comment be there.
  507. * @var integer {@link question_display_options::HIDDEN},
  508. * {@link question_display_options::VISIBLE}, or {@link question_display_options::EDITABLE}.
  509. * Editable means that form fields are displayed inline.
  510. */
  511. public $manualcomment = self::VISIBLE;
  512. /**
  513. * Should we show a 'Make comment or override grade' link?
  514. * @var string base URL for the edit comment script, which will be shown if
  515. * $manualcomment = self::VISIBLE.
  516. */
  517. public $manualcommentlink = null;
  518. /**
  519. * Used in places like the question history table, to show a link to review
  520. * this question in a certain state. If blank, a link is not shown.
  521. * @var string base URL for a review question script.
  522. */
  523. public $questionreviewlink = null;
  524. /**
  525. * Should the history of previous question states table be visible?
  526. * @var integer {@link question_display_options::HIDDEN} or
  527. * {@link question_display_options::VISIBLE}
  528. */
  529. public $history = self::HIDDEN;
  530. /**
  531. * @since 2.9
  532. * @var string extra HTML to include at the end of the outcome (feedback) box
  533. * of the question display.
  534. *
  535. * This field is now badly named. The place it included is was changed
  536. * (for the better) but the name was left unchanged for backwards compatibility.
  537. */
  538. public $extrainfocontent = '';
  539. /**
  540. * @since 2.9
  541. * @var string extra HTML to include in the history box of the question display,
  542. * if it is shown.
  543. */
  544. public $extrahistorycontent = '';
  545. /**
  546. * If not empty, then a link to edit the question will be included in
  547. * the info box for the question.
  548. *
  549. * If used, this array must contain an element courseid or cmid.
  550. *
  551. * It shoudl also contain a parameter returnurl => moodle_url giving a
  552. * sensible URL to go back to when the editing form is submitted or cancelled.
  553. *
  554. * @var array url parameter for the edit link. id => questiosnid will be
  555. * added automatically.
  556. */
  557. public $editquestionparams = array();
  558. /**
  559. * @var int the context the attempt being output belongs to.
  560. */
  561. public $context;
  562. /**
  563. * Set all the feedback-related fields {@link $feedback}, {@link generalfeedback},
  564. * {@link rightanswer} and {@link manualcomment} to
  565. * {@link question_display_options::HIDDEN}.
  566. */
  567. public function hide_all_feedback() {
  568. $this->feedback = self::HIDDEN;
  569. $this->numpartscorrect = self::HIDDEN;
  570. $this->generalfeedback = self::HIDDEN;
  571. $this->rightanswer = self::HIDDEN;
  572. $this->manualcomment = self::HIDDEN;
  573. $this->correctness = self::HIDDEN;
  574. }
  575. /**
  576. * Returns the valid choices for the number of decimal places for showing
  577. * question marks. For use in the user interface.
  578. *
  579. * Calling code should probably use {@link question_engine::get_dp_options()}
  580. * rather than calling this method directly.
  581. *
  582. * @return array suitable for passing to {@link html_writer::select()} or similar.
  583. */
  584. public static function get_dp_options() {
  585. $options = array();
  586. for ($i = 0; $i <= self::MAX_DP; $i += 1) {
  587. $options[$i] = $i;
  588. }
  589. return $options;
  590. }
  591. }
  592. /**
  593. * Contains the logic for handling question flags.
  594. *
  595. * @copyright 2010 The Open University
  596. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  597. */
  598. abstract class question_flags {
  599. /**
  600. * Get the checksum that validates that a toggle request is valid.
  601. * @param int $qubaid the question usage id.
  602. * @param int $questionid the question id.
  603. * @param int $sessionid the question_attempt id.
  604. * @param object $user the user. If null, defaults to $USER.
  605. * @return string that needs to be sent to question/toggleflag.php for it to work.
  606. */
  607. protected static function get_toggle_checksum($qubaid, $questionid,
  608. $qaid, $slot, $user = null) {
  609. if (is_null($user)) {
  610. global $USER;
  611. $user = $USER;
  612. }
  613. return md5($qubaid . "_" . $user->secret . "_" . $questionid . "_" . $qaid . "_" . $slot);
  614. }
  615. /**
  616. * Get the postdata that needs to be sent to question/toggleflag.php to change the flag state.
  617. * You need to append &newstate=0/1 to this.
  618. * @return the post data to send.
  619. */
  620. public static function get_postdata(question_attempt $qa) {
  621. $qaid = $qa->get_database_id();
  622. $qubaid = $qa->get_usage_id();
  623. $qid = $qa->get_question()->id;
  624. $slot = $qa->get_slot();
  625. $checksum = self::get_toggle_checksum($qubaid, $qid, $qaid, $slot);
  626. return "qaid={$qaid}&qubaid={$qubaid}&qid={$qid}&slot={$slot}&checksum={$checksum}&sesskey=" .
  627. sesskey() . '&newstate=';
  628. }
  629. /**
  630. * If the request seems valid, update the flag state of a question attempt.
  631. * Throws exceptions if this is not a valid update request.
  632. * @param int $qubaid the question usage id.
  633. * @param int $questionid the question id.
  634. * @param int $sessionid the question_attempt id.
  635. * @param string $checksum checksum, as computed by {@link get_toggle_checksum()}
  636. * corresponding to the last three arguments.
  637. * @param bool $newstate the new state of the flag. true = flagged.
  638. */
  639. public static function update_flag($qubaid, $questionid, $qaid, $slot, $checksum, $newstate) {
  640. // Check the checksum - it is very hard to know who a question session belongs
  641. // to, so we require that checksum parameter is matches an md5 hash of the
  642. // three ids and the users username. Since we are only updating a flag, that
  643. // probably makes it sufficiently difficult for malicious users to toggle
  644. // other users flags.
  645. if ($checksum != self::get_toggle_checksum($qubaid, $questionid, $qaid, $slot)) {
  646. throw new moodle_exception('errorsavingflags', 'question');
  647. }
  648. $dm = new question_engine_data_mapper();
  649. $dm->update_question_attempt_flag($qubaid, $questionid, $qaid, $slot, $newstate);
  650. }
  651. public static function initialise_js() {
  652. global $CFG, $PAGE, $OUTPUT;
  653. static $done = false;
  654. if ($done) {
  655. return;
  656. }
  657. $module = array(
  658. 'name' => 'core_question_flags',
  659. 'fullpath' => '/question/flags.js',
  660. 'requires' => array('base', 'dom', 'event-delegate', 'io-base'),
  661. );
  662. $actionurl = $CFG->wwwroot . '/question/toggleflag.php';
  663. $flagtext = array(
  664. 0 => get_string('clickflag', 'question'),
  665. 1 => get_string('clickunflag', 'question')
  666. );
  667. $flagattributes = array(
  668. 0 => array(
  669. 'src' => $OUTPUT->pix_url('i/unflagged') . '',
  670. 'title' => get_string('clicktoflag', 'question'),
  671. 'alt' => get_string('notflagged', 'question'),
  672. // 'text' => get_string('clickflag', 'question'),
  673. ),
  674. 1 => array(
  675. 'src' => $OUTPUT->pix_url('i/flagged') . '',
  676. 'title' => get_string('clicktounflag', 'question'),
  677. 'alt' => get_string('flagged', 'question'),
  678. // 'text' => get_string('clickunflag', 'question'),
  679. ),
  680. );
  681. $PAGE->requires->js_init_call('M.core_question_flags.init',
  682. array($actionurl, $flagattributes, $flagtext), false, $module);
  683. $done = true;
  684. }
  685. }
  686. /**
  687. * Exception thrown when the system detects that a student has done something
  688. * out-of-order to a question. This can happen, for example, if they click
  689. * the browser's back button in a quiz, then try to submit a different response.
  690. *
  691. * @copyright 2010 The Open University
  692. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  693. */
  694. class question_out_of_sequence_exception extends moodle_exception {
  695. public function __construct($qubaid, $slot, $postdata) {
  696. if ($postdata == null) {
  697. $postdata = data_submitted();
  698. }
  699. parent::__construct('submissionoutofsequence', 'question', '', null,
  700. "QUBAid: {$qubaid}, slot: {$slot}, post data: " . print_r($postdata, true));
  701. }
  702. }
  703. /**
  704. * Useful functions for writing question types and behaviours.
  705. *
  706. * @copyright 2010 The Open University
  707. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  708. */
  709. abstract class question_utils {
  710. /**
  711. * Tests to see whether two arrays have the same keys, with the same values
  712. * (as compared by ===) for each key. However, the order of the arrays does
  713. * not have to be the same.
  714. * @param array $array1 the first array.
  715. * @param array $array2 the second array.
  716. * @return bool whether the two arrays have the same keys with the same
  717. * corresponding values.
  718. */
  719. public static function arrays_have_same_keys_and_values(array $array1, array $array2) {
  720. if (count($array1) != count($array2)) {
  721. return false;
  722. }
  723. foreach ($array1 as $key => $value1) {
  724. if (!array_key_exists($key, $array2)) {
  725. return false;
  726. }
  727. if (((string) $value1) !== ((string) $array2[$key])) {
  728. return false;
  729. }
  730. }
  731. return true;
  732. }
  733. /**
  734. * Tests to see whether two arrays have the same value at a particular key.
  735. * This method will return true if:
  736. * 1. Neither array contains the key; or
  737. * 2. Both arrays contain the key, and the corresponding values compare
  738. * identical when cast to strings and compared with ===.
  739. * @param array $array1 the first array.
  740. * @param array $array2 the second array.
  741. * @param string $key an array key.
  742. * @return bool whether the two arrays have the same value (or lack of
  743. * one) for a given key.
  744. */
  745. public static function arrays_same_at_key(array $array1, array $array2, $key) {
  746. if (array_key_exists($key, $array1) && array_key_exists($key, $array2)) {
  747. return ((string) $array1[$key]) === ((string) $array2[$key]);
  748. }
  749. if (!array_key_exists($key, $array1) && !array_key_exists($key, $array2)) {
  750. return true;
  751. }
  752. return false;
  753. }
  754. /**
  755. * Tests to see whether two arrays have the same value at a particular key.
  756. * Missing values are replaced by '', and then the values are cast to
  757. * strings and compared with ===.
  758. * @param array $array1 the first array.
  759. * @param array $array2 the second array.
  760. * @param string $key an array key.
  761. * @return bool whether the two arrays have the same value (or lack of
  762. * one) for a given key.
  763. */
  764. public static function arrays_same_at_key_missing_is_blank(
  765. array $array1, array $array2, $key) {
  766. if (array_key_exists($key, $array1)) {
  767. $value1 = $array1[$key];
  768. } else {
  769. $value1 = '';
  770. }
  771. if (array_key_exists($key, $array2)) {
  772. $value2 = $array2[$key];
  773. } else {
  774. $value2 = '';
  775. }
  776. return ((string) $value1) === ((string) $value2);
  777. }
  778. /**
  779. * Tests to see whether two arrays have the same value at a particular key.
  780. * Missing values are replaced by 0, and then the values are cast to
  781. * integers and compared with ===.
  782. * @param array $array1 the first array.
  783. * @param array $array2 the second array.
  784. * @param string $key an array key.
  785. * @return bool whether the two arrays have the same value (or lack of
  786. * one) for a given key.
  787. */
  788. public static function arrays_same_at_key_integer(
  789. array $array1, array $array2, $key) {
  790. if (array_key_exists($key, $array1)) {
  791. $value1 = (int) $array1[$key];
  792. } else {
  793. $value1 = 0;
  794. }
  795. if (array_key_exists($key, $array2)) {
  796. $value2 = (int) $array2[$key];
  797. } else {
  798. $value2 = 0;
  799. }
  800. return $value1 === $value2;
  801. }
  802. private static $units = array('', 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix');
  803. private static $tens = array('', 'x', 'xx', 'xxx', 'xl', 'l', 'lx', 'lxx', 'lxxx', 'xc');
  804. private static $hundreds = array('', 'c', 'cc', 'ccc', 'cd', 'd', 'dc', 'dcc', 'dccc', 'cm');
  805. private static $thousands = array('', 'm', 'mm', 'mmm');
  806. /**
  807. * Convert an integer to roman numerals.
  808. * @param int $number an integer between 1 and 3999 inclusive. Anything else
  809. * will throw an exception.
  810. * @return string the number converted to lower case roman numerals.
  811. */
  812. public static function int_to_roman($number) {
  813. if (!is_integer($number) || $number < 1 || $number > 3999) {
  814. throw new coding_exception('Only integers between 0 and 3999 can be ' .
  815. 'converted to roman numerals.', $number);
  816. }
  817. return self::$thousands[$number / 1000 % 10] . self::$hundreds[$number / 100 % 10] .
  818. self::$tens[$number / 10 % 10] . self::$units[$number % 10];
  819. }
  820. /**
  821. * Typically, $mark will have come from optional_param($name, null, PARAM_RAW_TRIMMED).
  822. * This method copes with:
  823. * - keeping null or '' input unchanged - important to let teaches set a question back to requries grading.
  824. * - numbers that were typed as either 1.00 or 1,00 form.
  825. * - invalid things, which get turned into null.
  826. *
  827. * @param string|null $mark raw use input of a mark.
  828. * @return float|string|null cleaned mark as a float if possible. Otherwise '' or null.
  829. */
  830. public static function clean_param_mark($mark) {
  831. if ($mark === '' || is_null($mark)) {
  832. return $mark;
  833. }
  834. $mark = str_replace(',', '.', $mark);
  835. // This regexp should match the one in validate_param.
  836. if (!preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', $mark)) {
  837. return null;
  838. }
  839. return clean_param($mark, PARAM_FLOAT);
  840. }
  841. /**
  842. * Get a sumitted variable (from the GET or POST data) that is a mark.
  843. * @param string $parname the submitted variable name.
  844. * @return float|string|null cleaned mark as a float if possible. Otherwise '' or null.
  845. */
  846. public static function optional_param_mark($parname) {
  847. return self::clean_param_mark(
  848. optional_param($parname, null, PARAM_RAW_TRIMMED));
  849. }
  850. /**
  851. * Convert part of some question content to plain text.
  852. * @param string $text the text.
  853. * @param int $format the text format.
  854. * @param array $options formatting options. Passed to {@link format_text}.
  855. * @return float|string|null cleaned mark as a float if possible. Otherwise '' or null.
  856. */
  857. public static function to_plain_text($text, $format, $options = array('noclean' => 'true')) {
  858. // The following call to html_to_text uses the option that strips out
  859. // all URLs, but format_text complains if it finds @@PLUGINFILE@@ tokens.
  860. // So, we need to replace @@PLUGINFILE@@ with a real URL, but it doesn't
  861. // matter what. We use http://example.com/.
  862. $text = str_replace('@@PLUGINFILE@@/', 'http://example.com/', $text);
  863. return html_to_text(format_text($text, $format, $options), 0, false);
  864. }
  865. }
  866. /**
  867. * The interface for strategies for controlling which variant of each question is used.
  868. *
  869. * @copyright 2011 The Open University
  870. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  871. */
  872. interface question_variant_selection_strategy {
  873. /**
  874. * @param int $maxvariants the num
  875. * @param string $seed data that can be used to controls how the variant is selected
  876. * in a semi-random way.
  877. * @return int the variant to use, a number betweeb 1 and $maxvariants inclusive.
  878. */
  879. public function choose_variant($maxvariants, $seed);
  880. }
  881. /**
  882. * A {@link question_variant_selection_strategy} that is completely random.
  883. *
  884. * @copyright 2011 The Open University
  885. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  886. */
  887. class question_variant_random_strategy implements question_variant_selection_strategy {
  888. public function choose_variant($maxvariants, $seed) {
  889. return rand(1, $maxvariants);
  890. }
  891. }
  892. /**
  893. * A {@link question_variant_selection_strategy} that is effectively random
  894. * for the first attempt, and then after that cycles through the available
  895. * variants so that the students will not get a repeated variant until they have
  896. * seen them all.
  897. *
  898. * @copyright 2011 The Open University
  899. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  900. */
  901. class question_variant_pseudorandom_no_repeats_strategy
  902. implements question_variant_selection_strategy {
  903. /** @var int the number of attempts this users has had, including the curent one. */
  904. protected $attemptno;
  905. /** @var int the user id the attempt belongs to. */
  906. protected $userid;
  907. /** @var string extra input fed into the pseudo-random code. */
  908. protected $extrarandomness = '';
  909. /**
  910. * Constructor.
  911. * @param int $attemptno The attempt number.
  912. * @param int $userid the user the attempt is for (defaults to $USER->id).
  913. */
  914. public function __construct($attemptno, $userid = null, $extrarandomness = '') {
  915. $this->attemptno = $attemptno;
  916. if (is_null($userid)) {
  917. global $USER;
  918. $this->userid = $USER->id;
  919. } else {
  920. $this->userid = $userid;
  921. }
  922. if ($extrarandomness) {
  923. $this->extrarandomness = '|' . $extrarandomness;
  924. }
  925. }
  926. public function choose_variant($maxvariants, $seed) {
  927. if ($maxvariants == 1) {
  928. return 1;
  929. }
  930. $hash = sha1($seed . '|user' . $this->userid . $this->extrarandomness);
  931. $randint = hexdec(substr($hash, 17, 7));
  932. return ($randint + $this->attemptno) % $maxvariants + 1;
  933. }
  934. }
  935. /**
  936. * A {@link question_variant_selection_strategy} designed ONLY for testing.
  937. * For selected questions it wil return a specific variants. For the other
  938. * slots it will use a fallback strategy.
  939. *
  940. * @copyright 2013 The Open University
  941. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  942. */
  943. class question_variant_forced_choices_selection_strategy
  944. implements question_variant_selection_strategy {
  945. /** @var array seed => variant to select. */
  946. protected $forcedchoices;
  947. /** @var question_variant_selection_strategy strategy used to make the non-forced choices. */
  948. protected $basestrategy;
  949. /**
  950. * Constructor.
  951. * @param array $forcedchoices array seed => variant to select.
  952. * @param question_variant_selection_strategy $basestrategy strategy used
  953. * to make the non-forced choices.
  954. */
  955. public function __construct(array $forcedchoices, question_variant_selection_strategy $basestrategy) {
  956. $this->forcedchoices = $forcedchoices;
  957. $this->basestrategy = $basestrategy;
  958. }
  959. public function choose_variant($maxvariants, $seed) {
  960. if (array_key_exists($seed, $this->forcedchoices)) {
  961. if ($this->forcedchoices[$seed] > $maxvariants) {
  962. throw new coding_exception('Forced variant out of range.');
  963. }
  964. return $this->forcedchoices[$seed];
  965. } else {
  966. return $this->basestrategy->choose_variant($maxvariants, $seed);
  967. }
  968. }
  969. /**
  970. * Helper method for preparing the $forcedchoices array.
  971. * @param array $variantsbyslot slot number => variant to select.
  972. * @param question_usage_by_activity $quba the question usage we need a strategy for.
  973. * @throws coding_exception when variant cannot be forced as doesn't work.
  974. * @return array that can be passed to the constructor as $forcedchoices.
  975. */
  976. public static function prepare_forced_choices_array(array $variantsbyslot,
  977. question_usage_by_activity $quba) {
  978. $forcedchoices = array();
  979. foreach ($variantsbyslot as $slot => $varianttochoose) {
  980. $question = $quba->get_question($slot);
  981. $seed = $question->get_variants_selection_seed();
  982. if (array_key_exists($seed, $forcedchoices) && $forcedchoices[$seed] != $varianttochoose) {
  983. throw new coding_exception('Inconsistent forced variant detected at slot ' . $slot);
  984. }
  985. if ($varianttochoose > $question->get_num_variants()) {
  986. throw new coding_exception('Forced variant out of range at slot ' . $slot);
  987. }
  988. $forcedchoices[$seed] = $varianttochoose;
  989. }
  990. return $forcedchoices;
  991. }
  992. }