MDL-10109 fixed aggregate outcomes depends_on() incorrect condition
[moodle.git] / lib / questionlib.php
CommitLineData
516cf3eb 1<?php // $Id$
2/**
6b11a0e8 3 * Code for handling and processing questions
4 *
5 * This is code that is module independent, i.e., can be used by any module that
6 * uses questions, like quiz, lesson, ..
7 * This script also loads the questiontype classes
8 * Code for handling the editing of questions is in {@link question/editlib.php}
9 *
10 * TODO: separate those functions which form part of the API
11 * from the helper functions.
12 *
6b11a0e8 13 * @author Martin Dougiamas and many others. This has recently been completely
14 * rewritten by Alex Smith, Julian Sedding and Gustav Delius as part of
15 * the Serving Mathematics project
16 * {@link http://maths.york.ac.uk/serving_maths}
17 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
18 * @package question
19 */
20
21/// CONSTANTS ///////////////////////////////////
516cf3eb 22
e56a08dc 23/**#@+
6b11a0e8 24 * The different types of events that can create question states
25 */
f30bbcaf 26define('QUESTION_EVENTOPEN', '0'); // The state was created by Moodle
27define('QUESTION_EVENTNAVIGATE', '1'); // The responses were saved because the student navigated to another page (this is not currently used)
28define('QUESTION_EVENTSAVE', '2'); // The student has requested that the responses should be saved but not submitted or validated
29define('QUESTION_EVENTGRADE', '3'); // Moodle has graded the responses. A SUBMIT event can be changed to a GRADE event by Moodle.
30define('QUESTION_EVENTDUPLICATE', '4'); // The responses submitted were the same as previously
31define('QUESTION_EVENTVALIDATE', '5'); // The student has requested a validation. This causes the responses to be saved as well, but not graded.
32define('QUESTION_EVENTCLOSEANDGRADE', '6'); // Moodle has graded the responses. A CLOSE event can be changed to a CLOSEANDGRADE event by Moodle.
33define('QUESTION_EVENTSUBMIT', '7'); // The student response has been submitted but it has not yet been marked
34define('QUESTION_EVENTCLOSE', '8'); // The response has been submitted and the session has been closed, either because the student requested it or because Moodle did it (e.g. because of a timelimit). The responses have not been graded.
bc2feba3 35define('QUESTION_EVENTMANUALGRADE', '9'); // Grade was entered by teacher
e56a08dc 36/**#@-*/
37
38/**#@+
a2156789 39 * The core question types.
6b11a0e8 40 */
60407982 41define("SHORTANSWER", "shortanswer");
42define("TRUEFALSE", "truefalse");
43define("MULTICHOICE", "multichoice");
44define("RANDOM", "random");
45define("MATCH", "match");
46define("RANDOMSAMATCH", "randomsamatch");
47define("DESCRIPTION", "description");
48define("NUMERICAL", "numerical");
49define("MULTIANSWER", "multianswer");
50define("CALCULATED", "calculated");
60407982 51define("ESSAY", "essay");
e56a08dc 52/**#@-*/
53
6b11a0e8 54/**
55 * Constant determines the number of answer boxes supplied in the editing
56 * form for multiple choice and similar question types.
57 */
4f48fb42 58define("QUESTION_NUMANS", "10");
e56a08dc 59
271ffe3f 60/**
61 * Constant determines the number of answer boxes supplied in the editing
62 * form for multiple choice and similar question types to start with, with
63 * the option of adding QUESTION_NUMANS_ADD more answers.
64 */
65define("QUESTION_NUMANS_START", 3);
66
67/**
68 * Constant determines the number of answer boxes to add in the editing
69 * form for multiple choice and similar question types when the user presses
70 * 'add form fields button'.
71 */
72define("QUESTION_NUMANS_ADD", 3);
73
1b8a7434 74/**
75 * The options used when popping up a question preview window in Javascript.
76 */
7d87171b 77define('QUESTION_PREVIEW_POPUP_OPTIONS', 'scrollbars=yes,resizable=yes,width=700,height=540');
516cf3eb 78
6b11a0e8 79/**#@+
80 * Option flags for ->optionflags
81 * The options are read out via bitwise operation using these constants
82 */
83/**
84 * Whether the questions is to be run in adaptive mode. If this is not set then
85 * a question closes immediately after the first submission of responses. This
86 * is how question is Moodle always worked before version 1.5
87 */
88define('QUESTION_ADAPTIVE', 1);
89
6b11a0e8 90/**#@-*/
91
f02c6f01 92/// QTYPES INITIATION //////////////////
a2156789 93// These variables get initialised via calls to question_register_questiontype
94// as the question type classes are included.
95global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
516cf3eb 96/**
6b11a0e8 97 * Array holding question type objects
98 */
a2156789 99$QTYPES = array();
ccccf04f 100/**
6b11a0e8 101 * Array of question types names translated to the user's language
102 *
103 * The $QTYPE_MENU array holds the names of all the question types that the user should
104 * be able to create directly. Some internal question types like random questions are excluded.
105 * The complete list of question types can be found in {@link $QTYPES}.
106 */
a2156789 107$QTYPE_MENU = array();
108/**
109 * String in the format "'type1','type2'" that can be used in SQL clauses like
110 * "WHERE q.type IN ($QTYPE_MANUAL)".
111 */
271ffe3f 112$QTYPE_MANUAL = '';
a2156789 113/**
114 * String in the format "'type1','type2'" that can be used in SQL clauses like
115 * "WHERE q.type NOT IN ($QTYPE_EXCLUDE_FROM_RANDOM)".
116 */
117$QTYPE_EXCLUDE_FROM_RANDOM = '';
118
119/**
120 * Add a new question type to the various global arrays above.
271ffe3f 121 *
a2156789 122 * @param object $qtype An instance of the new question type class.
123 */
124function question_register_questiontype($qtype) {
125 global $QTYPES, $QTYPE_MENU, $QTYPE_MANUAL, $QTYPE_EXCLUDE_FROM_RANDOM;
271ffe3f 126
a2156789 127 $name = $qtype->name();
128 $QTYPES[$name] = $qtype;
129 $menuname = $qtype->menu_name();
130 if ($menuname) {
131 $QTYPE_MENU[$name] = $menuname;
132 }
133 if ($qtype->is_manual_graded()) {
134 if ($QTYPE_MANUAL) {
135 $QTYPE_MANUAL .= ',';
136 }
137 $QTYPE_MANUAL .= "'$name'";
138 }
139 if (!$qtype->is_usable_by_random()) {
140 if ($QTYPE_EXCLUDE_FROM_RANDOM) {
141 $QTYPE_EXCLUDE_FROM_RANDOM .= ',';
142 }
143 $QTYPE_EXCLUDE_FROM_RANDOM .= "'$name'";
144 }
145}
516cf3eb 146
643ec47d 147require_once("$CFG->dirroot/question/type/questiontype.php");
516cf3eb 148
a2156789 149// Load the questiontype.php file for each question type
271ffe3f 150// These files in turn call question_register_questiontype()
a2156789 151// with a new instance of each qtype class.
aaae75b0 152$qtypenames= get_list_of_plugins('question/type');
f02c6f01 153foreach($qtypenames as $qtypename) {
154 // Instanciates all plug-in question types
643ec47d 155 $qtypefilepath= "$CFG->dirroot/question/type/$qtypename/questiontype.php";
f02c6f01 156
157 // echo "Loading $qtypename<br/>"; // Uncomment for debugging
158 if (is_readable($qtypefilepath)) {
159 require_once($qtypefilepath);
516cf3eb 160 }
161}
162
163/// OTHER CLASSES /////////////////////////////////////////////////////////
164
165/**
6b11a0e8 166 * This holds the options that are set by the course module
167 */
516cf3eb 168class cmoptions {
169 /**
170 * Whether a new attempt should be based on the previous one. If true
171 * then a new attempt will start in a state where all responses are set
172 * to the last responses from the previous attempt.
173 */
174 var $attemptonlast = false;
175
176 /**
177 * Various option flags. The flags are accessed via bitwise operations
178 * using the constants defined in the CONSTANTS section above.
179 */
6b11a0e8 180 var $optionflags = QUESTION_ADAPTIVE;
516cf3eb 181
182 /**
183 * Determines whether in the calculation of the score for a question
184 * penalties for earlier wrong responses within the same attempt will
185 * be subtracted.
186 */
187 var $penaltyscheme = true;
188
189 /**
190 * The maximum time the user is allowed to answer the questions withing
191 * an attempt. This is measured in minutes so needs to be multiplied by
192 * 60 before compared to timestamps. If set to 0 no timelimit will be applied
193 */
194 var $timelimit = 0;
195
196 /**
197 * Timestamp for the closing time. Responses submitted after this time will
198 * be saved but no credit will be given for them.
199 */
200 var $timeclose = 9999999999;
201
202 /**
203 * The id of the course from withing which the question is currently being used
204 */
205 var $course = SITEID;
206
207 /**
208 * Whether the answers in a multiple choice question should be randomly
209 * shuffled when a new attempt is started.
210 */
c4c11af8 211 var $shuffleanswers = true;
516cf3eb 212
213 /**
214 * The number of decimals to be shown when scores are printed
215 */
216 var $decimalpoints = 2;
516cf3eb 217}
218
219
516cf3eb 220/// FUNCTIONS //////////////////////////////////////////////////////
221
90c3f310 222/**
f67172b6 223 * Returns an array of names of activity modules that use this question
90c3f310 224 *
f67172b6 225 * @param object $questionid
226 * @return array of strings
90c3f310 227 */
f67172b6 228function question_list_instances($questionid) {
90c3f310 229 $instances = array();
230 $modules = get_records('modules');
231 foreach ($modules as $module) {
f67172b6 232 $fn = $module->name.'_question_list_instances';
90c3f310 233 if (function_exists($fn)) {
f67172b6 234 $instances = $instances + $fn($questionid);
90c3f310 235 }
236 }
237 return $instances;
238}
516cf3eb 239
e9de4366 240
271ffe3f 241/**
e9de4366 242 * Returns list of 'allowed' grades for grade selection
243 * formatted suitably for dropdown box function
244 * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
245 */
246function get_grade_options() {
247 // define basic array of grades
248 $grades = array(
249 1,
250 0.9,
251 0.8,
252 0.75,
253 0.70,
254 0.66666,
255 0.60,
256 0.50,
257 0.40,
258 0.33333,
259 0.30,
260 0.25,
261 0.20,
262 0.16666,
263 0.142857,
264 0.125,
265 0.11111,
266 0.10,
267 0.05,
268 0);
269
270 // iterate through grades generating full range of options
271 $gradeoptionsfull = array();
272 $gradeoptions = array();
273 foreach ($grades as $grade) {
274 $percentage = 100 * $grade;
275 $neggrade = -$grade;
276 $gradeoptions["$grade"] = "$percentage %";
277 $gradeoptionsfull["$grade"] = "$percentage %";
278 $gradeoptionsfull["$neggrade"] = -$percentage." %";
279 }
280 $gradeoptionsfull["0"] = $gradeoptions["0"] = get_string("none");
281
282 // sort lists
283 arsort($gradeoptions, SORT_NUMERIC);
284 arsort($gradeoptionsfull, SORT_NUMERIC);
285
286 // construct return object
287 $grades = new stdClass;
288 $grades->gradeoptions = $gradeoptions;
289 $grades->gradeoptionsfull = $gradeoptionsfull;
290
291 return $grades;
292}
293
8511669c 294/**
295 * match grade options
296 * if no match return error or match nearest
297 * @param array $gradeoptionsfull list of valid options
298 * @param int $grade grade to be tested
299 * @param string $matchgrades 'error' or 'nearest'
300 * @return mixed either 'fixed' value or false if erro
301 */
302function match_grade_options($gradeoptionsfull, $grade, $matchgrades='error') {
303 // if we just need an error...
304 if ($matchgrades=='error') {
305 foreach($gradeoptionsfull as $value => $option) {
2784b982 306 // slightly fuzzy test, never check floats for equality :-)
307 if (abs($grade-$value)<0.00001) {
8511669c 308 return $grade;
309 }
310 }
311 // didn't find a match so that's an error
312 return false;
313 }
314 // work out nearest value
315 else if ($matchgrades=='nearest') {
316 $hownear = array();
317 foreach($gradeoptionsfull as $value => $option) {
318 if ($grade==$value) {
319 return $grade;
320 }
321 $hownear[ $value ] = abs( $grade - $value );
322 }
323 // reverse sort list of deltas and grab the last (smallest)
324 asort( $hownear, SORT_NUMERIC );
325 reset( $hownear );
326 return key( $hownear );
327 }
328 else {
329 return false;
271ffe3f 330 }
8511669c 331}
332
f67172b6 333/**
334 * Tests whether a category is in use by any activity module
335 *
336 * @return boolean
271ffe3f 337 * @param integer $categoryid
f67172b6 338 * @param boolean $recursive Whether to examine category children recursively
339 */
340function question_category_isused($categoryid, $recursive = false) {
341
342 //Look at each question in the category
343 if ($questions = get_records('question', 'category', $categoryid)) {
344 foreach ($questions as $question) {
345 if (count(question_list_instances($question->id))) {
346 return true;
347 }
348 }
349 }
350
351 //Look under child categories recursively
352 if ($recursive) {
353 if ($children = get_records('question_categories', 'parent', $categoryid)) {
354 foreach ($children as $child) {
355 if (question_category_isused($child->id, $recursive)) {
356 return true;
357 }
358 }
359 }
360 }
361
362 return false;
363}
364
0429cd86 365/**
366 * Deletes all data associated to an attempt from the database
367 *
93eb0ea3 368 * @param integer $attemptid The id of the attempt being deleted
0429cd86 369 */
370function delete_attempt($attemptid) {
371 global $QTYPES;
372
373 $states = get_records('question_states', 'attempt', $attemptid);
9523cbfc 374 if ($states) {
375 $stateslist = implode(',', array_keys($states));
376
377 // delete question-type specific data
378 foreach ($QTYPES as $qtype) {
379 $qtype->delete_states($stateslist);
380 }
0429cd86 381 }
382
383 // delete entries from all other question tables
384 // It is important that this is done only after calling the questiontype functions
385 delete_records("question_states", "attempt", $attemptid);
386 delete_records("question_sessions", "attemptid", $attemptid);
36be25f6 387 delete_records("question_attempts", "id", $attemptid);
0429cd86 388}
f67172b6 389
516cf3eb 390/**
6b11a0e8 391 * Deletes question and all associated data from the database
392 *
90c3f310 393 * It will not delete a question if it is used by an activity module
6b11a0e8 394 * @param object $question The question being deleted
395 */
90c3f310 396function delete_question($questionid) {
f02c6f01 397 global $QTYPES;
271ffe3f 398
90c3f310 399 // Do not delete a question if it is used by an activity module
f67172b6 400 if (count(question_list_instances($questionid))) {
90c3f310 401 return;
402 }
403
404 // delete questiontype-specific data
cf60a28a 405 if ($question = get_record('question', 'id', $questionid)) {
406 if (isset($QTYPES[$question->qtype])) {
407 $QTYPES[$question->qtype]->delete_question($questionid);
408 }
409 } else {
410 echo "Question with id $questionid does not exist.<br />";
516cf3eb 411 }
90c3f310 412
5cb9076a 413 if ($states = get_records('question_states', 'question', $questionid)) {
414 $stateslist = implode(',', array_keys($states));
271ffe3f 415
5cb9076a 416 // delete questiontype-specific data
417 foreach ($QTYPES as $qtype) {
418 $qtype->delete_states($stateslist);
419 }
0429cd86 420 }
421
90c3f310 422 // delete entries from all other question tables
423 // It is important that this is done only after calling the questiontype functions
424 delete_records("question_answers", "question", $questionid);
425 delete_records("question_states", "question", $questionid);
426 delete_records("question_sessions", "questionid", $questionid);
427
428 // Now recursively delete all child questions
429 if ($children = get_records('question', 'parent', $questionid)) {
516cf3eb 430 foreach ($children as $child) {
1d723a16 431 if ($child->id != $questionid) {
432 delete_question($child->id);
433 }
516cf3eb 434 }
435 }
271ffe3f 436
90c3f310 437 // Finally delete the question record itself
438 delete_records('question', 'id', $questionid);
439
440 return;
516cf3eb 441}
442
f67172b6 443/**
444 * All non-used question categories and their questions are deleted and
445 * categories still used by other courses are moved to the site course.
446 *
447 * @param object $course an object representing the course
448 * @param boolean $feedback to specify if the process must output a summary of its work
449 * @return boolean
450 */
451function question_delete_course($course, $feedback=true) {
452
453 global $CFG, $QTYPES;
454
455 //To detect if we have created the "container category"
456 $concatid = 0;
457
458 //The "container" category we'll create if we need if
459 $contcat = new object;
460
461 //To temporary store changes performed with parents
462 $parentchanged = array();
463
464 //To store feedback to be showed at the end of the process
465 $feedbackdata = array();
466
467 //Cache some strings
468 $strcatcontainer=get_string('containercategorycreated', 'quiz');
469 $strcatmoved = get_string('usedcategorymoved', 'quiz');
470 $strcatdeleted = get_string('unusedcategorydeleted', 'quiz');
471
472 if ($categories = get_records('question_categories', 'course', $course->id, 'parent', 'id, parent, name, course')) {
473
474 //Sort categories following their tree (parent-child) relationships
475 $categories = sort_categories_by_tree($categories);
476
477 foreach ($categories as $cat) {
478
479 //Get the full record
480 $category = get_record('question_categories', 'id', $cat->id);
481
482 //Check if the category is being used anywhere
483 if(question_category_isused($category->id, true)) {
484 //It's being used. Cannot delete it, so:
485 //Create a container category in SITEID course if it doesn't exist
486 if (!$concatid) {
d7444d44 487 $concat = new stdClass;
f67172b6 488 $concat->course = SITEID;
489 if (!isset($course->shortname)) {
490 $course->shortname = 'id=' . $course->id;
491 }
6ba65fa0 492 $concat->name = get_string('savedfromdeletedcourse', 'quiz', format_string($course->shortname));
f67172b6 493 $concat->info = $concat->name;
494 $concat->publish = 1;
495 $concat->stamp = make_unique_id_code();
496 $concatid = insert_record('question_categories', $concat);
497
498 //Fill feedback
499 $feedbackdata[] = array($concat->name, $strcatcontainer);
500 }
501 //Move the category to the container category in SITEID course
502 $category->course = SITEID;
503 //Assign to container if the category hasn't parent or if the parent is wrong (not belongs to the course)
504 if (!$category->parent || !isset($categories[$category->parent])) {
505 $category->parent = $concatid;
506 }
507 //If it's being used, its publish field should be 1
508 $category->publish = 1;
509 //Let's update it
510 update_record('question_categories', $category);
511
512 //Save this parent change for future use
513 $parentchanged[$category->id] = $category->parent;
514
515 //Fill feedback
516 $feedbackdata[] = array($category->name, $strcatmoved);
517
518 } else {
519 //Category isn't being used so:
520 //Delete it completely (questions and category itself)
521 //deleting questions
522 if ($questions = get_records("question", "category", $category->id)) {
523 foreach ($questions as $question) {
524 delete_question($question->id);
525 }
526 delete_records("question", "category", $category->id);
527 }
528 //delete the category
529 delete_records('question_categories', 'id', $category->id);
530
531 //Save this parent change for future use
532 if (!empty($category->parent)) {
533 $parentchanged[$category->id] = $category->parent;
534 } else {
535 $parentchanged[$category->id] = $concatid;
536 }
537
538 //Update all its child categories to re-parent them to grandparent.
539 set_field ('question_categories', 'parent', $parentchanged[$category->id], 'parent', $category->id);
540
541 //Fill feedback
542 $feedbackdata[] = array($category->name, $strcatdeleted);
543 }
544 }
545 //Inform about changes performed if feedback is enabled
546 if ($feedback) {
d7444d44 547 $table = new stdClass;
f67172b6 548 $table->head = array(get_string('category','quiz'), get_string('action'));
549 $table->data = $feedbackdata;
550 print_table($table);
551 }
552 }
553 return true;
554}
555
a044c05d 556function questionbank_navigation_tabs(&$row, $context, $querystring) {
d187f660 557 global $CFG;
558 if (has_capability('moodle/question:manage', $context)) {
a044c05d 559 $row[] = new tabobject('questions', "$CFG->wwwroot/question/edit.php?$querystring", get_string('questions', 'quiz'), get_string('editquestions', "quiz"));
d187f660 560 }
561
562 if (has_capability('moodle/question:managecategory', $context)) {
a044c05d 563 $row[] = new tabobject('categories', "$CFG->wwwroot/question/category.php?$querystring", get_string('categories', 'quiz'), get_string('editqcats', 'quiz'));
d187f660 564 }
565
566 if (has_capability('moodle/question:import', $context)) {
a044c05d 567 $row[] = new tabobject('import', "$CFG->wwwroot/question/import.php?$querystring", get_string('import', 'quiz'), get_string('importquestions', 'quiz'));
d187f660 568 }
569
570 if (has_capability('moodle/question:export', $context)) {
a044c05d 571 $row[] = new tabobject('export', "$CFG->wwwroot/question/export.php?$querystring", get_string('export', 'quiz'), get_string('exportquestions', 'quiz'));
d187f660 572 }
573}
574
516cf3eb 575/**
d7444d44 576 * Private function to factor common code out of get_question_options().
271ffe3f 577 *
d7444d44 578 * @param object $question the question to tidy.
271ffe3f 579 * @return boolean true if successful, else false.
d7444d44 580 */
581function _tidy_question(&$question) {
f02c6f01 582 global $QTYPES;
d7444d44 583 if (!array_key_exists($question->qtype, $QTYPES)) {
584 $question->qtype = 'missingtype';
585 $question->questiontext = '<p>' . get_string('warningmissingtype', 'quiz') . '</p>' . $question->questiontext;
586 }
587 $question->name_prefix = question_make_name_prefix($question->id);
588 return $QTYPES[$question->qtype]->get_question_options($question);
589}
516cf3eb 590
d7444d44 591/**
592 * Updates the question objects with question type specific
593 * information by calling {@link get_question_options()}
594 *
595 * Can be called either with an array of question objects or with a single
596 * question object.
271ffe3f 597 *
d7444d44 598 * @param mixed $questions Either an array of question objects to be updated
599 * or just a single question object
600 * @return bool Indicates success or failure.
601 */
602function get_question_options(&$questions) {
516cf3eb 603 if (is_array($questions)) { // deal with an array of questions
d7444d44 604 foreach ($questions as $i => $notused) {
605 if (!_tidy_question($questions[$i])) {
516cf3eb 606 return false;
d7444d44 607 }
516cf3eb 608 }
609 return true;
610 } else { // deal with single question
d7444d44 611 return _tidy_question($questions);
516cf3eb 612 }
613}
614
615/**
616* Loads the most recent state of each question session from the database
617* or create new one.
618*
619* For each question the most recent session state for the current attempt
4f48fb42 620* is loaded from the question_states table and the question type specific data and
621* responses are added by calling {@link restore_question_state()} which in turn
516cf3eb 622* calls {@link restore_session_and_responses()} for each question.
623* If no states exist for the question instance an empty state object is
624* created representing the start of a session and empty question
625* type specific information and responses are created by calling
626* {@link create_session_and_responses()}.
516cf3eb 627*
628* @return array An array of state objects representing the most recent
629* states of the question sessions.
630* @param array $questions The questions for which sessions are to be restored or
631* created.
632* @param object $cmoptions
633* @param object $attempt The attempt for which the question sessions are
634* to be restored or created.
46e910c7 635* @param mixed either the id of a previous attempt, if this attmpt is
636* building on a previous one, or false for a clean attempt.
516cf3eb 637*/
46e910c7 638function get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) {
f02c6f01 639 global $CFG, $QTYPES;
516cf3eb 640
641 // get the question ids
642 $ids = array_keys($questions);
643 $questionlist = implode(',', $ids);
644
645 // The question field must be listed first so that it is used as the
646 // array index in the array returned by get_records_sql
3e3e5a40 647 $statefields = 'n.questionid as question, s.*, n.sumpenalty, n.manualcomment';
516cf3eb 648 // Load the newest states for the questions
649 $sql = "SELECT $statefields".
4f48fb42 650 " FROM {$CFG->prefix}question_states s,".
516cf3eb 651 " {$CFG->prefix}question_sessions n".
652 " WHERE s.id = n.newest".
653 " AND n.attemptid = '$attempt->uniqueid'".
654 " AND n.questionid IN ($questionlist)";
655 $states = get_records_sql($sql);
656
657 // Load the newest graded states for the questions
658 $sql = "SELECT $statefields".
4f48fb42 659 " FROM {$CFG->prefix}question_states s,".
516cf3eb 660 " {$CFG->prefix}question_sessions n".
661 " WHERE s.id = n.newgraded".
662 " AND n.attemptid = '$attempt->uniqueid'".
663 " AND n.questionid IN ($questionlist)";
664 $gradedstates = get_records_sql($sql);
665
666 // loop through all questions and set the last_graded states
667 foreach ($ids as $i) {
668 if (isset($states[$i])) {
4f48fb42 669 restore_question_state($questions[$i], $states[$i]);
516cf3eb 670 if (isset($gradedstates[$i])) {
4f48fb42 671 restore_question_state($questions[$i], $gradedstates[$i]);
516cf3eb 672 $states[$i]->last_graded = $gradedstates[$i];
673 } else {
674 $states[$i]->last_graded = clone($states[$i]);
516cf3eb 675 }
676 } else {
fb708c11 677 // If the new attempt is to be based on a previous attempt get it and clean things
678 // Having lastattemptid filled implies that (should we double check?):
679 // $attempt->attempt > 1 and $cmoptions->attemptonlast and !$attempt->preview
680 if ($lastattemptid) {
681 // find the responses from the previous attempt and save them to the new session
682
683 // Load the last graded state for the question
684 $statefields = 'n.questionid as question, s.*, n.sumpenalty';
685 $sql = "SELECT $statefields".
686 " FROM {$CFG->prefix}question_states s,".
687 " {$CFG->prefix}question_sessions n".
688 " WHERE s.id = n.newgraded".
689 " AND n.attemptid = '$lastattemptid'".
690 " AND n.questionid = '$i'";
691 if (!$laststate = get_record_sql($sql)) {
692 // Only restore previous responses that have been graded
693 continue;
694 }
695 // Restore the state so that the responses will be restored
696 restore_question_state($questions[$i], $laststate);
697 $states[$i] = clone ($laststate);
698 } else {
699 // create a new empty state
700 $states[$i] = new object;
701 }
702
703 // now fill/overide initial values
d23e3e11 704 $states[$i]->attempt = $attempt->uniqueid;
705 $states[$i]->question = (int) $i;
706 $states[$i]->seq_number = 0;
707 $states[$i]->timestamp = $attempt->timestart;
708 $states[$i]->event = ($attempt->timefinish) ? QUESTION_EVENTCLOSE : QUESTION_EVENTOPEN;
709 $states[$i]->grade = 0;
710 $states[$i]->raw_grade = 0;
711 $states[$i]->penalty = 0;
712 $states[$i]->sumpenalty = 0;
3e3e5a40 713 $states[$i]->manualcomment = '';
fb708c11 714
715 // if building on last attempt we want to preserve responses
716 if (!$lastattemptid) {
717 $states[$i]->responses = array('' => '');
718 }
d23e3e11 719 // Prevent further changes to the session from incrementing the
720 // sequence number
721 $states[$i]->changed = true;
722
fb708c11 723 if ($lastattemptid) {
724 // prepare the previous responses for new processing
725 $action = new stdClass;
726 $action->responses = $laststate->responses;
727 $action->timestamp = $laststate->timestamp;
728 $action->event = QUESTION_EVENTSAVE; //emulate save of questions from all pages MDL-7631
729
730 // Process these responses ...
731 question_process_responses($questions[$i], $states[$i], $action, $cmoptions, $attempt);
732
733 // Fix for Bug #5506: When each attempt is built on the last one,
734 // preserve the options from any previous attempt.
735 if ( isset($laststate->options) ) {
736 $states[$i]->options = $laststate->options;
737 }
738 } else {
739 // Create the empty question type specific information
740 if (!$QTYPES[$questions[$i]->qtype]->create_session_and_responses(
741 $questions[$i], $states[$i], $cmoptions, $attempt)) {
742 return false;
743 }
516cf3eb 744 }
d23e3e11 745 $states[$i]->last_graded = clone($states[$i]);
516cf3eb 746 }
747 }
748 return $states;
749}
750
751
752/**
753* Creates the run-time fields for the states
754*
755* Extends the state objects for a question by calling
756* {@link restore_session_and_responses()}
516cf3eb 757* @param object $question The question for which the state is needed
865b7534 758* @param object $state The state as loaded from the database
759* @return boolean Represents success or failure
516cf3eb 760*/
4f48fb42 761function restore_question_state(&$question, &$state) {
f02c6f01 762 global $QTYPES;
516cf3eb 763
764 // initialise response to the value in the answer field
865b7534 765 $state->responses = array('' => addslashes($state->answer));
516cf3eb 766 unset($state->answer);
3e3e5a40 767 $state->manualcomment = isset($state->manualcomment) ? addslashes($state->manualcomment) : '';
516cf3eb 768
769 // Set the changed field to false; any code which changes the
770 // question session must set this to true and must increment
4f48fb42 771 // ->seq_number. The save_question_session
516cf3eb 772 // function will save the new state object to the database if the field is
773 // set to true.
774 $state->changed = false;
775
776 // Load the question type specific data
f02c6f01 777 return $QTYPES[$question->qtype]
865b7534 778 ->restore_session_and_responses($question, $state);
516cf3eb 779
780}
781
782/**
783* Saves the current state of the question session to the database
784*
785* The state object representing the current state of the session for the
4f48fb42 786* question is saved to the question_states table with ->responses[''] saved
516cf3eb 787* to the answer field of the database table. The information in the
788* question_sessions table is updated.
789* The question type specific data is then saved.
bc2feba3 790* @return mixed The id of the saved or updated state or false
516cf3eb 791* @param object $question The question for which session is to be saved.
792* @param object $state The state information to be saved. In particular the
793* most recent responses are in ->responses. The object
794* is updated to hold the new ->id.
795*/
4f48fb42 796function save_question_session(&$question, &$state) {
f02c6f01 797 global $QTYPES;
516cf3eb 798 // Check if the state has changed
799 if (!$state->changed && isset($state->id)) {
bc2feba3 800 return $state->id;
516cf3eb 801 }
802 // Set the legacy answer field
803 $state->answer = isset($state->responses['']) ? $state->responses[''] : '';
804
805 // Save the state
36be25f6 806 if (!empty($state->update)) { // this forces the old state record to be overwritten
4f48fb42 807 update_record('question_states', $state);
516cf3eb 808 } else {
4f48fb42 809 if (!$state->id = insert_record('question_states', $state)) {
516cf3eb 810 unset($state->id);
811 unset($state->answer);
812 return false;
813 }
b6e907a2 814 }
516cf3eb 815
b6e907a2 816 // create or update the session
2e9b6d15 817 if (!$session = get_record('question_sessions', 'attemptid',
865b7534 818 $state->attempt, 'questionid', $question->id)) {
2e9b6d15 819 $session->attemptid = $state->attempt;
820 $session->questionid = $question->id;
821 $session->newest = $state->id;
822 // The following may seem weird, but the newgraded field needs to be set
823 // already even if there is no graded state yet.
824 $session->newgraded = $state->id;
825 $session->sumpenalty = $state->sumpenalty;
3e3e5a40 826 $session->manualcomment = $state->manualcomment;
2e9b6d15 827 if (!insert_record('question_sessions', $session)) {
b6e907a2 828 error('Could not insert entry in question_sessions');
516cf3eb 829 }
b6e907a2 830 } else {
2e9b6d15 831 $session->newest = $state->id;
832 if (question_state_is_graded($state) or $state->event == QUESTION_EVENTOPEN) {
833 // this state is graded or newly opened, so it goes into the lastgraded field as well
834 $session->newgraded = $state->id;
835 $session->sumpenalty = $state->sumpenalty;
3e3e5a40 836 $session->manualcomment = $state->manualcomment;
ef822868 837 } else {
3e3e5a40 838 $session->manualcomment = addslashes($session->manualcomment);
516cf3eb 839 }
2e9b6d15 840 update_record('question_sessions', $session);
516cf3eb 841 }
842
843 unset($state->answer);
844
845 // Save the question type specific state information and responses
f02c6f01 846 if (!$QTYPES[$question->qtype]->save_session_and_responses(
516cf3eb 847 $question, $state)) {
848 return false;
849 }
850 // Reset the changed flag
851 $state->changed = false;
bc2feba3 852 return $state->id;
516cf3eb 853}
854
855/**
856* Determines whether a state has been graded by looking at the event field
857*
858* @return boolean true if the state has been graded
859* @param object $state
860*/
4f48fb42 861function question_state_is_graded($state) {
bc2feba3 862 return ($state->event == QUESTION_EVENTGRADE
863 or $state->event == QUESTION_EVENTCLOSEANDGRADE
864 or $state->event == QUESTION_EVENTMANUALGRADE);
f30bbcaf 865}
866
867/**
868* Determines whether a state has been closed by looking at the event field
869*
870* @return boolean true if the state has been closed
871* @param object $state
872*/
873function question_state_is_closed($state) {
b6e907a2 874 return ($state->event == QUESTION_EVENTCLOSE
875 or $state->event == QUESTION_EVENTCLOSEANDGRADE
876 or $state->event == QUESTION_EVENTMANUALGRADE);
516cf3eb 877}
878
879
880/**
4dca7e51 881 * Extracts responses from submitted form
882 *
883 * This can extract the responses given to one or several questions present on a page
884 * It returns an array with one entry for each question, indexed by question id
885 * Each entry is an object with the properties
886 * ->event The event that has triggered the submission. This is determined by which button
887 * the user has pressed.
888 * ->responses An array holding the responses to an individual question, indexed by the
889 * name of the corresponding form element.
890 * ->timestamp A unix timestamp
891 * @return array array of action objects, indexed by question ids.
892 * @param array $questions an array containing at least all questions that are used on the form
893 * @param array $formdata the data submitted by the form on the question page
894 * @param integer $defaultevent the event type used if no 'mark' or 'validate' is submitted
895 */
896function question_extract_responses($questions, $formdata, $defaultevent=QUESTION_EVENTSAVE) {
516cf3eb 897
4dca7e51 898 $time = time();
516cf3eb 899 $actions = array();
4dca7e51 900 foreach ($formdata as $key => $response) {
516cf3eb 901 // Get the question id from the response name
4f48fb42 902 if (false !== ($quid = question_get_id_from_name_prefix($key))) {
516cf3eb 903 // check if this is a valid id
904 if (!isset($questions[$quid])) {
905 error('Form contained question that is not in questionids');
906 }
907
908 // Remove the name prefix from the name
909 //decrypt trying
910 $key = substr($key, strlen($questions[$quid]->name_prefix));
911 if (false === $key) {
912 $key = '';
913 }
914 // Check for question validate and mark buttons & set events
915 if ($key === 'validate') {
4f48fb42 916 $actions[$quid]->event = QUESTION_EVENTVALIDATE;
4dca7e51 917 } else if ($key === 'submit') {
f30bbcaf 918 $actions[$quid]->event = QUESTION_EVENTSUBMIT;
516cf3eb 919 } else {
920 $actions[$quid]->event = $defaultevent;
921 }
922
923 // Update the state with the new response
924 $actions[$quid]->responses[$key] = $response;
271ffe3f 925
4dca7e51 926 // Set the timestamp
927 $actions[$quid]->timestamp = $time;
516cf3eb 928 }
929 }
3ebdddf7 930 foreach ($actions as $quid => $notused) {
931 ksort($actions[$quid]->responses);
932 }
516cf3eb 933 return $actions;
934}
935
936
bc75cc52 937/**
938 * Returns the html for question feedback image.
939 * @param float $fraction value representing the correctness of the user's
940 * response to a question.
941 * @param boolean $selected whether or not the answer is the one that the
942 * user picked.
943 * @return string
944 */
945function question_get_feedback_image($fraction, $selected=true) {
946
947 global $CFG;
948
949 if ($fraction >= 1.0) {
950 if ($selected) {
951 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_green_big.gif" '.
0d905d9f 952 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
bc75cc52 953 } else {
954 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_green_small.gif" '.
0d905d9f 955 'alt="'.get_string('correct', 'quiz').'" class="icon" />';
bc75cc52 956 }
957 } else if ($fraction > 0.0 && $fraction < 1.0) {
958 if ($selected) {
959 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_amber_big.gif" '.
0d905d9f 960 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
bc75cc52 961 } else {
962 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/tick_amber_small.gif" '.
0d905d9f 963 'alt="'.get_string('partiallycorrect', 'quiz').'" class="icon" />';
bc75cc52 964 }
965 } else {
966 if ($selected) {
967 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/cross_red_big.gif" '.
0d905d9f 968 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
bc75cc52 969 } else {
970 $feedbackimg = '<img src="'.$CFG->pixpath.'/i/cross_red_small.gif" '.
0d905d9f 971 'alt="'.get_string('incorrect', 'quiz').'" class="icon" />';
bc75cc52 972 }
973 }
974 return $feedbackimg;
975}
976
977
978/**
979 * Returns the class name for question feedback.
980 * @param float $fraction value representing the correctness of the user's
981 * response to a question.
982 * @return string
983 */
984function question_get_feedback_class($fraction) {
985
986 global $CFG;
987
988 if ($fraction >= 1.0) {
989 $class = 'correct';
990 } else if ($fraction > 0.0 && $fraction < 1.0) {
991 $class = 'partiallycorrect';
992 } else {
993 $class = 'incorrect';
994 }
995 return $class;
996}
997
516cf3eb 998
999/**
1000* For a given question in an attempt we walk the complete history of states
1001* and recalculate the grades as we go along.
1002*
1003* This is used when a question is changed and old student
1004* responses need to be marked with the new version of a question.
1005*
4f48fb42 1006* TODO: Make sure this is not quiz-specific
1007*
0a5b58af 1008* @return boolean Indicates whether the grade has changed
516cf3eb 1009* @param object $question A question object
1010* @param object $attempt The attempt, in which the question needs to be regraded.
1011* @param object $cmoptions
1012* @param boolean $verbose Optional. Whether to print progress information or not.
1013*/
4f48fb42 1014function regrade_question_in_attempt($question, $attempt, $cmoptions, $verbose=false) {
516cf3eb 1015
1016 // load all states for this question in this attempt, ordered in sequence
4f48fb42 1017 if ($states = get_records_select('question_states',
865b7534 1018 "attempt = '{$attempt->uniqueid}' AND question = '{$question->id}'",
1019 'seq_number ASC')) {
516cf3eb 1020 $states = array_values($states);
1021
1022 // Subtract the grade for the latest state from $attempt->sumgrades to get the
271ffe3f 1023 // sumgrades for the attempt without this question.
516cf3eb 1024 $attempt->sumgrades -= $states[count($states)-1]->grade;
1025
1026 // Initialise the replaystate
1027 $state = clone($states[0]);
3e3e5a40 1028 $state->manualcomment = get_field('question_sessions', 'manualcomment', 'attemptid',
82b5d7cd 1029 $attempt->uniqueid, 'questionid', $question->id);
4f48fb42 1030 restore_question_state($question, $state);
516cf3eb 1031 $state->sumpenalty = 0.0;
1032 $replaystate = clone($state);
1033 $replaystate->last_graded = $state;
1034
0a5b58af 1035 $changed = false;
516cf3eb 1036 for($j = 1; $j < count($states); $j++) {
4f48fb42 1037 restore_question_state($question, $states[$j]);
516cf3eb 1038 $action = new stdClass;
1039 $action->responses = $states[$j]->responses;
1040 $action->timestamp = $states[$j]->timestamp;
1041
f30bbcaf 1042 // Change event to submit so that it will be reprocessed
0a5b58af 1043 if (QUESTION_EVENTCLOSE == $states[$j]->event
865b7534 1044 or QUESTION_EVENTGRADE == $states[$j]->event
1045 or QUESTION_EVENTCLOSEANDGRADE == $states[$j]->event) {
f30bbcaf 1046 $action->event = QUESTION_EVENTSUBMIT;
516cf3eb 1047
1048 // By default take the event that was saved in the database
1049 } else {
1050 $action->event = $states[$j]->event;
1051 }
36be25f6 1052
5e60643e 1053 if ($action->event == QUESTION_EVENTMANUALGRADE) {
865b7534 1054 question_process_comment($question, $replaystate, $attempt,
3e3e5a40 1055 $replaystate->manualcomment, $states[$j]->grade);
36be25f6 1056 } else {
1057
1058 // Reprocess (regrade) responses
865b7534 1059 if (!question_process_responses($question, $replaystate,
1060 $action, $cmoptions, $attempt)) {
36be25f6 1061 $verbose && notify("Couldn't regrade state #{$state->id}!");
1062 }
516cf3eb 1063 }
1064
1065 // We need rounding here because grades in the DB get truncated
1066 // e.g. 0.33333 != 0.3333333, but we want them to be equal here
0a5b58af 1067 if ((round((float)$replaystate->raw_grade, 5) != round((float)$states[$j]->raw_grade, 5))
865b7534 1068 or (round((float)$replaystate->penalty, 5) != round((float)$states[$j]->penalty, 5))
1069 or (round((float)$replaystate->grade, 5) != round((float)$states[$j]->grade, 5))) {
0a5b58af 1070 $changed = true;
516cf3eb 1071 }
1072
1073 $replaystate->id = $states[$j]->id;
271ffe3f 1074 $replaystate->changed = true;
d23e3e11 1075 $replaystate->update = true; // This will ensure that the existing database entry is updated rather than a new one created
4f48fb42 1076 save_question_session($question, $replaystate);
516cf3eb 1077 }
0a5b58af 1078 if ($changed) {
1780811d 1079 // TODO, call a method in quiz to do this, where 'quiz' comes from
1080 // the question_attempts table.
0a5b58af 1081 update_record('quiz_attempts', $attempt);
516cf3eb 1082 }
1083
0a5b58af 1084 return $changed;
516cf3eb 1085 }
0a5b58af 1086 return false;
516cf3eb 1087}
1088
1089/**
1090* Processes an array of student responses, grading and saving them as appropriate
1091*
1092* @return boolean Indicates success/failure
1093* @param object $question Full question object, passed by reference
1094* @param object $state Full state object, passed by reference
1095* @param object $action object with the fields ->responses which
1096* is an array holding the student responses,
4f48fb42 1097* ->action which specifies the action, e.g., QUESTION_EVENTGRADE,
516cf3eb 1098* and ->timestamp which is a timestamp from when the responses
1099* were submitted by the student.
1100* @param object $cmoptions
1101* @param object $attempt The attempt is passed by reference so that
1102* during grading its ->sumgrades field can be updated
1103*/
4f48fb42 1104function question_process_responses(&$question, &$state, $action, $cmoptions, &$attempt) {
f02c6f01 1105 global $QTYPES;
516cf3eb 1106
1107 // if no responses are set initialise to empty response
1108 if (!isset($action->responses)) {
1109 $action->responses = array('' => '');
1110 }
1111
1112 // make sure these are gone!
755bddf1 1113 unset($action->responses['submit'], $action->responses['validate']);
516cf3eb 1114
1115 // Check the question session is still open
f30bbcaf 1116 if (question_state_is_closed($state)) {
516cf3eb 1117 return true;
1118 }
f30bbcaf 1119
516cf3eb 1120 // If $action->event is not set that implies saving
1121 if (! isset($action->event)) {
a6b691d8 1122 debugging('Ambiguous action in question_process_responses.' , DEBUG_DEVELOPER);
4f48fb42 1123 $action->event = QUESTION_EVENTSAVE;
516cf3eb 1124 }
f30bbcaf 1125 // If submitted then compare against last graded
516cf3eb 1126 // responses, not last given responses in this case
4f48fb42 1127 if (question_isgradingevent($action->event)) {
516cf3eb 1128 $state->responses = $state->last_graded->responses;
1129 }
271ffe3f 1130
516cf3eb 1131 // Check for unchanged responses (exactly unchanged, not equivalent).
1132 // We also have to catch questions that the student has not yet attempted
47cdbd1f 1133 $sameresponses = $QTYPES[$question->qtype]->compare_responses($question, $action, $state);
4f2c86ad 1134 if (!empty($state->last_graded) && $state->last_graded->event == QUESTION_EVENTOPEN &&
1135 question_isgradingevent($action->event)) {
47cdbd1f 1136 $sameresponses = false;
1137 }
516cf3eb 1138
f30bbcaf 1139 // If the response has not been changed then we do not have to process it again
1140 // unless the attempt is closing or validation is requested
4f48fb42 1141 if ($sameresponses and QUESTION_EVENTCLOSE != $action->event
5a14d563 1142 and QUESTION_EVENTVALIDATE != $action->event) {
516cf3eb 1143 return true;
1144 }
1145
1146 // Roll back grading information to last graded state and set the new
1147 // responses
1148 $newstate = clone($state->last_graded);
1149 $newstate->responses = $action->responses;
1150 $newstate->seq_number = $state->seq_number + 1;
1151 $newstate->changed = true; // will assure that it gets saved to the database
ca56222d 1152 $newstate->last_graded = clone($state->last_graded);
516cf3eb 1153 $newstate->timestamp = $action->timestamp;
1154 $state = $newstate;
1155
1156 // Set the event to the action we will perform. The question type specific
4f48fb42 1157 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
516cf3eb 1158 // attempt at the question causes the session to close
1159 $state->event = $action->event;
1160
4f48fb42 1161 if (!question_isgradingevent($action->event)) {
516cf3eb 1162 // Grade the response but don't update the overall grade
47e16978 1163 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
1164
1165 // Temporary hack because question types are not given enough control over what is going
1166 // on. Used by Opaque questions.
1167 // TODO fix this code properly.
1168 if (!empty($state->believeevent)) {
1169 // If the state was graded we need to ...
1170 if (question_state_is_graded($state)) {
1171 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1172
1173 // update the attempt grade
1174 $attempt->sumgrades -= (float)$state->last_graded->grade;
1175 $attempt->sumgrades += (float)$state->grade;
1176
1177 // and update the last_graded field.
1178 unset($state->last_graded);
1179 $state->last_graded = clone($state);
1180 unset($state->last_graded->changed);
1181 }
1182 } else {
1183 // Don't allow the processing to change the event type
1184 $state->event = $action->event;
1185 }
1186
ca56222d 1187 } else { // grading event
516cf3eb 1188
271ffe3f 1189 // Unless the attempt is closing, we want to work out if the current responses
1190 // (or equivalent responses) were already given in the last graded attempt.
5a14d563 1191 if(QUESTION_EVENTCLOSE != $action->event && QUESTION_EVENTOPEN != $state->last_graded->event &&
1192 $QTYPES[$question->qtype]->compare_responses($question, $state, $state->last_graded)) {
f30bbcaf 1193 $state->event = QUESTION_EVENTDUPLICATE;
516cf3eb 1194 }
f30bbcaf 1195
ca56222d 1196 // If we did not find a duplicate or if the attempt is closing, perform grading
5a14d563 1197 if ((!$sameresponses and QUESTION_EVENTDUPLICATE != $state->event) or
1198 QUESTION_EVENTCLOSE == $action->event) {
f30bbcaf 1199
47e16978 1200 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
f30bbcaf 1201 // Calculate overall grade using correct penalty method
1202 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
516cf3eb 1203 }
516cf3eb 1204
47e16978 1205 // If the state was graded we need to ...
ca56222d 1206 if (question_state_is_graded($state)) {
47e16978 1207 // update the attempt grade
1208 $attempt->sumgrades -= (float)$state->last_graded->grade;
1209 $attempt->sumgrades += (float)$state->grade;
1210
1211 // and update the last_graded field.
ca56222d 1212 unset($state->last_graded);
1213 $state->last_graded = clone($state);
1214 unset($state->last_graded->changed);
1215 }
516cf3eb 1216 }
1217 $attempt->timemodified = $action->timestamp;
1218
1219 return true;
1220}
1221
1222/**
1223* Determine if event requires grading
1224*/
4f48fb42 1225function question_isgradingevent($event) {
f30bbcaf 1226 return (QUESTION_EVENTSUBMIT == $event || QUESTION_EVENTCLOSE == $event);
516cf3eb 1227}
1228
516cf3eb 1229/**
1230* Applies the penalty from the previous graded responses to the raw grade
1231* for the current responses
1232*
1233* The grade for the question in the current state is computed by subtracting the
1234* penalty accumulated over the previous graded responses at the question from the
1235* raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1236* the grade is set to zero. The ->grade field of the state object is modified to
1237* reflect the new grade but is never allowed to decrease.
1238* @param object $question The question for which the penalty is to be applied.
1239* @param object $state The state for which the grade is to be set from the
1240* raw grade and the cumulative penalty from the last
1241* graded state. The ->grade field is updated by applying
1242* the penalty scheme determined in $cmoptions to the ->raw_grade and
1243* ->last_graded->penalty fields.
1244* @param object $cmoptions The options set by the course module.
1245* The ->penaltyscheme field determines whether penalties
1246* for incorrect earlier responses are subtracted.
1247*/
4f48fb42 1248function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
b423cff1 1249 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1250 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1251
f30bbcaf 1252 // deal with penalty
516cf3eb 1253 if ($cmoptions->penaltyscheme) {
47e16978 1254 $state->grade = $state->raw_grade - $state->sumpenalty;
1255 $state->sumpenalty += (float) $state->penalty;
516cf3eb 1256 } else {
1257 $state->grade = $state->raw_grade;
1258 }
1259
1260 // deal with timelimit
1261 if ($cmoptions->timelimit) {
1262 // We allow for 5% uncertainty in the following test
c7318911 1263 if ($state->timestamp - $attempt->timestart > $cmoptions->timelimit * 63) {
1264 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
1265 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE, $cm->id),
1266 $attempt->userid, false)) {
1267 $state->grade = 0;
1268 }
516cf3eb 1269 }
1270 }
1271
1272 // deal with closing time
1273 if ($cmoptions->timeclose and $state->timestamp > ($cmoptions->timeclose + 60) // allowing 1 minute lateness
1274 and !$attempt->preview) { // ignore closing time for previews
1275 $state->grade = 0;
1276 }
1277
1278 // Ensure that the grade does not go down
1279 $state->grade = max($state->grade, $state->last_graded->grade);
1280}
1281
516cf3eb 1282/**
1283* Print the icon for the question type
1284*
1285* @param object $question The question object for which the icon is required
516cf3eb 1286* @param boolean $return If true the functions returns the link as a string
1287*/
dcc2ffde 1288function print_question_icon($question, $return = false) {
dc1f00de 1289 global $QTYPES, $CFG;
516cf3eb 1290
a95cd8a6 1291 $namestr = $QTYPES[$question->qtype]->menu_name();
dcc2ffde 1292 $html = '<img src="' . $CFG->wwwroot . '/question/type/' .
1293 $question->qtype . '/icon.gif" alt="' .
1294 $namestr . '" title="' . $namestr . '" />';
516cf3eb 1295 if ($return) {
1296 return $html;
1297 } else {
1298 echo $html;
1299 }
1300}
1301
516cf3eb 1302/**
1303* Returns a html link to the question image if there is one
1304*
1305* @return string The html image tag or the empy string if there is no image.
1306* @param object $question The question object
1307*/
4f48fb42 1308function get_question_image($question, $courseid) {
516cf3eb 1309
1310 global $CFG;
1311 $img = '';
1312
1313 if ($question->image) {
1314
1315 if (substr(strtolower($question->image), 0, 7) == 'http://') {
1316 $img .= $question->image;
1317
1318 } else if ($CFG->slasharguments) { // Use this method if possible for better caching
1319 $img .= "$CFG->wwwroot/file.php/$courseid/$question->image";
1320
1321 } else {
87075ec1 1322 $img .= "$CFG->wwwroot/file.php?file=/$courseid/$question->image";
516cf3eb 1323 }
1324 }
1325 return $img;
1326}
b6e907a2 1327
1328function question_print_comment_box($question, $state, $attempt, $url) {
2a2aba27 1329 global $CFG;
1330
848d886e 1331 $prefix = 'response';
2a2aba27 1332 $usehtmleditor = can_use_richtext_editor();
1333 $grade = round($state->last_graded->grade, 3);
1334 echo '<form method="post" action="'.$url.'">';
1335 include($CFG->dirroot.'/question/comment.html');
1336 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid.'" />';
1337 echo '<input type="hidden" name="question" value="'.$question->id.'" />';
1338 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1339 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1340 echo '</form>';
1341
1342 if ($usehtmleditor) {
848d886e 1343 use_html_editor();
2a2aba27 1344 }
b6e907a2 1345}
1346
1347function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1348
1349 // Update the comment and save it in the database
3e3e5a40 1350 $state->manualcomment = $comment;
13835c77 1351 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid, 'questionid', $question->id)) {
b6e907a2 1352 error("Cannot save comment");
1353 }
95ac8a40 1354
1355 // Update the attempt if the score has changed.
b6e907a2 1356 if (abs($state->last_graded->grade - $grade) > 0.002) {
b6e907a2 1357 $attempt->sumgrades = $attempt->sumgrades - $state->last_graded->grade + $grade;
1358 $attempt->timemodified = time();
1359 if (!update_record('quiz_attempts', $attempt)) {
1360 error('Failed to save the current quiz attempt!');
1361 }
95ac8a40 1362 }
b6e907a2 1363
95ac8a40 1364 // Update the state if either the score has changed, or this is the first
1365 // manual grade event.
1366 // We don't need to store the modified state in the database, we just need
1367 // to set the $state->changed flag.
1368 if (abs($state->last_graded->grade - $grade) > 0.002 ||
1369 $state->last_graded->event != QUESTION_EVENTMANUALGRADE) {
84bf852c 1370
1371 // We want to update existing state (rather than creating new one) if it
1372 // was itself created by a manual grading event.
1373 $state->update = ($state->event == QUESTION_EVENTMANUALGRADE) ? 1 : 0;
1374
1375 // Update the other parts of the state object.
b6e907a2 1376 $state->raw_grade = $grade;
1377 $state->grade = $grade;
1378 $state->penalty = 0;
1379 $state->timestamp = time();
36be25f6 1380 $state->seq_number++;
95ac8a40 1381 $state->event = QUESTION_EVENTMANUALGRADE;
1382
b6e907a2 1383 // Update the last graded state (don't simplify!)
1384 unset($state->last_graded);
1385 $state->last_graded = clone($state);
95ac8a40 1386
1387 // We need to indicate that the state has changed in order for it to be saved.
1388 $state->changed = 1;
b6e907a2 1389 }
1390
1391}
1392
516cf3eb 1393/**
1394* Construct name prefixes for question form element names
1395*
1396* Construct the name prefix that should be used for example in the
1397* names of form elements created by questions.
4f48fb42 1398* This is called by {@link get_question_options()}
516cf3eb 1399* to set $question->name_prefix.
1400* This name prefix includes the question id which can be
4f48fb42 1401* extracted from it with {@link question_get_id_from_name_prefix()}.
516cf3eb 1402*
1403* @return string
1404* @param integer $id The question id
1405*/
4f48fb42 1406function question_make_name_prefix($id) {
516cf3eb 1407 return 'resp' . $id . '_';
1408}
1409
1410/**
1411* Extract question id from the prefix of form element names
1412*
1413* @return integer The question id
1414* @param string $name The name that contains a prefix that was
4f48fb42 1415* constructed with {@link question_make_name_prefix()}
516cf3eb 1416*/
4f48fb42 1417function question_get_id_from_name_prefix($name) {
516cf3eb 1418 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1419 return false;
1420 return (integer) $matches[1];
1421}
1422
4f48fb42 1423/**
4dca7e51 1424 * Returns the unique id for a new attempt
1425 *
1426 * Every module can keep their own attempts table with their own sequential ids but
1427 * the question code needs to also have a unique id by which to identify all these
1428 * attempts. Hence a module, when creating a new attempt, calls this function and
1429 * stores the return value in the 'uniqueid' field of its attempts table.
4f48fb42 1430 */
36be25f6 1431function question_new_attempt_uniqueid($modulename='quiz') {
516cf3eb 1432 global $CFG;
d7444d44 1433 $attempt = new stdClass;
36be25f6 1434 $attempt->modulename = $modulename;
1435 if (!$id = insert_record('question_attempts', $attempt)) {
1436 error('Could not create new entry in question_attempts table');
1437 }
1438 return $id;
516cf3eb 1439}
1440
36be25f6 1441/**
1442 * Creates a stamp that uniquely identifies this version of the question
cbe20043 1443 *
1444 * In future we want this to use a hash of the question data to guarantee that
1445 * identical versions have the same version stamp.
1446 *
1447 * @param object $question
1448 * @return string A unique version stamp
1449 */
1450function question_hash($question) {
1451 return make_unique_id_code();
1452}
1453
516cf3eb 1454
1455/// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
99ba746d 1456/**
1457 * Get the HTML that needs to be included in the head tag when the
1458 * questions in $questionlist are printed in the gives states.
1459 *
1460 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1461 * @param array $questions an array of question objects, whose keys are question ids.
1462 * Must contain all the questions in $questionlist
1463 * @param array $states an array of question state objects, whose keys are question ids.
1464 * Must contain the state of all the questions in $questionlist
1465 *
1466 * @return string some HTML code that can go inside the head tag.
1467 */
1468function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1469 global $QTYPES;
516cf3eb 1470
99ba746d 1471 $contributions = array();
1472 foreach ($questionlist as $questionid) {
1473 $question = $questions[$questionid];
1474 $contributions = array_merge($contributions,
1475 $QTYPES[$question->qtype]->get_html_head_contributions(
1476 $question, $states[$questionid]));
1477 }
1478 return implode("\n", array_unique($contributions));
1479}
1480
1481/**
4dca7e51 1482 * Prints a question
1483 *
1484 * Simply calls the question type specific print_question() method.
1485 * @param object $question The question to be rendered.
1486 * @param object $state The state to render the question in.
1487 * @param integer $number The number for this question.
1488 * @param object $cmoptions The options specified by the course module
1489 * @param object $options An object specifying the rendering options.
1490 */
4f48fb42 1491function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
f02c6f01 1492 global $QTYPES;
516cf3eb 1493
f02c6f01 1494 $QTYPES[$question->qtype]->print_question($question, $state, $number,
516cf3eb 1495 $cmoptions, $options);
1496}
f5565b69 1497/**
99ba746d 1498 * Saves question options
1499 *
1500 * Simply calls the question type specific save_question_options() method.
1501 */
f5565b69 1502function save_question_options($question) {
1503 global $QTYPES;
1504
1505 $QTYPES[$question->qtype]->save_question_options($question);
1506}
516cf3eb 1507
1508/**
1509* Gets all teacher stored answers for a given question
1510*
1511* Simply calls the question type specific get_all_responses() method.
1512*/
1513// ULPGC ecastro
4f48fb42 1514function get_question_responses($question, $state) {
f02c6f01 1515 global $QTYPES;
1516 $r = $QTYPES[$question->qtype]->get_all_responses($question, $state);
516cf3eb 1517 return $r;
1518}
1519
1520
1521/**
dc1f00de 1522* Gets the response given by the user in a particular state
516cf3eb 1523*
1524* Simply calls the question type specific get_actual_response() method.
1525*/
1526// ULPGC ecastro
4f48fb42 1527function get_question_actual_response($question, $state) {
f02c6f01 1528 global $QTYPES;
516cf3eb 1529
f02c6f01 1530 $r = $QTYPES[$question->qtype]->get_actual_response($question, $state);
516cf3eb 1531 return $r;
1532}
1533
1534/**
dc1f00de 1535* TODO: document this
516cf3eb 1536*/
1537// ULPGc ecastro
4f48fb42 1538function get_question_fraction_grade($question, $state) {
f02c6f01 1539 global $QTYPES;
516cf3eb 1540
f02c6f01 1541 $r = $QTYPES[$question->qtype]->get_fractional_grade($question, $state);
516cf3eb 1542 return $r;
1543}
1544
1545
1546/// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1547
6cb4910c 1548/**
1549 * returns the categories with their names ordered following parent-child relationships
1550 * finally it tries to return pending categories (those being orphaned, whose parent is
1551 * incorrect) to avoid missing any category from original array.
1552 */
1553function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1554 $children = array();
1555 $keys = array_keys($categories);
1556
1557 foreach ($keys as $key) {
1558 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1559 $children[$key] = $categories[$key];
1560 $categories[$key]->processed = true;
1561 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1562 }
1563 }
1564 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1565 if ($level == 1) {
1566 foreach ($keys as $key) {
1567 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1568 if (!isset($categories[$key]->processed) && !record_exists('question_categories', 'course', $categories[$key]->course, 'id', $categories[$key]->parent)) {
1569 $children[$key] = $categories[$key];
1570 $categories[$key]->processed = true;
1571 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1572 }
1573 }
1574 }
1575 return $children;
1576}
1577
1578/**
062a7522 1579 * Private method, only for the use of add_indented_names().
271ffe3f 1580 *
062a7522 1581 * Recursively adds an indentedname field to each category, starting with the category
271ffe3f 1582 * with id $id, and dealing with that category and all its children, and
062a7522 1583 * return a new array, with those categories in the right order.
1584 *
271ffe3f 1585 * @param array $categories an array of categories which has had childids
062a7522 1586 * fields added by flatten_category_tree(). Passed by reference for
1587 * performance only. It is not modfied.
1588 * @param int $id the category to start the indenting process from.
1589 * @param int $depth the indent depth. Used in recursive calls.
1590 * @return array a new array of categories, in the right order for the tree.
6cb4910c 1591 */
062a7522 1592function flatten_category_tree(&$categories, $id, $depth = 0) {
271ffe3f 1593
062a7522 1594 // Indent the name of this category.
1595 $newcategories = array();
1596 $newcategories[$id] = $categories[$id];
1597 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) . $categories[$id]->name;
271ffe3f 1598
062a7522 1599 // Recursively indent the children.
1600 foreach ($categories[$id]->childids as $childid) {
1601 $newcategories = $newcategories + flatten_category_tree($categories, $childid, $depth + 1);
6cb4910c 1602 }
271ffe3f 1603
062a7522 1604 // Remove the childids array that were temporarily added.
1605 unset($newcategories[$id]->childids);
271ffe3f 1606
062a7522 1607 return $newcategories;
6cb4910c 1608}
1609
1610/**
062a7522 1611 * Format categories into an indented list reflecting the tree structure.
271ffe3f 1612 *
062a7522 1613 * @param array $categories An array of category objects, for example from the.
1614 * @return array The formatted list of categories.
6cb4910c 1615 */
062a7522 1616function add_indented_names($categories) {
6cb4910c 1617
271ffe3f 1618 // Add an array to each category to hold the child category ids. This array will be removed
062a7522 1619 // again by flatten_category_tree(). It should not be used outside these two functions.
1620 foreach (array_keys($categories) as $id) {
1621 $categories[$id]->childids = array();
6cb4910c 1622 }
1623
062a7522 1624 // Build the tree structure, and record which categories are top-level.
271ffe3f 1625 // We have to be careful, because the categories array may include published
062a7522 1626 // categories from other courses, but not their parents.
1627 $toplevelcategoryids = array();
1628 foreach (array_keys($categories) as $id) {
1629 if (!empty($categories[$id]->parent) && array_key_exists($categories[$id]->parent, $categories)) {
1630 $categories[$categories[$id]->parent]->childids[] = $id;
1631 } else {
1632 $toplevelcategoryids[] = $id;
6cb4910c 1633 }
1634 }
1635
062a7522 1636 // Flatten the tree to and add the indents.
1637 $newcategories = array();
1638 foreach ($toplevelcategoryids as $id) {
1639 $newcategories = $newcategories + flatten_category_tree($categories, $id);
6cb4910c 1640 }
1641
062a7522 1642 return $newcategories;
6cb4910c 1643}
2dd6d66b 1644
516cf3eb 1645/**
062a7522 1646 * Output a select menu of question categories.
271ffe3f 1647 *
062a7522 1648 * Categories from this course and (optionally) published categories from other courses
271ffe3f 1649 * are included. Optionally, only categories the current user may edit can be included.
062a7522 1650 *
1651 * @param integer $courseid the id of the course to get the categories for.
1652 * @param integer $published if true, include publised categories from other courses.
1653 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1654 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1655 */
61d9b9fc 1656function question_category_select_menu($courseid, $published = false, $only_editable = false, $selected = "") {
1657 $categoriesarray = question_category_options($courseid, $published, $only_editable);
3ed998f3 1658 if ($selected) {
1659 $nothing = '';
1660 } else {
1661 $nothing = 'choose';
516cf3eb 1662 }
61d9b9fc 1663 choose_from_menu($categoriesarray, 'category', $selected, $nothing);
516cf3eb 1664}
1665
375ed78a 1666/**
1667 * Output an array of question categories.
1668 *
61d9b9fc 1669 * Categories from this course and (optionally) published categories from other courses
1670 * are included. Optionally, only categories the current user may edit can be included.
375ed78a 1671 *
61d9b9fc 1672 * @param integer $courseid the id of the course to get the categories for.
1673 * @param integer $published if true, include publised categories from other courses.
1674 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1675 * @return array The list of categories.
375ed78a 1676 */
61d9b9fc 1677function question_category_options($courseid, $published = false, $only_editable = false) {
375ed78a 1678 global $CFG;
3a3c454e 1679
61d9b9fc 1680 // get sql fragment for published
1681 $publishsql="";
1682 if ($published) {
1683 $publishsql = " OR publish = 1";
1684 }
375ed78a 1685
1686 $categories = get_records_sql("
61d9b9fc 1687 SELECT cat.*, c.shortname AS coursename
1688 FROM {$CFG->prefix}question_categories cat, {$CFG->prefix}course c
1689 WHERE c.id = cat.course AND (cat.course = $courseid $publishsql)
1690 ORDER BY (CASE WHEN cat.course = $courseid THEN 0 ELSE 1 END), cat.parent, cat.sortorder, cat.name ASC");
3ed998f3 1691 $categories = add_indented_names($categories);
1692
375ed78a 1693 $categoriesarray = array();
61d9b9fc 1694 foreach ($categories as $category) {
1695 $cid = $category->id;
1696 $cname = question_category_coursename($category, $courseid);
1697 if ((!$only_editable) || has_capability('moodle/question:managecategory', get_context_instance(CONTEXT_COURSE, $category->course))) {
1698 $categoriesarray[$cid] = $cname;
375ed78a 1699 }
1700 }
61d9b9fc 1701 return $categoriesarray;
375ed78a 1702}
1703
61d9b9fc 1704/**
1705 * If the category is not from this course, and it is a published category,
1706 * then return the course category name with the course shortname appended in
1707 * brackets. Otherwise, just return the category name.
1708 */
1709function question_category_coursename($category, $courseid = 0) {
1710 $cname = (isset($category->indentedname)) ? $category->indentedname : $category->name;
1711 if ($category->course != $courseid && $category->publish) {
1712 if (!empty($category->coursename)) {
1713 $coursename = $category->coursename;
1714 } else {
1715 $coursename = get_field('course', 'shortname', 'id', $category->course);
1716 }
1717 $cname .= " ($coursename)";
516cf3eb 1718 }
61d9b9fc 1719 return $cname;
516cf3eb 1720}
1721
516cf3eb 1722/**
b20ea669 1723 * Returns a comma separated list of ids of the category and all subcategories
1724 */
dc1f00de 1725function question_categorylist($categoryid) {
516cf3eb 1726 // returns a comma separated list of ids of the category and all subcategories
1727 $categorylist = $categoryid;
dc1f00de 1728 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
516cf3eb 1729 foreach ($subcategories as $subcategory) {
dc1f00de 1730 $categorylist .= ','. question_categorylist($subcategory->id);
516cf3eb 1731 }
1732 }
1733 return $categorylist;
1734}
1735
61d9b9fc 1736/**
1737 * find and/or create the category described by a delimited list
1738 * e.g. tom/dick/harry
1739 * @param string catpath delimited category path
1740 * @param string delimiter path delimiting character
1741 * @param int courseid course to search for categories
1742 * @return mixed category object or null if fails
1743 */
1744function create_category_path( $catpath, $delimiter='/', $courseid=0 ) {
1745 $catpath = clean_param( $catpath,PARAM_PATH );
1746 $catnames = explode( $delimiter, $catpath );
1747 $parent = 0;
1748 $category = null;
1749 foreach ($catnames as $catname) {
1750 if ($category = get_record( 'question_categories', 'name', $catname, 'course', $courseid, 'parent', $parent )) {
1751 $parent = $category->id;
1752 }
1753 else {
1754 // create the new category
1755 $category = new object;
1756 $category->course = $courseid;
1757 $category->name = $catname;
1758 $category->info = '';
1759 $category->publish = false;
1760 $category->parent = $parent;
1761 $category->sortorder = 999;
1762 $category->stamp = make_unique_id_code();
1763 if (!($id = insert_record( 'question_categories', $category ))) {
1764 error( "cannot create new category - $catname" );
1765 }
1766 $category->id = $id;
1767 $parent = $id;
1768 }
1769 }
1770 return $category;
1771}
f5c15407 1772
61d9b9fc 1773/**
1774 * get the category as a path (e.g., tom/dick/harry)
1775 * @param int id the id of the most nested catgory
1776 * @param string delimiter the delimiter you want
1777 * @return string the path
1778 */
1779function get_category_path( $id, $delimiter='/' ) {
1780 $path = '';
1781 do {
1782 if (!$category = get_record( 'question_categories','id',$id )) {
1783 print_error( "Error reading category record - $id" );
1784 }
1785 $name = $category->name;
1786 $id = $category->parent;
1787 if (!empty($path)) {
1788 $path = "{$name}{$delimiter}{$path}";
1789 }
1790 else {
1791 $path = $name;
1792 }
1793 } while ($id != 0);
1794
1795 return $path;
1796}
516cf3eb 1797
947217d7 1798//===========================
1799// Import/Export Functions
1800//===========================
1801
ff4b6492 1802/**
1803 * Get list of available import or export formats
1804 * @param string $type 'import' if import list, otherwise export list assumed
271ffe3f 1805 * @return array sorted list of import/export formats available
ff4b6492 1806**/
1807function get_import_export_formats( $type ) {
1808
1809 global $CFG;
dc1f00de 1810 $fileformats = get_list_of_plugins("question/format");
ff4b6492 1811
1812 $fileformatname=array();
947217d7 1813 require_once( "{$CFG->dirroot}/question/format.php" );
ff4b6492 1814 foreach ($fileformats as $key => $fileformat) {
1815 $format_file = $CFG->dirroot . "/question/format/$fileformat/format.php";
1816 if (file_exists( $format_file ) ) {
1817 require_once( $format_file );
1818 }
1819 else {
1820 continue;
1821 }
70c01adb 1822 $classname = "qformat_$fileformat";
ff4b6492 1823 $format_class = new $classname();
1824 if ($type=='import') {
1825 $provided = $format_class->provide_import();
1826 }
1827 else {
1828 $provided = $format_class->provide_export();
1829 }
1830 if ($provided) {
1831 $formatname = get_string($fileformat, 'quiz');
1832 if ($formatname == "[[$fileformat]]") {
1833 $formatname = $fileformat; // Just use the raw folder name
1834 }
1835 $fileformatnames[$fileformat] = $formatname;
1836 }
1837 }
1838 natcasesort($fileformatnames);
1839
1840 return $fileformatnames;
1841}
feb60a07 1842
1843
1844/**
1845* Create default export filename
1846*
1847* @return string default export filename
1848* @param object $course
1849* @param object $category
1850*/
1851function default_export_filename($course,$category) {
1852 //Take off some characters in the filename !!
1853 $takeoff = array(" ", ":", "/", "\\", "|");
57f1b914 1854 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
feb60a07 1855 //If non-translated, use "export"
1856 if (substr($export_word,0,1) == "[") {
1857 $export_word= "export";
1858 }
1859
1860 //Calculate the date format string
1861 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1862 //If non-translated, use "%Y%m%d-%H%M"
1863 if (substr($export_date_format,0,1) == "[") {
1864 $export_date_format = "%%Y%%m%%d-%%H%%M";
1865 }
1866
1867 //Calculate the shortname
1868 $export_shortname = clean_filename($course->shortname);
1869 if (empty($export_shortname) or $export_shortname == '_' ) {
1870 $export_shortname = $course->id;
1871 }
1872
1873 //Calculate the category name
1874 $export_categoryname = clean_filename($category->name);
1875
1876 //Calculate the final export filename
1877 //The export word
1878 $export_name = $export_word."-";
1879 //The shortname
57f1b914 1880 $export_name .= moodle_strtolower($export_shortname)."-";
feb60a07 1881 //The category name
57f1b914 1882 $export_name .= moodle_strtolower($export_categoryname)."-";
feb60a07 1883 //The date format
1884 $export_name .= userdate(time(),$export_date_format,99,false);
1885 //The extension - no extension, supplied by format
1886 // $export_name .= ".txt";
1887
1888 return $export_name;
1889}
1890
f5c15407 1891?>