PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/question/engine/datalib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 1613 lines | 911 code | 205 blank | 497 comment | 64 complexity | 38b8a295d88173f99f725eef48b8d645 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0

Large files files are truncated, but you can click here to view the full file

  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. * Code for loading and saving question attempts to and from the database.
  18. *
  19. * A note for future reference. This code is pretty efficient but there are two
  20. * potential optimisations that could be contemplated, at the cost of making the
  21. * code more complex:
  22. *
  23. * 1. (This is the easier one, but probably not worth doing.) In the unit-of-work
  24. * save method, we could get all the ids for steps due to be deleted or modified,
  25. * and delete all the question_attempt_step_data for all of those steps in one
  26. * query. That would save one DB query for each ->stepsupdated. However that number
  27. * is 0 except when re-grading, and when regrading, there are many more inserts
  28. * into question_attempt_step_data than deletes, so it is really hardly worth it.
  29. *
  30. * 2. A more significant optimisation would be to write an efficient
  31. * $DB->insert_records($arrayofrecords) method (for example using functions
  32. * like pg_copy_from) and then whenever we save stuff (unit_of_work->save and
  33. * insert_questions_usage_by_activity) collect together all the records that
  34. * need to be inserted into question_attempt_step_data, and insert them with
  35. * a single call to $DB->insert_records. This is likely to be the biggest win.
  36. * We do a lot of separate inserts into question_attempt_step_data.
  37. *
  38. * @package moodlecore
  39. * @subpackage questionengine
  40. * @copyright 2009 The Open University
  41. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42. */
  43. defined('MOODLE_INTERNAL') || die();
  44. /**
  45. * This class controls the loading and saving of question engine data to and from
  46. * the database.
  47. *
  48. * @copyright 2009 The Open University
  49. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  50. */
  51. class question_engine_data_mapper {
  52. /**
  53. * @var moodle_database normally points to global $DB, but I prefer not to
  54. * use globals if I can help it.
  55. */
  56. protected $db;
  57. /**
  58. * @param moodle_database $db a database connectoin. Defaults to global $DB.
  59. */
  60. public function __construct(moodle_database $db = null) {
  61. if (is_null($db)) {
  62. global $DB;
  63. $this->db = $DB;
  64. } else {
  65. $this->db = $db;
  66. }
  67. }
  68. /**
  69. * Store an entire {@link question_usage_by_activity} in the database,
  70. * including all the question_attempts that comprise it.
  71. * @param question_usage_by_activity $quba the usage to store.
  72. */
  73. public function insert_questions_usage_by_activity(question_usage_by_activity $quba) {
  74. $record = new stdClass();
  75. $record->contextid = $quba->get_owning_context()->id;
  76. $record->component = $quba->get_owning_component();
  77. $record->preferredbehaviour = $quba->get_preferred_behaviour();
  78. $newid = $this->db->insert_record('question_usages', $record);
  79. $quba->set_id_from_database($newid);
  80. foreach ($quba->get_attempt_iterator() as $qa) {
  81. $this->insert_question_attempt($qa, $quba->get_owning_context());
  82. }
  83. }
  84. /**
  85. * Store an entire {@link question_attempt} in the database,
  86. * including all the question_attempt_steps that comprise it.
  87. * @param question_attempt $qa the question attempt to store.
  88. * @param context $context the context of the owning question_usage_by_activity.
  89. */
  90. public function insert_question_attempt(question_attempt $qa, $context) {
  91. $record = new stdClass();
  92. $record->questionusageid = $qa->get_usage_id();
  93. $record->slot = $qa->get_slot();
  94. $record->behaviour = $qa->get_behaviour_name();
  95. $record->questionid = $qa->get_question()->id;
  96. $record->variant = $qa->get_variant();
  97. $record->maxmark = $qa->get_max_mark();
  98. $record->minfraction = $qa->get_min_fraction();
  99. $record->maxfraction = $qa->get_max_fraction();
  100. $record->flagged = $qa->is_flagged();
  101. $record->questionsummary = $qa->get_question_summary();
  102. if (core_text::strlen($record->questionsummary) > question_bank::MAX_SUMMARY_LENGTH) {
  103. // It seems some people write very long quesions! MDL-30760
  104. $record->questionsummary = core_text::substr($record->questionsummary,
  105. 0, question_bank::MAX_SUMMARY_LENGTH - 3) . '...';
  106. }
  107. $record->rightanswer = $qa->get_right_answer_summary();
  108. $record->responsesummary = $qa->get_response_summary();
  109. $record->timemodified = time();
  110. $record->id = $this->db->insert_record('question_attempts', $record);
  111. $qa->set_database_id($record->id);
  112. foreach ($qa->get_step_iterator() as $seq => $step) {
  113. $this->insert_question_attempt_step($step, $record->id, $seq, $context);
  114. }
  115. }
  116. /**
  117. * Helper method used by insert_question_attempt_step and update_question_attempt_step
  118. * @param question_attempt_step $step the step to store.
  119. * @param int $questionattemptid the question attept id this step belongs to.
  120. * @param int $seq the sequence number of this stop.
  121. * @return stdClass data to insert into the database.
  122. */
  123. protected function make_step_record(question_attempt_step $step, $questionattemptid, $seq) {
  124. $record = new stdClass();
  125. $record->questionattemptid = $questionattemptid;
  126. $record->sequencenumber = $seq;
  127. $record->state = (string) $step->get_state();
  128. $record->fraction = $step->get_fraction();
  129. $record->timecreated = $step->get_timecreated();
  130. $record->userid = $step->get_user_id();
  131. return $record;
  132. }
  133. /**
  134. * Helper method used by insert_question_attempt_step and update_question_attempt_step
  135. * @param question_attempt_step $step the step to store.
  136. * @param int $stepid the id of the step.
  137. * @param context $context the context of the owning question_usage_by_activity.
  138. */
  139. protected function insert_step_data(question_attempt_step $step, $stepid, $context) {
  140. foreach ($step->get_all_data() as $name => $value) {
  141. if ($value instanceof question_file_saver) {
  142. $value->save_files($stepid, $context);
  143. }
  144. if ($value instanceof question_response_files) {
  145. $value = (string) $value;
  146. }
  147. $data = new stdClass();
  148. $data->attemptstepid = $stepid;
  149. $data->name = $name;
  150. $data->value = $value;
  151. $this->db->insert_record('question_attempt_step_data', $data, false);
  152. }
  153. }
  154. /**
  155. * Store a {@link question_attempt_step} in the database.
  156. * @param question_attempt_step $step the step to store.
  157. * @param int $questionattemptid the question attept id this step belongs to.
  158. * @param int $seq the sequence number of this stop.
  159. * @param context $context the context of the owning question_usage_by_activity.
  160. */
  161. public function insert_question_attempt_step(question_attempt_step $step,
  162. $questionattemptid, $seq, $context) {
  163. $record = $this->make_step_record($step, $questionattemptid, $seq);
  164. $record->id = $this->db->insert_record('question_attempt_steps', $record);
  165. $this->insert_step_data($step, $record->id, $context);
  166. }
  167. /**
  168. * Update a {@link question_attempt_step} in the database.
  169. * @param question_attempt_step $qa the step to store.
  170. * @param int $questionattemptid the question attept id this step belongs to.
  171. * @param int $seq the sequence number of this stop.
  172. * @param context $context the context of the owning question_usage_by_activity.
  173. */
  174. public function update_question_attempt_step(question_attempt_step $step,
  175. $questionattemptid, $seq, $context) {
  176. $record = $this->make_step_record($step, $questionattemptid, $seq);
  177. $record->id = $step->get_id();
  178. $this->db->update_record('question_attempt_steps', $record);
  179. $this->db->delete_records('question_attempt_step_data',
  180. array('attemptstepid' => $record->id));
  181. $this->insert_step_data($step, $record->id, $context);
  182. }
  183. /**
  184. * Load a {@link question_attempt_step} from the database.
  185. * @param int $stepid the id of the step to load.
  186. * @param question_attempt_step the step that was loaded.
  187. */
  188. public function load_question_attempt_step($stepid) {
  189. $records = $this->db->get_recordset_sql("
  190. SELECT
  191. quba.contextid,
  192. COALLESCE(q.qtype, 'missingtype') AS qtype,
  193. qas.id AS attemptstepid,
  194. qas.questionattemptid,
  195. qas.sequencenumber,
  196. qas.state,
  197. qas.fraction,
  198. qas.timecreated,
  199. qas.userid,
  200. qasd.name,
  201. qasd.value
  202. FROM {question_attempt_steps} qas
  203. JOIN {question_attempts} qa ON qa.id = qas.questionattemptid
  204. JOIN {question_usages} quba ON quba.id = qa.questionusageid
  205. LEFT JOIN {question} q ON q.id = qa.questionid
  206. LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
  207. WHERE
  208. qas.id = :stepid
  209. ", array('stepid' => $stepid));
  210. if (!$records->valid()) {
  211. throw new coding_exception('Failed to load question_attempt_step ' . $stepid);
  212. }
  213. $step = question_attempt_step::load_from_records($records, $stepid);
  214. $records->close();
  215. return $step;
  216. }
  217. /**
  218. * Load a {@link question_attempt} from the database, including all its
  219. * steps.
  220. * @param int $questionattemptid the id of the question attempt to load.
  221. * @param question_attempt the question attempt that was loaded.
  222. */
  223. public function load_question_attempt($questionattemptid) {
  224. $records = $this->db->get_recordset_sql("
  225. SELECT
  226. quba.contextid,
  227. quba.preferredbehaviour,
  228. qa.id AS questionattemptid,
  229. qa.questionusageid,
  230. qa.slot,
  231. qa.behaviour,
  232. qa.questionid,
  233. qa.variant,
  234. qa.maxmark,
  235. qa.minfraction,
  236. qa.maxfraction,
  237. qa.flagged,
  238. qa.questionsummary,
  239. qa.rightanswer,
  240. qa.responsesummary,
  241. qa.timemodified,
  242. qas.id AS attemptstepid,
  243. qas.sequencenumber,
  244. qas.state,
  245. qas.fraction,
  246. qas.timecreated,
  247. qas.userid,
  248. qasd.name,
  249. qasd.value
  250. FROM {question_attempts} qa
  251. JOIN {question_usages} quba ON quba.id = qa.questionusageid
  252. LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  253. LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
  254. WHERE
  255. qa.id = :questionattemptid
  256. ORDER BY
  257. qas.sequencenumber
  258. ", array('questionattemptid' => $questionattemptid));
  259. if (!$records->valid()) {
  260. throw new coding_exception('Failed to load question_attempt ' . $questionattemptid);
  261. }
  262. $record = $records->current();
  263. $qa = question_attempt::load_from_records($records, $questionattemptid,
  264. new question_usage_null_observer(), $record->preferredbehaviour);
  265. $records->close();
  266. return $qa;
  267. }
  268. /**
  269. * Load a {@link question_usage_by_activity} from the database, including
  270. * all its {@link question_attempt}s and all their steps.
  271. * @param int $qubaid the id of the usage to load.
  272. * @param question_usage_by_activity the usage that was loaded.
  273. */
  274. public function load_questions_usage_by_activity($qubaid) {
  275. $records = $this->db->get_recordset_sql("
  276. SELECT
  277. quba.id AS qubaid,
  278. quba.contextid,
  279. quba.component,
  280. quba.preferredbehaviour,
  281. qa.id AS questionattemptid,
  282. qa.questionusageid,
  283. qa.slot,
  284. qa.behaviour,
  285. qa.questionid,
  286. qa.variant,
  287. qa.maxmark,
  288. qa.minfraction,
  289. qa.maxfraction,
  290. qa.flagged,
  291. qa.questionsummary,
  292. qa.rightanswer,
  293. qa.responsesummary,
  294. qa.timemodified,
  295. qas.id AS attemptstepid,
  296. qas.sequencenumber,
  297. qas.state,
  298. qas.fraction,
  299. qas.timecreated,
  300. qas.userid,
  301. qasd.name,
  302. qasd.value
  303. FROM {question_usages} quba
  304. LEFT JOIN {question_attempts} qa ON qa.questionusageid = quba.id
  305. LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  306. LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
  307. WHERE
  308. quba.id = :qubaid
  309. ORDER BY
  310. qa.slot,
  311. qas.sequencenumber
  312. ", array('qubaid' => $qubaid));
  313. if (!$records->valid()) {
  314. throw new coding_exception('Failed to load questions_usage_by_activity ' . $qubaid);
  315. }
  316. $quba = question_usage_by_activity::load_from_records($records, $qubaid);
  317. $records->close();
  318. return $quba;
  319. }
  320. /**
  321. * Load information about the latest state of each question from the database.
  322. *
  323. * @param qubaid_condition $qubaids used to restrict which usages are included
  324. * in the query. See {@link qubaid_condition}.
  325. * @param array $slots A list of slots for the questions you want to know about.
  326. * @param string|null $fields
  327. * @return array of records. See the SQL in this function to see the fields available.
  328. */
  329. public function load_questions_usages_latest_steps(qubaid_condition $qubaids, $slots, $fields = null) {
  330. list($slottest, $params) = $this->db->get_in_or_equal($slots, SQL_PARAMS_NAMED, 'slot');
  331. if ($fields === null) {
  332. $fields = "qas.id,
  333. qa.id AS questionattemptid,
  334. qa.questionusageid,
  335. qa.slot,
  336. qa.behaviour,
  337. qa.questionid,
  338. qa.variant,
  339. qa.maxmark,
  340. qa.minfraction,
  341. qa.maxfraction,
  342. qa.flagged,
  343. qa.questionsummary,
  344. qa.rightanswer,
  345. qa.responsesummary,
  346. qa.timemodified,
  347. qas.id AS attemptstepid,
  348. qas.sequencenumber,
  349. qas.state,
  350. qas.fraction,
  351. qas.timecreated,
  352. qas.userid";
  353. }
  354. $records = $this->db->get_records_sql("
  355. SELECT
  356. {$fields}
  357. FROM {$qubaids->from_question_attempts('qa')}
  358. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  359. AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
  360. WHERE
  361. {$qubaids->where()} AND
  362. qa.slot $slottest
  363. ", $params + $qubaids->from_where_params());
  364. return $records;
  365. }
  366. /**
  367. * Load summary information about the state of each question in a group of
  368. * attempts. This is used, for example, by the quiz manual grading report,
  369. * to show how many attempts at each question need to be graded.
  370. *
  371. * @param qubaid_condition $qubaids used to restrict which usages are included
  372. * in the query. See {@link qubaid_condition}.
  373. * @param array $slots A list of slots for the questions you want to konw about.
  374. * @return array The array keys are slot,qestionid. The values are objects with
  375. * fields $slot, $questionid, $inprogress, $name, $needsgrading, $autograded,
  376. * $manuallygraded and $all.
  377. */
  378. public function load_questions_usages_question_state_summary(
  379. qubaid_condition $qubaids, $slots) {
  380. list($slottest, $params) = $this->db->get_in_or_equal($slots, SQL_PARAMS_NAMED, 'slot');
  381. $rs = $this->db->get_recordset_sql("
  382. SELECT
  383. qa.slot,
  384. qa.questionid,
  385. q.name,
  386. CASE qas.state
  387. {$this->full_states_to_summary_state_sql()}
  388. END AS summarystate,
  389. COUNT(1) AS numattempts
  390. FROM {$qubaids->from_question_attempts('qa')}
  391. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  392. AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
  393. JOIN {question} q ON q.id = qa.questionid
  394. WHERE
  395. {$qubaids->where()} AND
  396. qa.slot $slottest
  397. GROUP BY
  398. qa.slot,
  399. qa.questionid,
  400. q.name,
  401. q.id,
  402. CASE qas.state
  403. {$this->full_states_to_summary_state_sql()}
  404. END
  405. ORDER BY
  406. qa.slot,
  407. qa.questionid,
  408. q.name,
  409. q.id
  410. ", $params + $qubaids->from_where_params());
  411. $results = array();
  412. foreach ($rs as $row) {
  413. $index = $row->slot . ',' . $row->questionid;
  414. if (!array_key_exists($index, $results)) {
  415. $res = new stdClass();
  416. $res->slot = $row->slot;
  417. $res->questionid = $row->questionid;
  418. $res->name = $row->name;
  419. $res->inprogress = 0;
  420. $res->needsgrading = 0;
  421. $res->autograded = 0;
  422. $res->manuallygraded = 0;
  423. $res->all = 0;
  424. $results[$index] = $res;
  425. }
  426. $results[$index]->{$row->summarystate} = $row->numattempts;
  427. $results[$index]->all += $row->numattempts;
  428. }
  429. $rs->close();
  430. return $results;
  431. }
  432. /**
  433. * Get a list of usage ids where the question with slot $slot, and optionally
  434. * also with question id $questionid, is in summary state $summarystate. Also
  435. * return the total count of such states.
  436. *
  437. * Only a subset of the ids can be returned by using $orderby, $limitfrom and
  438. * $limitnum. A special value 'random' can be passed as $orderby, in which case
  439. * $limitfrom is ignored.
  440. *
  441. * @param qubaid_condition $qubaids used to restrict which usages are included
  442. * in the query. See {@link qubaid_condition}.
  443. * @param int $slot The slot for the questions you want to konw about.
  444. * @param int $questionid (optional) Only return attempts that were of this specific question.
  445. * @param string $summarystate the summary state of interest, or 'all'.
  446. * @param string $orderby the column to order by.
  447. * @param array $params any params required by any of the SQL fragments.
  448. * @param int $limitfrom implements paging of the results.
  449. * Ignored if $orderby = random or $limitnum is null.
  450. * @param int $limitnum implements paging of the results. null = all.
  451. * @return array with two elements, an array of usage ids, and a count of the total number.
  452. */
  453. public function load_questions_usages_where_question_in_state(
  454. qubaid_condition $qubaids, $summarystate, $slot, $questionid = null,
  455. $orderby = 'random', $params = array(), $limitfrom = 0, $limitnum = null) {
  456. $extrawhere = '';
  457. if ($questionid) {
  458. $extrawhere .= ' AND qa.questionid = :questionid';
  459. $params['questionid'] = $questionid;
  460. }
  461. if ($summarystate != 'all') {
  462. list($test, $sparams) = $this->in_summary_state_test($summarystate);
  463. $extrawhere .= ' AND qas.state ' . $test;
  464. $params += $sparams;
  465. }
  466. if ($orderby == 'random') {
  467. $sqlorderby = '';
  468. } else if ($orderby) {
  469. $sqlorderby = 'ORDER BY ' . $orderby;
  470. } else {
  471. $sqlorderby = '';
  472. }
  473. // We always want the total count, as well as the partcular list of ids
  474. // based on the paging and sort order. Because the list of ids is never
  475. // going to be too ridiculously long. My worst-case scenario is
  476. // 10,000 students in the course, each doing 5 quiz attempts. That
  477. // is a 50,000 element int => int array, which PHP seems to use 5MB
  478. // memory to store on a 64 bit server.
  479. $qubaidswhere = $qubaids->where(); // Must call this before params.
  480. $params += $qubaids->from_where_params();
  481. $params['slot'] = $slot;
  482. $qubaids = $this->db->get_records_sql_menu("
  483. SELECT
  484. qa.questionusageid,
  485. 1
  486. FROM {$qubaids->from_question_attempts('qa')}
  487. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  488. AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
  489. JOIN {question} q ON q.id = qa.questionid
  490. WHERE
  491. {$qubaidswhere} AND
  492. qa.slot = :slot
  493. $extrawhere
  494. $sqlorderby
  495. ", $params);
  496. $qubaids = array_keys($qubaids);
  497. $count = count($qubaids);
  498. if ($orderby == 'random') {
  499. shuffle($qubaids);
  500. $limitfrom = 0;
  501. }
  502. if (!is_null($limitnum)) {
  503. $qubaids = array_slice($qubaids, $limitfrom, $limitnum);
  504. }
  505. return array($qubaids, $count);
  506. }
  507. /**
  508. * Load a {@link question_usage_by_activity} from the database, including
  509. * all its {@link question_attempt}s and all their steps.
  510. * @param qubaid_condition $qubaids used to restrict which usages are included
  511. * in the query. See {@link qubaid_condition}.
  512. * @param array $slots if null, load info for all quesitions, otherwise only
  513. * load the averages for the specified questions.
  514. */
  515. public function load_average_marks(qubaid_condition $qubaids, $slots = null) {
  516. if (!empty($slots)) {
  517. list($slottest, $slotsparams) = $this->db->get_in_or_equal(
  518. $slots, SQL_PARAMS_NAMED, 'slot');
  519. $slotwhere = " AND qa.slot $slottest";
  520. } else {
  521. $slotwhere = '';
  522. $slotsparams = array();
  523. }
  524. list($statetest, $stateparams) = $this->db->get_in_or_equal(array(
  525. (string) question_state::$gaveup,
  526. (string) question_state::$gradedwrong,
  527. (string) question_state::$gradedpartial,
  528. (string) question_state::$gradedright,
  529. (string) question_state::$mangaveup,
  530. (string) question_state::$mangrwrong,
  531. (string) question_state::$mangrpartial,
  532. (string) question_state::$mangrright), SQL_PARAMS_NAMED, 'st');
  533. return $this->db->get_records_sql("
  534. SELECT
  535. qa.slot,
  536. AVG(COALESCE(qas.fraction, 0)) AS averagefraction,
  537. COUNT(1) AS numaveraged
  538. FROM {$qubaids->from_question_attempts('qa')}
  539. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  540. AND qas.sequencenumber = {$this->latest_step_for_qa_subquery()}
  541. WHERE
  542. {$qubaids->where()}
  543. $slotwhere
  544. AND qas.state $statetest
  545. GROUP BY qa.slot
  546. ORDER BY qa.slot
  547. ", $slotsparams + $stateparams + $qubaids->from_where_params());
  548. }
  549. /**
  550. * Load a {@link question_attempt} from the database, including all its
  551. * steps.
  552. * @param int $questionid the question to load all the attempts fors.
  553. * @param qubaid_condition $qubaids used to restrict which usages are included
  554. * in the query. See {@link qubaid_condition}.
  555. * @return array of question_attempts.
  556. */
  557. public function load_attempts_at_question($questionid, qubaid_condition $qubaids) {
  558. $params = $qubaids->from_where_params();
  559. $params['questionid'] = $questionid;
  560. $records = $this->db->get_recordset_sql("
  561. SELECT
  562. quba.contextid,
  563. quba.preferredbehaviour,
  564. qa.id AS questionattemptid,
  565. qa.questionusageid,
  566. qa.slot,
  567. qa.behaviour,
  568. qa.questionid,
  569. qa.variant,
  570. qa.maxmark,
  571. qa.minfraction,
  572. qa.maxfraction,
  573. qa.flagged,
  574. qa.questionsummary,
  575. qa.rightanswer,
  576. qa.responsesummary,
  577. qa.timemodified,
  578. qas.id AS attemptstepid,
  579. qas.sequencenumber,
  580. qas.state,
  581. qas.fraction,
  582. qas.timecreated,
  583. qas.userid,
  584. qasd.name,
  585. qasd.value
  586. FROM {$qubaids->from_question_attempts('qa')}
  587. JOIN {question_usages} quba ON quba.id = qa.questionusageid
  588. LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  589. LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
  590. WHERE
  591. {$qubaids->where()} AND
  592. qa.questionid = :questionid
  593. ORDER BY
  594. quba.id,
  595. qa.id,
  596. qas.sequencenumber
  597. ", $params);
  598. $questionattempts = array();
  599. while ($records->valid()) {
  600. $record = $records->current();
  601. $questionattempts[$record->questionattemptid] =
  602. question_attempt::load_from_records($records,
  603. $record->questionattemptid, new question_usage_null_observer(),
  604. $record->preferredbehaviour);
  605. }
  606. $records->close();
  607. return $questionattempts;
  608. }
  609. /**
  610. * Update a question_usages row to refect any changes in a usage (but not
  611. * any of its question_attempts.
  612. * @param question_usage_by_activity $quba the usage that has changed.
  613. */
  614. public function update_questions_usage_by_activity(question_usage_by_activity $quba) {
  615. $record = new stdClass();
  616. $record->id = $quba->get_id();
  617. $record->contextid = $quba->get_owning_context()->id;
  618. $record->component = $quba->get_owning_component();
  619. $record->preferredbehaviour = $quba->get_preferred_behaviour();
  620. $this->db->update_record('question_usages', $record);
  621. }
  622. /**
  623. * Update a question_attempts row to refect any changes in a question_attempt
  624. * (but not any of its steps).
  625. * @param question_attempt $qa the question attempt that has changed.
  626. */
  627. public function update_question_attempt(question_attempt $qa) {
  628. $record = new stdClass();
  629. $record->id = $qa->get_database_id();
  630. $record->maxmark = $qa->get_max_mark();
  631. $record->minfraction = $qa->get_min_fraction();
  632. $record->maxfraction = $qa->get_max_fraction();
  633. $record->flagged = $qa->is_flagged();
  634. $record->questionsummary = $qa->get_question_summary();
  635. $record->rightanswer = $qa->get_right_answer_summary();
  636. $record->responsesummary = $qa->get_response_summary();
  637. $record->timemodified = time();
  638. $this->db->update_record('question_attempts', $record);
  639. }
  640. /**
  641. * Delete a question_usage_by_activity and all its associated
  642. * {@link question_attempts} and {@link question_attempt_steps} from the
  643. * database.
  644. * @param qubaid_condition $qubaids identifies which question useages to delete.
  645. */
  646. public function delete_questions_usage_by_activities(qubaid_condition $qubaids) {
  647. $where = "qa.questionusageid {$qubaids->usage_id_in()}";
  648. $params = $qubaids->usage_id_in_params();
  649. $contextids = $this->db->get_records_sql_menu("
  650. SELECT DISTINCT contextid, 1
  651. FROM {question_usages}
  652. WHERE id {$qubaids->usage_id_in()}", $qubaids->usage_id_in_params());
  653. foreach ($contextids as $contextid => $notused) {
  654. $this->delete_response_files($contextid, "IN (
  655. SELECT qas.id
  656. FROM {question_attempts} qa
  657. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  658. WHERE $where)", $params);
  659. }
  660. if ($this->db->get_dbfamily() == 'mysql') {
  661. $this->delete_usage_records_for_mysql($qubaids);
  662. return;
  663. }
  664. $this->db->delete_records_select('question_attempt_step_data', "attemptstepid IN (
  665. SELECT qas.id
  666. FROM {question_attempts} qa
  667. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  668. WHERE $where)", $params);
  669. $this->db->delete_records_select('question_attempt_steps', "questionattemptid IN (
  670. SELECT qa.id
  671. FROM {question_attempts} qa
  672. WHERE $where)", $params);
  673. $this->db->delete_records_select('question_attempts',
  674. "{question_attempts}.questionusageid {$qubaids->usage_id_in()}",
  675. $qubaids->usage_id_in_params());
  676. $this->db->delete_records_select('question_usages',
  677. "{question_usages}.id {$qubaids->usage_id_in()}", $qubaids->usage_id_in_params());
  678. }
  679. /**
  680. * This function is a work-around for poor MySQL performance with
  681. * DELETE FROM x WHERE id IN (SELECT ...). We have to use a non-standard
  682. * syntax to get good performance. See MDL-29520.
  683. * @param qubaid_condition $qubaids identifies which question useages to delete.
  684. */
  685. protected function delete_usage_records_for_mysql(qubaid_condition $qubaids) {
  686. $qubaidtest = $qubaids->usage_id_in();
  687. if (strpos($qubaidtest, 'question_usages') !== false &&
  688. strpos($qubaidtest, 'IN (SELECT') === 0) {
  689. // This horrible hack is required by MDL-29847. It comes from
  690. // http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/
  691. $qubaidtest = 'IN (SELECT * FROM ' . substr($qubaidtest, 3) . ' AS hack_subquery_alias)';
  692. }
  693. // TODO once MDL-29589 is fixed, eliminate this method, and instead use the new $DB API.
  694. $this->db->execute('
  695. DELETE qu, qa, qas, qasd
  696. FROM {question_usages} qu
  697. JOIN {question_attempts} qa ON qa.questionusageid = qu.id
  698. LEFT JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  699. LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id
  700. WHERE qu.id ' . $qubaidtest,
  701. $qubaids->usage_id_in_params());
  702. }
  703. /**
  704. * Delete all the steps for a question attempt.
  705. * @param int $qaids question_attempt id.
  706. * @param context $context the context that the $quba belongs to.
  707. */
  708. public function delete_steps($stepids, $context) {
  709. if (empty($stepids)) {
  710. return;
  711. }
  712. list($test, $params) = $this->db->get_in_or_equal($stepids, SQL_PARAMS_NAMED);
  713. $this->delete_response_files($context->id, $test, $params);
  714. $this->db->delete_records_select('question_attempt_step_data',
  715. "attemptstepid $test", $params);
  716. $this->db->delete_records_select('question_attempt_steps',
  717. "id $test", $params);
  718. }
  719. /**
  720. * Delete all the files belonging to the response variables in the gives
  721. * question attempt steps.
  722. * @param int $contextid the context these attempts belong to.
  723. * @param string $itemidstest a bit of SQL that can be used in a
  724. * WHERE itemid $itemidstest clause. Must use named params.
  725. * @param array $params any query parameters used in $itemidstest.
  726. */
  727. protected function delete_response_files($contextid, $itemidstest, $params) {
  728. $fs = get_file_storage();
  729. foreach (question_engine::get_all_response_file_areas() as $filearea) {
  730. $fs->delete_area_files_select($contextid, 'question', $filearea,
  731. $itemidstest, $params);
  732. }
  733. }
  734. /**
  735. * Delete all the previews for a given question.
  736. * @param int $questionid question id.
  737. */
  738. public function delete_previews($questionid) {
  739. $previews = $this->db->get_records_sql_menu("
  740. SELECT DISTINCT quba.id, 1
  741. FROM {question_usages} quba
  742. JOIN {question_attempts} qa ON qa.questionusageid = quba.id
  743. WHERE quba.component = 'core_question_preview' AND
  744. qa.questionid = ?", array($questionid));
  745. if (empty($previews)) {
  746. return;
  747. }
  748. $this->delete_questions_usage_by_activities(new qubaid_list($previews));
  749. }
  750. /**
  751. * Update the flagged state of a question in the database.
  752. * @param int $qubaid the question usage id.
  753. * @param int $questionid the question id.
  754. * @param int $sessionid the question_attempt id.
  755. * @param bool $newstate the new state of the flag. true = flagged.
  756. */
  757. public function update_question_attempt_flag($qubaid, $questionid, $qaid, $slot, $newstate) {
  758. if (!$this->db->record_exists('question_attempts', array('id' => $qaid,
  759. 'questionusageid' => $qubaid, 'questionid' => $questionid, 'slot' => $slot))) {
  760. throw new moodle_exception('errorsavingflags', 'question');
  761. }
  762. $this->db->set_field('question_attempts', 'flagged', $newstate, array('id' => $qaid));
  763. }
  764. /**
  765. * Get all the WHEN 'x' THEN 'y' terms needed to convert the question_attempt_steps.state
  766. * column to a summary state. Use this like
  767. * CASE qas.state {$this->full_states_to_summary_state_sql()} END AS summarystate,
  768. * @param string SQL fragment.
  769. */
  770. protected function full_states_to_summary_state_sql() {
  771. $sql = '';
  772. foreach (question_state::get_all() as $state) {
  773. $sql .= "WHEN '$state' THEN '{$state->get_summary_state()}'\n";
  774. }
  775. return $sql;
  776. }
  777. /**
  778. * Get the SQL needed to test that question_attempt_steps.state is in a
  779. * state corresponding to $summarystate.
  780. * @param string $summarystate one of
  781. * inprogress, needsgrading, manuallygraded or autograded
  782. * @param bool $equal if false, do a NOT IN test. Default true.
  783. * @return string SQL fragment.
  784. */
  785. public function in_summary_state_test($summarystate, $equal = true, $prefix = 'summarystates') {
  786. $states = question_state::get_all_for_summary_state($summarystate);
  787. return $this->db->get_in_or_equal(array_map('strval', $states),
  788. SQL_PARAMS_NAMED, $prefix, $equal);
  789. }
  790. /**
  791. * Change the maxmark for the question_attempt with number in usage $slot
  792. * for all the specified question_attempts.
  793. * @param qubaid_condition $qubaids Selects which usages are updated.
  794. * @param int $slot the number is usage to affect.
  795. * @param number $newmaxmark the new max mark to set.
  796. */
  797. public function set_max_mark_in_attempts(qubaid_condition $qubaids, $slot, $newmaxmark) {
  798. $this->db->set_field_select('question_attempts', 'maxmark', $newmaxmark,
  799. "questionusageid {$qubaids->usage_id_in()} AND slot = :slot",
  800. $qubaids->usage_id_in_params() + array('slot' => $slot));
  801. }
  802. /**
  803. * Return a subquery that computes the sum of the marks for all the questions
  804. * in a usage. Which useage to compute the sum for is controlled bu the $qubaid
  805. * parameter.
  806. *
  807. * See {@link quiz_update_all_attempt_sumgrades()} for an example of the usage of
  808. * this method.
  809. *
  810. * @param string $qubaid SQL fragment that controls which usage is summed.
  811. * This will normally be the name of a column in the outer query. Not that this
  812. * SQL fragment must not contain any placeholders.
  813. * @return string SQL code for the subquery.
  814. */
  815. public function sum_usage_marks_subquery($qubaid) {
  816. // To explain the COALESCE in the following SQL: SUM(lots of NULLs) gives
  817. // NULL, while SUM(one 0.0 and lots of NULLS) gives 0.0. We don't want that.
  818. // We always want to return a number, so the COALESCE is there to turn the
  819. // NULL total into a 0.
  820. return "SELECT COALESCE(SUM(qa.maxmark * qas.fraction), 0)
  821. FROM {question_attempts} qa
  822. JOIN {question_attempt_steps} qas ON qas.questionattemptid = qa.id
  823. AND qas.sequencenumber = (
  824. SELECT MAX(summarks_qas.sequencenumber)
  825. FROM {question_attempt_steps} summarks_qas
  826. WHERE summarks_qas.questionattemptid = qa.id
  827. )
  828. WHERE qa.questionusageid = $qubaid
  829. HAVING COUNT(CASE
  830. WHEN qas.state = 'needsgrading' AND qa.maxmark > 0 THEN 1
  831. ELSE NULL
  832. END) = 0";
  833. }
  834. /**
  835. * Get a subquery that returns the latest step of every qa in some qubas.
  836. * Currently, this is only used by the quiz reports. See
  837. * {@link quiz_attempts_report_table::add_latest_state_join()}.
  838. * @param string $alias alias to use for this inline-view.
  839. * @param qubaid_condition $qubaids restriction on which question_usages we
  840. * are interested in. This is important for performance.
  841. * @return array with two elements, the SQL fragment and any params requried.
  842. */
  843. public function question_attempt_latest_state_view($alias, qubaid_condition $qubaids) {
  844. return array("(
  845. SELECT {$alias}qa.id AS questionattemptid,
  846. {$alias}qa.questionusageid,
  847. {$alias}qa.slot,
  848. {$alias}qa.behaviour,
  849. {$alias}qa.questionid,
  850. {$alias}qa.variant,
  851. {$alias}qa.maxmark,
  852. {$alias}qa.minfraction,
  853. {$alias}qa.maxfraction,
  854. {$alias}qa.flagged,
  855. {$alias}qa.questionsummary,
  856. {$alias}qa.rightanswer,
  857. {$alias}qa.responsesummary,
  858. {$alias}qa.timemodified,
  859. {$alias}qas.id AS attemptstepid,
  860. {$alias}qas.sequencenumber,
  861. {$alias}qas.state,
  862. {$alias}qas.fraction,
  863. {$alias}qas.timecreated,
  864. {$alias}qas.userid
  865. FROM {$qubaids->from_question_attempts($alias . 'qa')}
  866. JOIN {question_attempt_steps} {$alias}qas ON {$alias}qas.questionattemptid = {$alias}qa.id
  867. AND {$alias}qas.sequencenumber = {$this->latest_step_for_qa_subquery($alias . 'qa.id')}
  868. WHERE {$qubaids->where()}
  869. ) $alias", $qubaids->from_where_params());
  870. }
  871. protected function latest_step_for_qa_subquery($questionattemptid = 'qa.id') {
  872. return "(
  873. SELECT MAX(sequencenumber)
  874. FROM {question_attempt_steps}
  875. WHERE questionattemptid = $questionattemptid
  876. )";
  877. }
  878. /**
  879. * @param array $questionids of question ids.
  880. * @param qubaid_condition $qubaids ids of the usages to consider.
  881. * @return boolean whether any of these questions are being used by any of
  882. * those usages.
  883. */
  884. public function questions_in_use(array $questionids, qubaid_condition $qubaids) {
  885. list($test, $params) = $this->db->get_in_or_equal($questionids);
  886. return $this->db->record_exists_select('question_attempts',
  887. 'questionid ' . $test . ' AND questionusageid ' .
  888. $qubaids->usage_id_in(), $params + $qubaids->usage_id_in_params());
  889. }
  890. }
  891. /**
  892. * Implementation of the unit of work pattern for the question engine.
  893. *
  894. * See http://martinfowler.com/eaaCatalog/unitOfWork.html. This tracks all the
  895. * changes to a {@link question_usage_by_activity}, and its constituent parts,
  896. * so that the changes can be saved to the database when {@link save()} is called.
  897. *
  898. * @copyright 2009 The Open University
  899. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  900. */
  901. class question_engine_unit_of_work implements question_usage_observer {
  902. /** @var question_usage_by_activity the usage being tracked. */
  903. protected $quba;
  904. /** @var boolean whether any of the fields of the usage have been changed. */
  905. protected $modified = false;
  906. /**
  907. * @var array list of slot => {@link question_attempt}s that
  908. * were already in the usage, and which have been modified.
  909. */
  910. protected $attemptsmodified = array();
  911. /**
  912. * @var array list of slot => {@link question_attempt}s that
  913. * have been added to the usage.
  914. */
  915. protected $attemptsadded = array();
  916. /**
  917. * @var array of array(question_attempt_step, question_attempt id, seq number)
  918. * of steps that have been added to question attempts in this usage.
  919. */
  920. protected $stepsadded = array();
  921. /**
  922. * @var array of array(question_attempt_step, question_attempt id, seq number)
  923. * of steps that have been modified in their attempt.
  924. */
  925. protected $stepsmodified = array();
  926. /**
  927. * @var array list of question_attempt_step.id => question_attempt_step of steps
  928. * that were previously stored in the database, but which are no longer required.
  929. */
  930. protected $stepsdeleted = array();
  931. /**
  932. * Constructor.
  933. * @param question_usage_by_activity $quba the usage to track.
  934. */
  935. public function __construct(question_usage_by_activity $quba) {
  936. $this->quba = $quba;
  937. }
  938. public function notify_modified() {
  939. $this->modified = true;
  940. }
  941. public function notify_attempt_modified(question_attempt $qa) {
  942. $slot = $qa->get_slot();
  943. if (!array_key_exists($slot, $this->attemptsadded)) {
  944. $this->attemptsmodified[$slot] = $qa;
  945. }
  946. }
  947. public function notify_attempt_added(question_attempt $qa) {
  948. $this->attemptsadded[$qa->get_slot()] = $qa;
  949. }
  950. public function notify_step_added(question_attempt_step $step, question_attempt $qa, $seq) {
  951. if (array_key_exists($qa->get_slot(), $this->attemptsadded)) {
  952. return;
  953. }
  954. if (($key = $this->is_step_added($step)) !== false) {
  955. return;
  956. }
  957. if (($key = $this->is_step_modified($step)) !== false) {
  958. throw new coding_exception('Cannot add a step that has already been modified.');
  959. }
  960. if (($key = $this->is_step_deleted($step)) !== false) {
  961. unset($this->stepsdeleted[$step->get_id()]);
  962. $this->stepsmodified[] = array($step, $qa->get_database_id(), $seq);
  963. return;
  964. }
  965. $stepid = $step->get_id();
  966. if ($stepid) {
  967. if (array_key_exists($stepid, $this->stepsdeleted)) {
  968. unset($this->stepsdeleted[$stepid]);
  969. }
  970. $this->stepsmodified[] = array($step, $qa->get_database_id(), $seq);
  971. } else {
  972. $this->stepsadded[] = array($step, $qa->get_database_id(), $seq);
  973. }
  974. }
  975. public function notify_step_modified(question_attempt_step $step, question_attempt $qa, $seq) {
  976. if (array_key_exists($qa->get_slot(), $this->attemptsadded)) {
  977. return;
  978. }
  979. if (($key = $this->is_step_added($step)) !== false) {
  980. return;
  981. }
  982. if (($key = $this->is_step_deleted($step)) !== false) {
  983. throw new coding_exception('Cannot modify a step after it has been deleted.');
  984. }
  985. $stepid = $step->get_id();
  986. if (empty($stepid)) {
  987. throw new coding_exception('Cannot modify a step that has never been stored in the database.');
  988. }
  989. $this->stepsmodified[] = array($step, $qa->get_database_id(), $seq);
  990. }
  991. public function notify_step_deleted(question_attempt_step $step, question_attempt $qa) {
  992. if (array_key_exists($qa->get_slot(), $this->attemptsadded)) {
  993. return;
  994. }
  995. if (($key = $this->is_step_added($step)) !== false) {
  996. unset($this->stepsadded[$key]);
  997. return;
  998. }
  999. if (($key = $this->is_step_modified($step)) !== false) {
  1000. unset($this->stepsmodified[$key]);
  1001. }
  1002. $stepid = $step->get_id();
  1003. if (empty($stepid)) {
  1004. return; // Was never in the database.
  1005. }
  1006. $this->stepsdeleted[$stepid] = $step;
  1007. }
  1008. /**
  1009. * @param question_attempt_step $step a step
  1010. * @return int|false if the step is in the list of steps to be added, return
  1011. * the key, otherwise return false.
  1012. */
  1013. protected function is_step_added(question_attempt_step $step) {
  1014. foreach ($this->stepsadded as $key => $data) {
  1015. list($addedstep, $qaid, $seq) = $data;
  1016. if ($addedstep === $step) {
  1017. return $key;
  1018. }
  1019. }
  1020. return false;
  1021. }
  1022. /**
  1023. * @param question_attempt_step $step a step
  1024. * @return int|false if the step is in the list of steps to be modified, return
  1025. * the key, otherwise return false.
  1026. */
  1027. protected function is_step_modified(question_attempt_step $step) {
  1028. foreach ($this->stepsmodified as $key => $data) {
  1029. list($modifiedstep, $qaid, $seq) = $data;
  1030. if ($modifiedstep === $step) {
  1031. return $key;
  1032. }
  1033. }
  1034. return false;
  1035. }
  1036. /**
  1037. * @param question_attempt_step $step a step
  1038. * @return bool whether the step is in the list of steps to be deleted.
  1039. */
  1040. protected function is_step_deleted(question_attempt_step $step) {
  1041. foreach ($this->stepsdeleted as $deletedstep) {
  1042. if ($deletedstep === $step) {
  1043. return true;
  1044. }
  1045. }
  1046. return false;
  1047. }
  1048. /**
  1049. * Write all the changes we have recorded to the database.
  1050. * @param question_engine_data_mapper $dm the mapper to use to update the database.
  1051. */
  1052. public function save(question_engine_data_mapper $dm) {
  1053. $dm->delete_steps(array_keys($this->stepsdeleted), $this->quba->get_owning_context());
  1054. foreach ($this->stepsmodified as $stepinfo) {
  1055. list($step, $questionattemptid, $seq) = $stepinfo;
  1056. $dm->update_question_attempt_step($step, $questionattemptid, $seq,
  1057. $this->quba->get_owning_context());
  1058. }
  1059. foreach ($this->stepsadded as $stepinfo) {
  1060. list($step, $questionattemptid, $seq) = $stepinfo;
  1061. $dm->insert_question_attempt_step($step, $questionattemptid, $seq,
  1062. $this->quba->get_owning_context());
  1063. }
  1064. foreach ($this->attemptsadded as $qa) {
  1065. $dm->insert_question_attempt($qa, $this->quba->get_owning_context());
  1066. }
  1067. foreach ($this->attemptsmodified as $qa) {
  1068. $dm->update_question_attempt($qa);
  1069. }
  1070. if ($this->modified) {
  1071. $dm->update_questions_usage_by_activity($this->quba);
  1072. }
  1073. }
  1074. }
  1075. /**
  1076. * The interface implemented by {@link question_file_saver} and {@link question_file_loader}.
  1077. *
  1078. * @copyright 2012 The Open University
  1079. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1080. */
  1081. interface question_response_files {
  1082. /**
  1083. * Get the files that were submitted.
  1084. * @return array of stored_files objects.
  1085. */
  1086. public function get_files();
  1087. }
  1088. /**
  1089. * This class represents the promise to save some files from a particular draft
  1090. * file area into a particular file area. It is used beause the necessary
  1091. * information about what to save is to hand in the
  1092. * {@link question_attempt::process_response_files()} method, but we don't know
  1093. * if this question attempt will actually be saved in the database until later,
  1094. * when the {@link question_engine_unit_of_work} is saved, if it is.
  1095. *
  1096. * @copyright 2011 The Open University
  1097. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1098. */
  1099. class question_file_saver implements question_response_files {
  1100. /** @var int the id of the draft file area to save files from. */
  1101. protected $draftitemid;
  1102. /** @var string the owning component name. */
  1103. protected $component;
  1104. /** @var string the file area name. */
  1105. protected $filearea;
  1106. /**
  1107. * @var string the value to store in the question_attempt_step_data to
  1108. * represent these files.
  1109. */
  1110. protected $value = null;
  1111. /**
  1112. * Constuctor.
  1113. * @param int $draftitemid the draft area to save the files from.
  1114. * @param string $component the component for the file area to save into.
  1115. * @param string $filearea the name of the file area to save into.
  1116. */
  1117. public function __construct($draftitemid, $component, $filearea, $text = null) {
  1118. $this->draftitemid = $draftitemid;
  1119. $this->component = $component;
  1120. $this->filearea = $filearea;
  1121. $this->value = $this->compute_value($draftitemid, $text);
  1122. }
  1123. /**
  1124. * Compute the value that should be stored in the question_attempt_step_data
  1125. * table. Contains a hash that (almost) uniquely encodes all the files.
  1126. * @param int $draftitemid the draft file area itemid.
  1127. * @param string $text optional content containing file links.
  1128. */
  1129. protected function compute_value($draftitemid, $text) {
  1130. global $USER;
  1131. $fs = get_file_storage();
  1132. $usercontext = context_user::instance($USER->id);
  1133. $files = $fs->get_area_files($usercontext->id, 'user', 'draft',
  1134. $draftitemid, 'sortorder, filepath, filename', false);
  1135. $string = '';
  1136. foreach ($files as $file) {
  1137. $string .= $file->get_filepath() . $file->get_filename() . '|' .
  1138. $file->get_contenthash() . '|';
  1139. }
  1140. $hash = md5($string);
  1141. if (is_null($text)) {
  1142. if ($string) {
  1143. return $hash;
  1144. } else {
  1145. return '';
  1146. }
  1147. }
  1148. // We add the file hash so a simple string comparison will say if the
  1149. // files have been changed. First strip off any existing file hash.
  1150. if ($text !== '') {
  1151. $text = preg_replace('/\s*<!-- File hash: \w+ -->\s*$/', '', $text);
  1152. $text = file_rewrite_urls_to_pluginfile($text, $draftitemid);
  1153. if ($string) {
  1154. $text .= '<!-- File hash: ' . $hash . ' -->';
  1155. }
  1156. }
  1157. return $text;
  1158. }
  1159. public function __toString() {
  1160. return $this->value;
  1161. }
  1162. /**
  1163. * Actually save the files.
  1164. * @param integer $itemid the item id for the file area to save into.
  1165. */
  1166. public function save_files($itemid, $context) {
  1167. file_save_draft_area_files($this->draftitemid, $context->id,
  1168. $this->component, $this->filearea, $itemid);
  1169. }
  1170. /**
  1171. * Get the files that were submitted.

Large files files are truncated, but you can click here to view the full file