fix for category.php lists. Slight change in listlib api caused breakage.
[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);
1134 if ($state->last_graded->event == QUESTION_EVENTOPEN && question_isgradingevent($action->event)) {
1135 $sameresponses = false;
1136 }
516cf3eb 1137
f30bbcaf 1138 // If the response has not been changed then we do not have to process it again
1139 // unless the attempt is closing or validation is requested
4f48fb42 1140 if ($sameresponses and QUESTION_EVENTCLOSE != $action->event
5a14d563 1141 and QUESTION_EVENTVALIDATE != $action->event) {
516cf3eb 1142 return true;
1143 }
1144
1145 // Roll back grading information to last graded state and set the new
1146 // responses
1147 $newstate = clone($state->last_graded);
1148 $newstate->responses = $action->responses;
1149 $newstate->seq_number = $state->seq_number + 1;
1150 $newstate->changed = true; // will assure that it gets saved to the database
ca56222d 1151 $newstate->last_graded = clone($state->last_graded);
516cf3eb 1152 $newstate->timestamp = $action->timestamp;
1153 $state = $newstate;
1154
1155 // Set the event to the action we will perform. The question type specific
4f48fb42 1156 // grading code may override this by setting it to QUESTION_EVENTCLOSE if the
516cf3eb 1157 // attempt at the question causes the session to close
1158 $state->event = $action->event;
1159
4f48fb42 1160 if (!question_isgradingevent($action->event)) {
516cf3eb 1161 // Grade the response but don't update the overall grade
47e16978 1162 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
1163
1164 // Temporary hack because question types are not given enough control over what is going
1165 // on. Used by Opaque questions.
1166 // TODO fix this code properly.
1167 if (!empty($state->believeevent)) {
1168 // If the state was graded we need to ...
1169 if (question_state_is_graded($state)) {
1170 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
1171
1172 // update the attempt grade
1173 $attempt->sumgrades -= (float)$state->last_graded->grade;
1174 $attempt->sumgrades += (float)$state->grade;
1175
1176 // and update the last_graded field.
1177 unset($state->last_graded);
1178 $state->last_graded = clone($state);
1179 unset($state->last_graded->changed);
1180 }
1181 } else {
1182 // Don't allow the processing to change the event type
1183 $state->event = $action->event;
1184 }
1185
ca56222d 1186 } else { // grading event
516cf3eb 1187
271ffe3f 1188 // Unless the attempt is closing, we want to work out if the current responses
1189 // (or equivalent responses) were already given in the last graded attempt.
5a14d563 1190 if(QUESTION_EVENTCLOSE != $action->event && QUESTION_EVENTOPEN != $state->last_graded->event &&
1191 $QTYPES[$question->qtype]->compare_responses($question, $state, $state->last_graded)) {
f30bbcaf 1192 $state->event = QUESTION_EVENTDUPLICATE;
516cf3eb 1193 }
f30bbcaf 1194
ca56222d 1195 // If we did not find a duplicate or if the attempt is closing, perform grading
5a14d563 1196 if ((!$sameresponses and QUESTION_EVENTDUPLICATE != $state->event) or
1197 QUESTION_EVENTCLOSE == $action->event) {
f30bbcaf 1198
47e16978 1199 $QTYPES[$question->qtype]->grade_responses($question, $state, $cmoptions);
f30bbcaf 1200 // Calculate overall grade using correct penalty method
1201 question_apply_penalty_and_timelimit($question, $state, $attempt, $cmoptions);
516cf3eb 1202 }
516cf3eb 1203
47e16978 1204 // If the state was graded we need to ...
ca56222d 1205 if (question_state_is_graded($state)) {
47e16978 1206 // update the attempt grade
1207 $attempt->sumgrades -= (float)$state->last_graded->grade;
1208 $attempt->sumgrades += (float)$state->grade;
1209
1210 // and update the last_graded field.
ca56222d 1211 unset($state->last_graded);
1212 $state->last_graded = clone($state);
1213 unset($state->last_graded->changed);
1214 }
516cf3eb 1215 }
1216 $attempt->timemodified = $action->timestamp;
1217
1218 return true;
1219}
1220
1221/**
1222* Determine if event requires grading
1223*/
4f48fb42 1224function question_isgradingevent($event) {
f30bbcaf 1225 return (QUESTION_EVENTSUBMIT == $event || QUESTION_EVENTCLOSE == $event);
516cf3eb 1226}
1227
516cf3eb 1228/**
1229* Applies the penalty from the previous graded responses to the raw grade
1230* for the current responses
1231*
1232* The grade for the question in the current state is computed by subtracting the
1233* penalty accumulated over the previous graded responses at the question from the
1234* raw grade. If the timestamp is more than 1 minute beyond the end of the attempt
1235* the grade is set to zero. The ->grade field of the state object is modified to
1236* reflect the new grade but is never allowed to decrease.
1237* @param object $question The question for which the penalty is to be applied.
1238* @param object $state The state for which the grade is to be set from the
1239* raw grade and the cumulative penalty from the last
1240* graded state. The ->grade field is updated by applying
1241* the penalty scheme determined in $cmoptions to the ->raw_grade and
1242* ->last_graded->penalty fields.
1243* @param object $cmoptions The options set by the course module.
1244* The ->penaltyscheme field determines whether penalties
1245* for incorrect earlier responses are subtracted.
1246*/
4f48fb42 1247function question_apply_penalty_and_timelimit(&$question, &$state, $attempt, $cmoptions) {
b423cff1 1248 // TODO. Quiz dependancy. The fact that the attempt that is passed in here
1249 // is from quiz_attempts, and we use things like $cmoptions->timelimit.
1250
f30bbcaf 1251 // deal with penalty
516cf3eb 1252 if ($cmoptions->penaltyscheme) {
47e16978 1253 $state->grade = $state->raw_grade - $state->sumpenalty;
1254 $state->sumpenalty += (float) $state->penalty;
516cf3eb 1255 } else {
1256 $state->grade = $state->raw_grade;
1257 }
1258
1259 // deal with timelimit
1260 if ($cmoptions->timelimit) {
1261 // We allow for 5% uncertainty in the following test
c7318911 1262 if ($state->timestamp - $attempt->timestart > $cmoptions->timelimit * 63) {
1263 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
1264 if (!has_capability('mod/quiz:ignoretimelimits', get_context_instance(CONTEXT_MODULE, $cm->id),
1265 $attempt->userid, false)) {
1266 $state->grade = 0;
1267 }
516cf3eb 1268 }
1269 }
1270
1271 // deal with closing time
1272 if ($cmoptions->timeclose and $state->timestamp > ($cmoptions->timeclose + 60) // allowing 1 minute lateness
1273 and !$attempt->preview) { // ignore closing time for previews
1274 $state->grade = 0;
1275 }
1276
1277 // Ensure that the grade does not go down
1278 $state->grade = max($state->grade, $state->last_graded->grade);
1279}
1280
516cf3eb 1281/**
1282* Print the icon for the question type
1283*
1284* @param object $question The question object for which the icon is required
516cf3eb 1285* @param boolean $return If true the functions returns the link as a string
1286*/
dcc2ffde 1287function print_question_icon($question, $return = false) {
dc1f00de 1288 global $QTYPES, $CFG;
516cf3eb 1289
a95cd8a6 1290 $namestr = $QTYPES[$question->qtype]->menu_name();
dcc2ffde 1291 $html = '<img src="' . $CFG->wwwroot . '/question/type/' .
1292 $question->qtype . '/icon.gif" alt="' .
1293 $namestr . '" title="' . $namestr . '" />';
516cf3eb 1294 if ($return) {
1295 return $html;
1296 } else {
1297 echo $html;
1298 }
1299}
1300
516cf3eb 1301/**
1302* Returns a html link to the question image if there is one
1303*
1304* @return string The html image tag or the empy string if there is no image.
1305* @param object $question The question object
1306*/
4f48fb42 1307function get_question_image($question, $courseid) {
516cf3eb 1308
1309 global $CFG;
1310 $img = '';
1311
1312 if ($question->image) {
1313
1314 if (substr(strtolower($question->image), 0, 7) == 'http://') {
1315 $img .= $question->image;
1316
1317 } else if ($CFG->slasharguments) { // Use this method if possible for better caching
1318 $img .= "$CFG->wwwroot/file.php/$courseid/$question->image";
1319
1320 } else {
87075ec1 1321 $img .= "$CFG->wwwroot/file.php?file=/$courseid/$question->image";
516cf3eb 1322 }
1323 }
1324 return $img;
1325}
b6e907a2 1326
1327function question_print_comment_box($question, $state, $attempt, $url) {
2a2aba27 1328 global $CFG;
1329
848d886e 1330 $prefix = 'response';
2a2aba27 1331 $usehtmleditor = can_use_richtext_editor();
1332 $grade = round($state->last_graded->grade, 3);
1333 echo '<form method="post" action="'.$url.'">';
1334 include($CFG->dirroot.'/question/comment.html');
1335 echo '<input type="hidden" name="attempt" value="'.$attempt->uniqueid.'" />';
1336 echo '<input type="hidden" name="question" value="'.$question->id.'" />';
1337 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1338 echo '<input type="submit" name="submit" value="'.get_string('save', 'quiz').'" />';
1339 echo '</form>';
1340
1341 if ($usehtmleditor) {
848d886e 1342 use_html_editor();
2a2aba27 1343 }
b6e907a2 1344}
1345
1346function question_process_comment($question, &$state, &$attempt, $comment, $grade) {
1347
1348 // Update the comment and save it in the database
3e3e5a40 1349 $state->manualcomment = $comment;
13835c77 1350 if (!set_field('question_sessions', 'manualcomment', $comment, 'attemptid', $attempt->uniqueid, 'questionid', $question->id)) {
b6e907a2 1351 error("Cannot save comment");
1352 }
95ac8a40 1353
1354 // Update the attempt if the score has changed.
b6e907a2 1355 if (abs($state->last_graded->grade - $grade) > 0.002) {
b6e907a2 1356 $attempt->sumgrades = $attempt->sumgrades - $state->last_graded->grade + $grade;
1357 $attempt->timemodified = time();
1358 if (!update_record('quiz_attempts', $attempt)) {
1359 error('Failed to save the current quiz attempt!');
1360 }
95ac8a40 1361 }
b6e907a2 1362
95ac8a40 1363 // Update the state if either the score has changed, or this is the first
1364 // manual grade event.
1365 // We don't need to store the modified state in the database, we just need
1366 // to set the $state->changed flag.
1367 if (abs($state->last_graded->grade - $grade) > 0.002 ||
1368 $state->last_graded->event != QUESTION_EVENTMANUALGRADE) {
84bf852c 1369
1370 // We want to update existing state (rather than creating new one) if it
1371 // was itself created by a manual grading event.
1372 $state->update = ($state->event == QUESTION_EVENTMANUALGRADE) ? 1 : 0;
1373
1374 // Update the other parts of the state object.
b6e907a2 1375 $state->raw_grade = $grade;
1376 $state->grade = $grade;
1377 $state->penalty = 0;
1378 $state->timestamp = time();
36be25f6 1379 $state->seq_number++;
95ac8a40 1380 $state->event = QUESTION_EVENTMANUALGRADE;
1381
b6e907a2 1382 // Update the last graded state (don't simplify!)
1383 unset($state->last_graded);
1384 $state->last_graded = clone($state);
95ac8a40 1385
1386 // We need to indicate that the state has changed in order for it to be saved.
1387 $state->changed = 1;
b6e907a2 1388 }
1389
1390}
1391
516cf3eb 1392/**
1393* Construct name prefixes for question form element names
1394*
1395* Construct the name prefix that should be used for example in the
1396* names of form elements created by questions.
4f48fb42 1397* This is called by {@link get_question_options()}
516cf3eb 1398* to set $question->name_prefix.
1399* This name prefix includes the question id which can be
4f48fb42 1400* extracted from it with {@link question_get_id_from_name_prefix()}.
516cf3eb 1401*
1402* @return string
1403* @param integer $id The question id
1404*/
4f48fb42 1405function question_make_name_prefix($id) {
516cf3eb 1406 return 'resp' . $id . '_';
1407}
1408
1409/**
1410* Extract question id from the prefix of form element names
1411*
1412* @return integer The question id
1413* @param string $name The name that contains a prefix that was
4f48fb42 1414* constructed with {@link question_make_name_prefix()}
516cf3eb 1415*/
4f48fb42 1416function question_get_id_from_name_prefix($name) {
516cf3eb 1417 if (!preg_match('/^resp([0-9]+)_/', $name, $matches))
1418 return false;
1419 return (integer) $matches[1];
1420}
1421
4f48fb42 1422/**
4dca7e51 1423 * Returns the unique id for a new attempt
1424 *
1425 * Every module can keep their own attempts table with their own sequential ids but
1426 * the question code needs to also have a unique id by which to identify all these
1427 * attempts. Hence a module, when creating a new attempt, calls this function and
1428 * stores the return value in the 'uniqueid' field of its attempts table.
4f48fb42 1429 */
36be25f6 1430function question_new_attempt_uniqueid($modulename='quiz') {
516cf3eb 1431 global $CFG;
d7444d44 1432 $attempt = new stdClass;
36be25f6 1433 $attempt->modulename = $modulename;
1434 if (!$id = insert_record('question_attempts', $attempt)) {
1435 error('Could not create new entry in question_attempts table');
1436 }
1437 return $id;
516cf3eb 1438}
1439
36be25f6 1440/**
1441 * Creates a stamp that uniquely identifies this version of the question
cbe20043 1442 *
1443 * In future we want this to use a hash of the question data to guarantee that
1444 * identical versions have the same version stamp.
1445 *
1446 * @param object $question
1447 * @return string A unique version stamp
1448 */
1449function question_hash($question) {
1450 return make_unique_id_code();
1451}
1452
516cf3eb 1453
1454/// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
99ba746d 1455/**
1456 * Get the HTML that needs to be included in the head tag when the
1457 * questions in $questionlist are printed in the gives states.
1458 *
1459 * @param array $questionlist a list of questionids of the questions what will appear on this page.
1460 * @param array $questions an array of question objects, whose keys are question ids.
1461 * Must contain all the questions in $questionlist
1462 * @param array $states an array of question state objects, whose keys are question ids.
1463 * Must contain the state of all the questions in $questionlist
1464 *
1465 * @return string some HTML code that can go inside the head tag.
1466 */
1467function get_html_head_contributions(&$questionlist, &$questions, &$states) {
1468 global $QTYPES;
516cf3eb 1469
99ba746d 1470 $contributions = array();
1471 foreach ($questionlist as $questionid) {
1472 $question = $questions[$questionid];
1473 $contributions = array_merge($contributions,
1474 $QTYPES[$question->qtype]->get_html_head_contributions(
1475 $question, $states[$questionid]));
1476 }
1477 return implode("\n", array_unique($contributions));
1478}
1479
1480/**
4dca7e51 1481 * Prints a question
1482 *
1483 * Simply calls the question type specific print_question() method.
1484 * @param object $question The question to be rendered.
1485 * @param object $state The state to render the question in.
1486 * @param integer $number The number for this question.
1487 * @param object $cmoptions The options specified by the course module
1488 * @param object $options An object specifying the rendering options.
1489 */
4f48fb42 1490function print_question(&$question, &$state, $number, $cmoptions, $options=null) {
f02c6f01 1491 global $QTYPES;
516cf3eb 1492
f02c6f01 1493 $QTYPES[$question->qtype]->print_question($question, $state, $number,
516cf3eb 1494 $cmoptions, $options);
1495}
f5565b69 1496/**
99ba746d 1497 * Saves question options
1498 *
1499 * Simply calls the question type specific save_question_options() method.
1500 */
f5565b69 1501function save_question_options($question) {
1502 global $QTYPES;
1503
1504 $QTYPES[$question->qtype]->save_question_options($question);
1505}
516cf3eb 1506
1507/**
1508* Gets all teacher stored answers for a given question
1509*
1510* Simply calls the question type specific get_all_responses() method.
1511*/
1512// ULPGC ecastro
4f48fb42 1513function get_question_responses($question, $state) {
f02c6f01 1514 global $QTYPES;
1515 $r = $QTYPES[$question->qtype]->get_all_responses($question, $state);
516cf3eb 1516 return $r;
1517}
1518
1519
1520/**
dc1f00de 1521* Gets the response given by the user in a particular state
516cf3eb 1522*
1523* Simply calls the question type specific get_actual_response() method.
1524*/
1525// ULPGC ecastro
4f48fb42 1526function get_question_actual_response($question, $state) {
f02c6f01 1527 global $QTYPES;
516cf3eb 1528
f02c6f01 1529 $r = $QTYPES[$question->qtype]->get_actual_response($question, $state);
516cf3eb 1530 return $r;
1531}
1532
1533/**
dc1f00de 1534* TODO: document this
516cf3eb 1535*/
1536// ULPGc ecastro
4f48fb42 1537function get_question_fraction_grade($question, $state) {
f02c6f01 1538 global $QTYPES;
516cf3eb 1539
f02c6f01 1540 $r = $QTYPES[$question->qtype]->get_fractional_grade($question, $state);
516cf3eb 1541 return $r;
1542}
1543
1544
1545/// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
1546
6cb4910c 1547/**
1548 * returns the categories with their names ordered following parent-child relationships
1549 * finally it tries to return pending categories (those being orphaned, whose parent is
1550 * incorrect) to avoid missing any category from original array.
1551 */
1552function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
1553 $children = array();
1554 $keys = array_keys($categories);
1555
1556 foreach ($keys as $key) {
1557 if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1558 $children[$key] = $categories[$key];
1559 $categories[$key]->processed = true;
1560 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1561 }
1562 }
1563 //If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too
1564 if ($level == 1) {
1565 foreach ($keys as $key) {
1566 //If not processed and it's a good candidate to start (because its parent doesn't exist in the course)
1567 if (!isset($categories[$key]->processed) && !record_exists('question_categories', 'course', $categories[$key]->course, 'id', $categories[$key]->parent)) {
1568 $children[$key] = $categories[$key];
1569 $categories[$key]->processed = true;
1570 $children = $children + sort_categories_by_tree($categories, $children[$key]->id, $level+1);
1571 }
1572 }
1573 }
1574 return $children;
1575}
1576
1577/**
062a7522 1578 * Private method, only for the use of add_indented_names().
271ffe3f 1579 *
062a7522 1580 * Recursively adds an indentedname field to each category, starting with the category
271ffe3f 1581 * with id $id, and dealing with that category and all its children, and
062a7522 1582 * return a new array, with those categories in the right order.
1583 *
271ffe3f 1584 * @param array $categories an array of categories which has had childids
062a7522 1585 * fields added by flatten_category_tree(). Passed by reference for
1586 * performance only. It is not modfied.
1587 * @param int $id the category to start the indenting process from.
1588 * @param int $depth the indent depth. Used in recursive calls.
1589 * @return array a new array of categories, in the right order for the tree.
6cb4910c 1590 */
062a7522 1591function flatten_category_tree(&$categories, $id, $depth = 0) {
271ffe3f 1592
062a7522 1593 // Indent the name of this category.
1594 $newcategories = array();
1595 $newcategories[$id] = $categories[$id];
1596 $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) . $categories[$id]->name;
271ffe3f 1597
062a7522 1598 // Recursively indent the children.
1599 foreach ($categories[$id]->childids as $childid) {
1600 $newcategories = $newcategories + flatten_category_tree($categories, $childid, $depth + 1);
6cb4910c 1601 }
271ffe3f 1602
062a7522 1603 // Remove the childids array that were temporarily added.
1604 unset($newcategories[$id]->childids);
271ffe3f 1605
062a7522 1606 return $newcategories;
6cb4910c 1607}
1608
1609/**
062a7522 1610 * Format categories into an indented list reflecting the tree structure.
271ffe3f 1611 *
062a7522 1612 * @param array $categories An array of category objects, for example from the.
1613 * @return array The formatted list of categories.
6cb4910c 1614 */
062a7522 1615function add_indented_names($categories) {
6cb4910c 1616
271ffe3f 1617 // Add an array to each category to hold the child category ids. This array will be removed
062a7522 1618 // again by flatten_category_tree(). It should not be used outside these two functions.
1619 foreach (array_keys($categories) as $id) {
1620 $categories[$id]->childids = array();
6cb4910c 1621 }
1622
062a7522 1623 // Build the tree structure, and record which categories are top-level.
271ffe3f 1624 // We have to be careful, because the categories array may include published
062a7522 1625 // categories from other courses, but not their parents.
1626 $toplevelcategoryids = array();
1627 foreach (array_keys($categories) as $id) {
1628 if (!empty($categories[$id]->parent) && array_key_exists($categories[$id]->parent, $categories)) {
1629 $categories[$categories[$id]->parent]->childids[] = $id;
1630 } else {
1631 $toplevelcategoryids[] = $id;
6cb4910c 1632 }
1633 }
1634
062a7522 1635 // Flatten the tree to and add the indents.
1636 $newcategories = array();
1637 foreach ($toplevelcategoryids as $id) {
1638 $newcategories = $newcategories + flatten_category_tree($categories, $id);
6cb4910c 1639 }
1640
062a7522 1641 return $newcategories;
6cb4910c 1642}
2dd6d66b 1643
516cf3eb 1644/**
062a7522 1645 * Output a select menu of question categories.
271ffe3f 1646 *
062a7522 1647 * Categories from this course and (optionally) published categories from other courses
271ffe3f 1648 * are included. Optionally, only categories the current user may edit can be included.
062a7522 1649 *
1650 * @param integer $courseid the id of the course to get the categories for.
1651 * @param integer $published if true, include publised categories from other courses.
1652 * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
1653 * @param integer $selected optionally, the id of a category to be selected by default in the dropdown.
1654 */
3a3c454e 1655function question_category_select_menu($contexts, $top = false, $currentcat = 0, $selected = "") {
1656 $categoriesarray = question_category_options($contexts, $top, $currentcat);
3ed998f3 1657 if ($selected) {
1658 $nothing = '';
1659 } else {
1660 $nothing = 'choose';
516cf3eb 1661 }
3a3c454e 1662 choose_from_menu_nested($categoriesarray, 'category', $selected, $nothing);
516cf3eb 1663}
1664
375ed78a 1665/**
1666 * Output an array of question categories.
1667 *
375ed78a 1668 *
375ed78a 1669 */
3a3c454e 1670function question_category_options($contexts, $top = false, $currentcat = 0, $popupform = false) {
375ed78a 1671 global $CFG;
3a3c454e 1672 $pcontexts = array();
1673 foreach($contexts as $context){
1674 $pcontexts[] = $context->id;
375ed78a 1675 }
3a3c454e 1676 $contextslist = join($pcontexts, ', ');
1677
1678 // get sql fragment for published
1679
375ed78a 1680
1681 $categories = get_records_sql("
d92b9d91 1682 SELECT c.*, count(q.id) as questioncount
1683 FROM {$CFG->prefix}question_categories as c
1684 LEFT JOIN {$CFG->prefix}question as q ON c.id = q.category
1685 WHERE c.contextid IN ($contextslist) AND
1686 (q.id IS NULL OR (q.hidden='0' AND q.parent='0'))
1687 GROUP BY c.id
3a3c454e 1688 ORDER BY parent, sortorder, name ASC");
d92b9d91 1689
1690
3a3c454e 1691 $categories = question_add_context_in_key($categories);
d92b9d91 1692
3a3c454e 1693 if ($top){
1694 $categories = question_add_tops($categories, $pcontexts);
1695 }
3ed998f3 1696 $categories = add_indented_names($categories);
1697
3a3c454e 1698 //sort cats out into different contexts
375ed78a 1699 $categoriesarray = array();
3a3c454e 1700 foreach ($pcontexts as $pcontext){
1701 $contextstring = print_context_name(get_context_instance_by_id($pcontext), true, true);
1702 foreach ($categories as $category) {
1703 if ($category->contextid == $pcontext){
1704 $cid = $category->id;
1705 if ($currentcat!= $cid) {
d92b9d91 1706 $countstring = (!empty($category->questioncount))?"($category->questioncount)":'';
1707 $categoriesarray[$contextstring][$cid] = $category->indentedname.$countstring;
3a3c454e 1708 }
1709 }
375ed78a 1710 }
1711 }
3a3c454e 1712 if ($popupform){
1713 $popupcats = array();
1714 foreach ($categoriesarray as $contextstring => $optgroup){
1715 $popupcats[] = '--'.$contextstring;
1716 $popupcats = array_merge($popupcats, $optgroup);
1717 $popupcats[] = '--';
1718 }
1719 return $popupcats;
1720 } else {
1721 return $categoriesarray;
1722 }
375ed78a 1723}
1724
3a3c454e 1725function question_add_context_in_key($categories){
1726 $newcatarray = array();
1727 foreach ($categories as $id => $category) {
1728 $category->parent = "$category->parent,$category->contextid";
1729 $category->id = "$category->id,$category->contextid";
1730 $newcatarray["$id,$category->contextid"] = $category;
1731 }
1732 return $newcatarray;
1733}
1734function question_add_tops($categories, $pcontexts){
1735 $topcats = array();
1736 foreach ($pcontexts as $context){
1737 $newcat = new object();
1738 $newcat->id = "0,$context";
1739 $newcat->name = get_string('top');
1740 $newcat->parent = -1;
1741 $newcat->contextid = $context;
1742 $topcats["0,$context"] = $newcat;
516cf3eb 1743 }
3a3c454e 1744 //put topcats in at beginning of array - they'll be sorted into different contexts later.
1745 return array_merge($topcats, $categories);
516cf3eb 1746}
1747
516cf3eb 1748/**
b20ea669 1749 * Returns a comma separated list of ids of the category and all subcategories
1750 */
dc1f00de 1751function question_categorylist($categoryid) {
516cf3eb 1752 // returns a comma separated list of ids of the category and all subcategories
1753 $categorylist = $categoryid;
dc1f00de 1754 if ($subcategories = get_records('question_categories', 'parent', $categoryid, 'sortorder ASC', 'id, id')) {
516cf3eb 1755 foreach ($subcategories as $subcategory) {
dc1f00de 1756 $categorylist .= ','. question_categorylist($subcategory->id);
516cf3eb 1757 }
1758 }
1759 return $categorylist;
1760}
1761
f5c15407 1762
3a3c454e 1763
516cf3eb 1764
947217d7 1765//===========================
1766// Import/Export Functions
1767//===========================
1768
ff4b6492 1769/**
1770 * Get list of available import or export formats
1771 * @param string $type 'import' if import list, otherwise export list assumed
271ffe3f 1772 * @return array sorted list of import/export formats available
ff4b6492 1773**/
1774function get_import_export_formats( $type ) {
1775
1776 global $CFG;
dc1f00de 1777 $fileformats = get_list_of_plugins("question/format");
ff4b6492 1778
1779 $fileformatname=array();
947217d7 1780 require_once( "{$CFG->dirroot}/question/format.php" );
ff4b6492 1781 foreach ($fileformats as $key => $fileformat) {
1782 $format_file = $CFG->dirroot . "/question/format/$fileformat/format.php";
1783 if (file_exists( $format_file ) ) {
1784 require_once( $format_file );
1785 }
1786 else {
1787 continue;
1788 }
70c01adb 1789 $classname = "qformat_$fileformat";
ff4b6492 1790 $format_class = new $classname();
1791 if ($type=='import') {
1792 $provided = $format_class->provide_import();
1793 }
1794 else {
1795 $provided = $format_class->provide_export();
1796 }
1797 if ($provided) {
1798 $formatname = get_string($fileformat, 'quiz');
1799 if ($formatname == "[[$fileformat]]") {
1800 $formatname = $fileformat; // Just use the raw folder name
1801 }
1802 $fileformatnames[$fileformat] = $formatname;
1803 }
1804 }
1805 natcasesort($fileformatnames);
1806
1807 return $fileformatnames;
1808}
feb60a07 1809
1810
1811/**
1812* Create default export filename
1813*
1814* @return string default export filename
1815* @param object $course
1816* @param object $category
1817*/
1818function default_export_filename($course,$category) {
1819 //Take off some characters in the filename !!
1820 $takeoff = array(" ", ":", "/", "\\", "|");
57f1b914 1821 $export_word = str_replace($takeoff,"_",moodle_strtolower(get_string("exportfilename","quiz")));
feb60a07 1822 //If non-translated, use "export"
1823 if (substr($export_word,0,1) == "[") {
1824 $export_word= "export";
1825 }
1826
1827 //Calculate the date format string
1828 $export_date_format = str_replace(" ","_",get_string("exportnameformat","quiz"));
1829 //If non-translated, use "%Y%m%d-%H%M"
1830 if (substr($export_date_format,0,1) == "[") {
1831 $export_date_format = "%%Y%%m%%d-%%H%%M";
1832 }
1833
1834 //Calculate the shortname
1835 $export_shortname = clean_filename($course->shortname);
1836 if (empty($export_shortname) or $export_shortname == '_' ) {
1837 $export_shortname = $course->id;
1838 }
1839
1840 //Calculate the category name
1841 $export_categoryname = clean_filename($category->name);
1842
1843 //Calculate the final export filename
1844 //The export word
1845 $export_name = $export_word."-";
1846 //The shortname
57f1b914 1847 $export_name .= moodle_strtolower($export_shortname)."-";
feb60a07 1848 //The category name
57f1b914 1849 $export_name .= moodle_strtolower($export_categoryname)."-";
feb60a07 1850 //The date format
1851 $export_name .= userdate(time(),$export_date_format,99,false);
1852 //The extension - no extension, supplied by format
1853 // $export_name .= ".txt";
1854
1855 return $export_name;
1856}
1857
f5c15407 1858?>