MDL-11510 added missing fields in new gradebook backup
[moodle-pu.git] / question / restorelib.php
blob72f88e28ef104b96635d5e7e5056d538ee9ce6d3
1 <?php //$Id$
2 /**
3 * Question bank restore code.
5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6 * @package questionbank
7 *//** */
9 // Todo:
10 // the restoration of the parent and sortorder fields in the category table needs
11 // a lot more thought. We should probably use a library function to add the category
12 // rather than just writing it to the database
14 // whereever it says "/// We have to recode the .... field" we should put in a check
15 // to see if the recoding was successful and throw an appropriate error otherwise
17 //This is the "graphical" structure of the question database:
18 //To see, put your terminal to 160cc
20 // The following holds student-independent information about the questions
22 // question_categories
23 // (CL,pk->id)
24 // |
25 // |
26 // |.......................................
27 // | .
28 // | .
29 // | -------question_datasets------ .
30 // | | (CL,pk->id,fk->question, | .
31 // | | fk->dataset_definition) | .
32 // | | | .
33 // | | | .
34 // | | | .
35 // | | question_dataset_definitions
36 // | | (CL,pk->id,fk->category)
37 // question |
38 // (CL,pk->id,fk->category,files) |
39 // | question_dataset_items
40 // | (CL,pk->id,fk->definition)
41 // |
42 // |
43 // |
44 // --------------------------------------------------------------------------------------------------------------
45 // | | | | | | |
46 // | | | | | | |
47 // | | | | question_calculated | |
48 // question_truefalse | question_multichoice | (CL,pl->id,fk->question) | |
49 // (CL,pk->id,fk->question) | (CL,pk->id,fk->question) | . | | question_randomsamatch
50 // . | . | . | |--(CL,pk->id,fk->question)
51 // . question_shortanswer . question_numerical . question_multianswer. |
52 // . (CL,pk->id,fk->question) . (CL,pk->id,fk->question) . (CL,pk->id,fk->question) |
53 // . . . . . . | question_match
54 // . . . . . . |--(CL,pk->id,fk->question)
55 // . . . . . . | .
56 // . . . . . . | .
57 // . . . . . . | .
58 // . . . . . . | question_match_sub
59 // ........................................................................................ |--(CL,pk->id,fk->question)
60 // . |
61 // . |
62 // . | question_numerical_units
63 // question_answers |--(CL,pk->id,fk->question)
64 // (CL,pk->id,fk->question)----------------------------------------------------------
67 // The following holds the information about student interaction with the questions
69 // question_sessions
70 // (UL,pk->id,fk->attempt,question)
71 // .
72 // .
73 // question_states
74 // (UL,pk->id,fk->attempt,question)
76 // Meaning: pk->primary key field of the table
77 // fk->foreign key to link with parent
78 // nt->nested field (recursive data)
79 // SL->site level info
80 // CL->course level info
81 // UL->user level info
82 // files->table may have files
84 //-----------------------------------------------------------
86 include_once($CFG->libdir.'/questionlib.php');
88 /**
89 * Returns the best question category (id) found to restore one
90 * question category from a backup file. Works by stamp.
92 * @param object $restore preferences for restoration
93 * @param array $contextinfo fragment of decoded xml
94 * @return object best context instance for this category to be in
96 function restore_question_get_best_category_context($restore, $contextinfo) {
97 switch ($contextinfo['LEVEL'][0]['#']) {
98 case 'module':
99 $instanceinfo = backup_getid($restore->backup_unique_code, 'course_modules', $contextinfo['INSTANCE'][0]['#']);
100 $tocontext = get_context_instance(CONTEXT_MODULE, $instanceinfo->new_id);
101 break;
102 case 'course':
103 $tocontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
104 break;
105 case 'coursecategory':
106 //search COURSECATEGORYLEVEL steps up the course cat tree or
107 //to the top of the tree if steps are exhausted.
108 $catno = $contextinfo['COURSECATEGORYLEVEL'][0]['#'];
109 $catid = get_field('course', 'parent', 'id', $restore->course_id);
110 while ($catno > 1){
111 $nextcatid = get_field('course_categories', 'parent', 'id', $catid);
112 if ($nextcatid == 0){
113 break;
115 $catid == $nextcatid;
116 $catno--;
118 $tocontext = get_context_instance(CONTEXT_COURSECAT, $catid);
119 break;
120 case 'system':
121 $tocontext = get_context_instance(CONTEXT_SYSTEM);
122 break;
124 return $tocontext;
127 function restore_question_categories($info, $restore) {
128 $status = true;
129 //Iterate over each category
130 foreach ($info as $category) {
131 $status = $status && restore_question_category($category, $restore);
133 $status = $status && restore_recode_category_parents($restore);
134 return $status;
137 function restore_question_category($category, $restore){
138 $status = true;
139 //Skip empty categories (some backups can contain them)
140 if (!empty($category->id)) {
141 //Get record from backup_ids
142 $data = backup_getid($restore->backup_unique_code, "question_categories", $category->id);
144 if ($data) {
145 //Now get completed xmlized object
146 $info = $data->info;
147 //traverse_xmlize($info); //Debug
148 //print_object ($GLOBALS['traverse_array']); //Debug
149 //$GLOBALS['traverse_array']=""; //Debug
151 //Now, build the question_categories record structure
152 $question_cat = new stdClass;
153 $question_cat->name = backup_todb($info['QUESTION_CATEGORY']['#']['NAME']['0']['#']);
154 $question_cat->info = backup_todb($info['QUESTION_CATEGORY']['#']['INFO']['0']['#']);
155 $question_cat->stamp = backup_todb($info['QUESTION_CATEGORY']['#']['STAMP']['0']['#']);
156 //parent is fixed after all categories are restored and we know all the new ids.
157 $question_cat->parent = backup_todb($info['QUESTION_CATEGORY']['#']['PARENT']['0']['#']);
158 $question_cat->sortorder = backup_todb($info['QUESTION_CATEGORY']['#']['SORTORDER']['0']['#']);
159 if (!$question_cat->stamp) {
160 $question_cat->stamp = make_unique_id_code();
162 if (isset($info['QUESTION_CATEGORY']['#']['PUBLISH'])) {
163 $course = $restore->course_id;
164 $publish = backup_todb($info['QUESTION_CATEGORY']['#']['PUBLISH']['0']['#']);
165 if ($publish){
166 $tocontext = get_context_instance(CONTEXT_SYSTEM);
167 } else {
168 $tocontext = get_context_instance(CONTEXT_COURSE, $course);
170 } else {
171 $tocontext = restore_question_get_best_category_context($restore, $info['QUESTION_CATEGORY']['#']['CONTEXT']['0']['#']);
173 $question_cat->contextid = $tocontext->id;
175 //does cat exist ?? if it does we check if the cat and questions already exist whether we have
176 //add permission or not if we have no permission to add questions to SYSTEM or COURSECAT context
177 //AND the question does not already exist then we create questions in COURSE context.
178 if (!$fcat = get_record('question_categories','contextid', $question_cat->contextid, 'stamp', $question_cat->stamp)){
179 //no preexisting cat
180 if ((($tocontext->contextlevel == CONTEXT_SYSTEM) || ($tocontext->contextlevel == CONTEXT_COURSECAT))
181 && !has_capability('moodle/question:add', $tocontext)){
182 //no preexisting cat and no permission to create questions here
183 //must restore to course.
184 $tocontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
186 $question_cat->contextid = $tocontext->id;
187 if (!$fcat = get_record('question_categories','contextid', $question_cat->contextid, 'stamp', $question_cat->stamp)){
188 $question_cat->id = insert_record ("question_categories", $question_cat);
189 } else {
190 $question_cat = $fcat;
192 //we'll be restoring all questions here.
193 backup_putid($restore->backup_unique_code, "question_categories", $category->id, $question_cat->id);
194 } else {
195 $question_cat = $fcat;
196 //we found an existing best category
197 //but later if context is above course need to check if there are questions need creating in category
198 //if we do need to create questions and permissions don't allow it create new category in course
201 //Do some output
202 if (!defined('RESTORE_SILENTLY')) {
203 echo "<li>".get_string('category', 'quiz')." \"".$question_cat->name."\"<br />";
206 backup_flush(300);
208 //start with questions
209 if ($question_cat->id) {
210 //We have the newid, update backup_ids
211 //Now restore question
212 $status = restore_questions($category->id, $question_cat, $info, $restore);
213 } else {
214 $status = false;
216 if (!defined('RESTORE_SILENTLY')) {
217 echo '</li>';
219 } else {
220 echo 'Could not get backup info for question category'. $category->id;
223 return $status;
226 function restore_recode_category_parents($restore){
227 global $CFG;
228 $status = true;
229 //Now we have to recode the parent field of each restored category
230 $categories = get_records_sql("SELECT old_id, new_id
231 FROM {$CFG->prefix}backup_ids
232 WHERE backup_code = $restore->backup_unique_code AND
233 table_name = 'question_categories'");
234 if ($categories) {
235 //recode all parents to point at their old parent cats no matter what context the parent is now in
236 foreach ($categories as $category) {
237 $restoredcategory = get_record('question_categories','id',$category->new_id);
238 if ($restoredcategory->parent != 0) {
239 $updateobj = new object();
240 $updateobj->id = $restoredcategory->id;
241 $idcat = backup_getid($restore->backup_unique_code,'question_categories',$restoredcategory->parent);
242 if ($idcat->new_id) {
243 $updateobj->parent = $idcat->new_id;
244 } else {
245 $updateobj->parent = 0;
247 $status = $status && update_record('question_categories', $updateobj);
250 //now we have recoded all parents, check through all parents and set parent to be
251 //grand parent / great grandparent etc where there is one in same context
252 //or else set parent to 0 (top level category).
253 $toupdate = array();
254 foreach ($categories as $category) {
255 $restoredcategory = get_record('question_categories','id',$category->new_id);
256 if ($restoredcategory->parent != 0) {
257 $nextparentid = $restoredcategory->parent;
258 do {
259 if (!$parent = get_record('question_categories', 'id', $nextparentid)){
260 if (!defined('RESTORE_SILENTLY')) {
261 echo 'Could not find parent for question category '. $category->id.' recoding as top category item.<br />';
263 break;//record fetch failed finish loop
264 } else {
265 $nextparentid = $nextparent->parent;
267 } while (($nextparentid != 0) && ($parent->contextid != $restoredcategory->contextid));
268 if (!$parent || ($parent->id != $restoredcategory->parent)){
269 //change needs to be made to the parent field.
270 if ($parent && ($parent->contextid == $restoredcategory->contextid)){
271 $toupdate[$restoredcategory->id] = $parent->id;
272 } else {
273 //searched up the tree till we came to the top and did not find cat in same
274 //context or there was an error getting next parent record
275 $toupdate[$restoredcategory->id] = 0;
280 //now finally do the changes to parent field.
281 foreach ($toupdate as $id => $parent){
282 $updateobj = new object();
283 $updateobj->id = $id;
284 $updateobj->parent = $parent;
285 $status = $status && update_record('question_categories', $updateobj);
288 return $status;
291 function restore_questions ($old_category_id, $best_question_cat, $info, $restore) {
293 global $CFG, $QTYPES;
295 $status = true;
296 $restored_questions = array();
298 //Get the questions array
299 if (!empty($info['QUESTION_CATEGORY']['#']['QUESTIONS'])) {
300 $questions = $info['QUESTION_CATEGORY']['#']['QUESTIONS']['0']['#']['QUESTION'];
301 } else {
302 $questions = array();
305 //Iterate over questions
306 for($i = 0; $i < sizeof($questions); $i++) {
307 $que_info = $questions[$i];
308 //traverse_xmlize($que_info); //Debug
309 //print_object ($GLOBALS['traverse_array']); //Debug
310 //$GLOBALS['traverse_array']=""; //Debug
312 //We'll need this later!!
313 $oldid = backup_todb($que_info['#']['ID']['0']['#']);
315 //Now, build the question record structure
316 $question = new object;
317 $question->parent = backup_todb($que_info['#']['PARENT']['0']['#']);
318 $question->name = backup_todb($que_info['#']['NAME']['0']['#']);
319 $question->questiontext = backup_todb($que_info['#']['QUESTIONTEXT']['0']['#']);
320 $question->questiontextformat = backup_todb($que_info['#']['QUESTIONTEXTFORMAT']['0']['#']);
321 $question->image = backup_todb($que_info['#']['IMAGE']['0']['#']);
322 $question->generalfeedback = backup_todb_optional_field($que_info, 'GENERALFEEDBACK', '');
323 $question->defaultgrade = backup_todb($que_info['#']['DEFAULTGRADE']['0']['#']);
324 $question->penalty = backup_todb($que_info['#']['PENALTY']['0']['#']);
325 $question->qtype = backup_todb($que_info['#']['QTYPE']['0']['#']);
326 $question->length = backup_todb($que_info['#']['LENGTH']['0']['#']);
327 $question->stamp = backup_todb($que_info['#']['STAMP']['0']['#']);
328 $question->version = backup_todb($que_info['#']['VERSION']['0']['#']);
329 $question->hidden = backup_todb($que_info['#']['HIDDEN']['0']['#']);
330 $question->timecreated = backup_todb_optional_field($que_info, 'TIMECREATED', 0);
331 $question->timemodified = backup_todb_optional_field($que_info, 'TIMEMODIFIED', 0);
332 $question->createdby = backup_todb_optional_field($que_info, 'CREATEDBY', null);
333 $question->modifiedby = backup_todb_optional_field($que_info, 'MODIFIEDBY', null);
335 if ($restore->backup_version < 2006032200) {
336 // The qtype was an integer that now needs to be converted to the name
337 $qtypenames = array(1=>'shortanswer',2=>'truefalse',3=>'multichoice',4=>'random',5=>'match',
338 6=>'randomsamatch',7=>'description',8=>'numerical',9=>'multianswer',10=>'calculated',
339 11=>'rqp',12=>'essay');
340 $question->qtype = $qtypenames[$question->qtype];
343 //Check if the question exists by category, stamp, and version
344 //first check for the question in the context specified in backup
345 $existingquestion = get_record ("question", "category", $best_question_cat->id, "stamp", $question->stamp,"version",$question->version);
346 //If the question exists, only record its id
347 //always use existing question, no permissions check here
348 if ($existingquestion) {
349 $question = $existingquestion;
350 $creatingnewquestion = false;
351 } else {
352 //then if context above course level check permissions and if no permission
353 //to restore above course level then restore to cat in course context.
354 $bestcontext = get_context_instance_by_id($best_question_cat->contextid);
355 if (($bestcontext->contextlevel == CONTEXT_SYSTEM || $bestcontext->contextlevel == CONTEXT_COURSECAT)
356 && !has_capability('moodle/question:add', $bestcontext)){
357 if (!isset($course_question_cat)) {
358 $coursecontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
359 $course_question_cat = clone($best_question_cat);
360 $course_question_cat->contextid = $coursecontext->id;
361 //create cat if it doesn't exist
362 if (!$fcat = get_record('question_categories','contextid', $course_question_cat->contextid, 'stamp', $course_question_cat->stamp)){
363 $course_question_cat->id = insert_record ("question_categories", $course_question_cat);
364 backup_putid($restore->backup_unique_code, "question_categories", $old_category_id, $course_question_cat->id);
365 } else {
366 $course_question_cat = $fcat;
368 //will fix category parents after all questions and categories restored. Will set parent to 0 if
369 //no parent in same context.
371 $question->category = $course_question_cat->id;
372 //does question already exist in course cat
373 $existingquestion = get_record ("question", "category", $question->category, "stamp", $question->stamp, "version", $question->version);
374 } else {
375 //permissions ok, restore to best cat
376 $question->category = $best_question_cat->id;
378 if (!$existingquestion){
379 //The structure is equal to the db, so insert the question
380 $question->id = insert_record ("question", $question);
381 $creatingnewquestion = true;
382 } else {
383 $question = $existingquestion;
384 $creatingnewquestion = false;
388 //Save newid to backup tables
389 if ($question->id) {
390 //We have the newid, update backup_ids
391 backup_putid($restore->backup_unique_code, "question", $oldid, $question->id);
394 $restored_questions[$i] = new stdClass;
395 $restored_questions[$i]->newid = $question->id;
396 $restored_questions[$i]->oldid = $oldid;
397 $restored_questions[$i]->qtype = $question->qtype;
398 $restored_questions[$i]->parent = $question->parent;
399 $restored_questions[$i]->is_new = $creatingnewquestion;
401 backup_flush(300);
403 // Loop again, now all the question id mappings exist, so everything can
404 // be restored.
405 for($i = 0; $i < sizeof($questions); $i++) {
406 $que_info = $questions[$i];
408 $newid = $restored_questions[$i]->newid;
409 $oldid = $restored_questions[$i]->oldid;
411 $question = new object;
412 $question->qtype = $restored_questions[$i]->qtype;
413 $question->parent = $restored_questions[$i]->parent;
416 //If it's a new question in the DB, restore it
417 if ($restored_questions[$i]->is_new) {
419 ////We have to recode the parent field
420 if ($question->parent) {
421 if ($parent = backup_getid($restore->backup_unique_code,"question",$question->parent)) {
422 $question->parent = $parent->new_id;
423 } elseif ($question->parent = $oldid) {
424 $question->parent = $newid;
425 } else {
426 echo 'Could not recode parent '.$question->parent.' for question '.$oldid.'<br />';
430 //Now, restore every question_answers in this question
431 $status = question_restore_answers($oldid,$newid,$que_info,$restore);
432 // Restore questiontype specific data
433 if (array_key_exists($question->qtype, $QTYPES)) {
434 $status = $QTYPES[$question->qtype]->restore($oldid,$newid,$que_info,$restore);
435 } else {
436 echo 'Unknown question type '.$question->qtype.' for question '.$oldid.'<br />';
437 $status = false;
439 } else {
440 //We are NOT creating the question, but we need to know every question_answers
441 //map between the XML file and the database to be able to restore the states
442 //in each attempt.
443 $status = question_restore_map_answers($oldid,$newid,$que_info,$restore);
444 // Do the questiontype specific mapping
445 if (array_key_exists($question->qtype, $QTYPES)) {
446 $status = $QTYPES[$question->qtype]->restore_map($oldid,$newid,$que_info,$restore);
447 } else {
448 echo 'Unknown question type '.$question->qtype.' for question '.$oldid.'<br />';
449 $status = false;
453 //Do some output
454 if (($i+1) % 2 == 0) {
455 if (!defined('RESTORE_SILENTLY')) {
456 echo ".";
457 if (($i+1) % 40 == 0) {
458 echo "<br />";
461 backup_flush(300);
464 return $status;
467 function backup_todb_optional_field($data, $field, $default) {
468 if (array_key_exists($field, $data['#'])) {
469 return backup_todb($data['#'][$field]['0']['#']);
470 } else {
471 return $default;
475 function question_restore_answers ($old_question_id,$new_question_id,$info,$restore) {
477 global $CFG;
479 $status = true;
480 $qtype = backup_todb($info['#']['QTYPE']['0']['#']);
482 //Get the answers array
483 if (isset($info['#']['ANSWERS']['0']['#']['ANSWER'])) {
484 $answers = $info['#']['ANSWERS']['0']['#']['ANSWER'];
486 //Iterate over answers
487 for($i = 0; $i < sizeof($answers); $i++) {
488 $ans_info = $answers[$i];
489 //traverse_xmlize($ans_info); //Debug
490 //print_object ($GLOBALS['traverse_array']); //Debug
491 //$GLOBALS['traverse_array']=""; //Debug
493 //We'll need this later!!
494 $oldid = backup_todb($ans_info['#']['ID']['0']['#']);
496 //Now, build the question_answers record structure
497 $answer = new stdClass;
498 $answer->question = $new_question_id;
499 $answer->answer = backup_todb($ans_info['#']['ANSWER_TEXT']['0']['#']);
500 $answer->fraction = backup_todb($ans_info['#']['FRACTION']['0']['#']);
501 $answer->feedback = backup_todb($ans_info['#']['FEEDBACK']['0']['#']);
503 // Update 'match everything' answers for numerical questions coming from old backup files.
504 if ($qtype == 'numerical' && $answer->answer == '') {
505 $answer->answer = '*';
508 //The structure is equal to the db, so insert the question_answers
509 $newid = insert_record ("question_answers",$answer);
511 //Do some output
512 if (($i+1) % 50 == 0) {
513 if (!defined('RESTORE_SILENTLY')) {
514 echo ".";
515 if (($i+1) % 1000 == 0) {
516 echo "<br />";
519 backup_flush(300);
522 if ($newid) {
523 //We have the newid, update backup_ids
524 backup_putid($restore->backup_unique_code,"question_answers",$oldid,
525 $newid);
526 } else {
527 $status = false;
532 return $status;
535 function question_restore_map_answers ($old_question_id,$new_question_id,$info,$restore) {
537 global $CFG;
539 $status = true;
541 if (!isset($info['#']['ANSWERS'])) { // No answers in this question (eg random)
542 return $status;
545 //Get the answers array
546 $answers = $info['#']['ANSWERS']['0']['#']['ANSWER'];
548 //Iterate over answers
549 for($i = 0; $i < sizeof($answers); $i++) {
550 $ans_info = $answers[$i];
551 //traverse_xmlize($ans_info); //Debug
552 //print_object ($GLOBALS['traverse_array']); //Debug
553 //$GLOBALS['traverse_array']=""; //Debug
555 //We'll need this later!!
556 $oldid = backup_todb($ans_info['#']['ID']['0']['#']);
558 //Now, build the question_answers record structure
559 $answer->question = $new_question_id;
560 $answer->answer = backup_todb($ans_info['#']['ANSWER_TEXT']['0']['#']);
561 $answer->fraction = backup_todb($ans_info['#']['FRACTION']['0']['#']);
562 $answer->feedback = backup_todb($ans_info['#']['FEEDBACK']['0']['#']);
564 //If we are in this method is because the question exists in DB, so its
565 //answers must exist too.
566 //Now, we are going to look for that answer in DB and to create the
567 //mappings in backup_ids to use them later where restoring states (user level).
569 //Get the answer from DB (by question and answer)
570 $db_answer = get_record ("question_answers","question",$new_question_id,
571 "answer",$answer->answer);
573 //Do some output
574 if (($i+1) % 50 == 0) {
575 if (!defined('RESTORE_SILENTLY')) {
576 echo ".";
577 if (($i+1) % 1000 == 0) {
578 echo "<br />";
581 backup_flush(300);
584 if ($db_answer) {
585 //We have the database answer, update backup_ids
586 backup_putid($restore->backup_unique_code,"question_answers",$oldid,
587 $db_answer->id);
588 } else {
589 $status = false;
593 return $status;
596 function question_restore_numerical_units($old_question_id,$new_question_id,$info,$restore) {
598 global $CFG;
600 $status = true;
602 //Get the numerical array
603 if (!empty($info['#']['NUMERICAL_UNITS'])) {
604 $numerical_units = $info['#']['NUMERICAL_UNITS']['0']['#']['NUMERICAL_UNIT'];
605 } else {
606 $numerical_units = array();
609 //Iterate over numerical_units
610 for($i = 0; $i < sizeof($numerical_units); $i++) {
611 $nu_info = $numerical_units[$i];
612 //traverse_xmlize($nu_info); //Debug
613 //print_object ($GLOBALS['traverse_array']); //Debug
614 //$GLOBALS['traverse_array']=""; //Debug
616 // Check to see if this until already exists in the database, which it might, for
617 // Historical reasons.
618 $unit = backup_todb($nu_info['#']['UNIT']['0']['#']);
619 if (!record_exists('question_numerical_units', 'question', $new_question_id, 'unit', $unit)) {
621 //Now, build the question_numerical_UNITS record structure.
622 $numerical_unit = new stdClass;
623 $numerical_unit->question = $new_question_id;
624 $numerical_unit->multiplier = backup_todb($nu_info['#']['MULTIPLIER']['0']['#']);
625 $numerical_unit->unit = $unit;
627 //The structure is equal to the db, so insert the question_numerical_units
628 $newid = insert_record("question_numerical_units", $numerical_unit);
630 if (!$newid) {
631 $status = false;
636 return $status;
639 function question_restore_dataset_definitions ($old_question_id,$new_question_id,$info,$restore) {
641 global $CFG;
643 $status = true;
645 //Get the dataset_definitions array
646 $dataset_definitions = $info['#']['DATASET_DEFINITIONS']['0']['#']['DATASET_DEFINITION'];
648 //Iterate over dataset_definitions
649 for($i = 0; $i < sizeof($dataset_definitions); $i++) {
650 $dd_info = $dataset_definitions[$i];
651 //traverse_xmlize($dd_info); //Debug
652 //print_object ($GLOBALS['traverse_array']); //Debug
653 //$GLOBALS['traverse_array']=""; //Debug
655 //Now, build the question_dataset_DEFINITION record structure
656 $dataset_definition = new stdClass;
657 $dataset_definition->category = backup_todb($dd_info['#']['CATEGORY']['0']['#']);
658 $dataset_definition->name = backup_todb($dd_info['#']['NAME']['0']['#']);
659 $dataset_definition->type = backup_todb($dd_info['#']['TYPE']['0']['#']);
660 $dataset_definition->options = backup_todb($dd_info['#']['OPTIONS']['0']['#']);
661 $dataset_definition->itemcount = backup_todb($dd_info['#']['ITEMCOUNT']['0']['#']);
663 //We have to recode the category field (only if the category != 0)
664 if ($dataset_definition->category != 0) {
665 $category = backup_getid($restore->backup_unique_code,"question_categories",$dataset_definition->category);
666 if ($category) {
667 $dataset_definition->category = $category->new_id;
668 } else {
669 echo 'Could not recode category id '.$dataset_definition->category.' for dataset definition'.$dataset_definition->name.'<br />';
673 //Now, we hace to decide when to create the new records or reuse an existing one
674 $create_definition = false;
676 //If the dataset_definition->category = 0, it's a individual question dataset_definition, so we'll create it
677 if ($dataset_definition->category == 0) {
678 $create_definition = true;
679 } else {
680 //The category isn't 0, so it's a category question dataset_definition, we have to see if it exists
681 //Look for a definition with the same category, name and type
682 if ($definitionrec = get_record_sql("SELECT d.*
683 FROM {$CFG->prefix}question_dataset_definitions d
684 WHERE d.category = '$dataset_definition->category' AND
685 d.name = '$dataset_definition->name' AND
686 d.type = '$dataset_definition->type'")) {
687 //Such dataset_definition exist. Now we must check if it has enough itemcount
688 if ($definitionrec->itemcount < $dataset_definition->itemcount) {
689 //We haven't enough itemcount, so we have to create the definition as an individual question one.
690 $dataset_definition->category = 0;
691 $create_definition = true;
692 } else {
693 //We have enough itemcount, so we'll reuse the existing definition
694 $create_definition = false;
695 $newid = $definitionrec->id;
697 } else {
698 //Such dataset_definition doesn't exist. We'll create it.
699 $create_definition = true;
703 //If we've to create the definition, do it
704 if ($create_definition) {
705 //The structure is equal to the db, so insert the question_dataset_definitions
706 $newid = insert_record ("question_dataset_definitions",$dataset_definition);
707 if ($newid) {
708 //Restore question_dataset_items
709 $status = question_restore_dataset_items($newid,$dd_info,$restore);
713 //Now, we must have a definition (created o reused). Its id is in newid. Create the question_datasets record
714 //to join the question and the dataset_definition
715 if ($newid) {
716 $question_dataset = new stdClass;
717 $question_dataset->question = $new_question_id;
718 $question_dataset->datasetdefinition = $newid;
719 $newid = insert_record ("question_datasets",$question_dataset);
722 if (!$newid) {
723 $status = false;
727 return $status;
730 function question_restore_dataset_items ($definitionid,$info,$restore) {
732 global $CFG;
734 $status = true;
736 //Get the items array
737 $dataset_items = $info['#']['DATASET_ITEMS']['0']['#']['DATASET_ITEM'];
739 //Iterate over dataset_items
740 for($i = 0; $i < sizeof($dataset_items); $i++) {
741 $di_info = $dataset_items[$i];
742 //traverse_xmlize($di_info); //Debug
743 //print_object ($GLOBALS['traverse_array']); //Debug
744 //$GLOBALS['traverse_array']=""; //Debug
746 //Now, build the question_dataset_ITEMS record structure
747 $dataset_item = new stdClass;
748 $dataset_item->definition = $definitionid;
749 $dataset_item->itemnumber = backup_todb($di_info['#']['NUMBER']['0']['#']);
750 $dataset_item->value = backup_todb($di_info['#']['VALUE']['0']['#']);
752 //The structure is equal to the db, so insert the question_dataset_items
753 $newid = insert_record ("question_dataset_items",$dataset_item);
755 if (!$newid) {
756 $status = false;
760 return $status;
764 //This function restores the question_states
765 function question_states_restore_mods($attempt_id,$info,$restore) {
767 global $CFG, $QTYPES;
769 $status = true;
771 //Get the question_states array
772 $states = $info['#']['STATES']['0']['#']['STATE'];
773 //Iterate over states
774 for($i = 0; $i < sizeof($states); $i++) {
775 $res_info = $states[$i];
776 //traverse_xmlize($res_info); //Debug
777 //print_object ($GLOBALS['traverse_array']); //Debug
778 //$GLOBALS['traverse_array']=""; //Debug
780 //We'll need this later!!
781 $oldid = backup_todb($res_info['#']['ID']['0']['#']);
783 //Now, build the STATES record structure
784 $state = new stdClass;
785 $state->attempt = $attempt_id;
786 $state->question = backup_todb($res_info['#']['QUESTION']['0']['#']);
787 $state->originalquestion = backup_todb($res_info['#']['ORIGINALQUESTION']['0']['#']);
788 $state->seq_number = backup_todb($res_info['#']['SEQ_NUMBER']['0']['#']);
789 $state->answer = backup_todb($res_info['#']['ANSWER']['0']['#']);
790 $state->timestamp = backup_todb($res_info['#']['TIMESTAMP']['0']['#']);
791 $state->event = backup_todb($res_info['#']['EVENT']['0']['#']);
792 $state->grade = backup_todb($res_info['#']['GRADE']['0']['#']);
793 $state->raw_grade = backup_todb($res_info['#']['RAW_GRADE']['0']['#']);
794 $state->penalty = backup_todb($res_info['#']['PENALTY']['0']['#']);
795 $state->oldid = $oldid; // So it is available to restore_recode_answer.
797 //We have to recode the question field
798 $question = backup_getid($restore->backup_unique_code,"question",$state->question);
799 if ($question) {
800 $state->question = $question->new_id;
801 } else {
802 echo 'Could not recode question id '.$state->question.' for state '.$oldid.'<br />';
805 //We have to recode the originalquestion field if it is nonzero
806 if ($state->originalquestion) {
807 $question = backup_getid($restore->backup_unique_code,"question",$state->originalquestion);
808 if ($question) {
809 $state->originalquestion = $question->new_id;
810 } else {
811 echo 'Could not recode originalquestion id '.$state->question.' for state '.$oldid.'<br />';
815 //We have to recode the answer field
816 //It depends of the question type !!
817 //We get the question first
818 if (!$question = get_record("question","id",$state->question)) {
819 error("Can't find the record for question $state->question for which I am trying to restore a state");
821 //Depending on the qtype, we make different recodes
822 if ($state->answer) {
823 $state->answer = $QTYPES[$question->qtype]->restore_recode_answer($state, $restore);
826 //The structure is equal to the db, so insert the question_states
827 $newid = insert_record ("question_states",$state);
829 //Do some output
830 if (($i+1) % 10 == 0) {
831 if (!defined('RESTORE_SILENTLY')) {
832 echo ".";
833 if (($i+1) % 200 == 0) {
834 echo "<br />";
837 backup_flush(300);
840 if ($newid) {
841 //We have the newid, update backup_ids
842 backup_putid($restore->backup_unique_code, 'question_states', $oldid, $newid);
843 } else {
844 $status = false;
848 //Get the question_sessions array
849 $sessions = $info['#']['NEWEST_STATES']['0']['#']['NEWEST_STATE'];
850 //Iterate over question_sessions
851 for($i = 0; $i < sizeof($sessions); $i++) {
852 $res_info = $sessions[$i];
853 //traverse_xmlize($res_info); //Debug
854 //print_object ($GLOBALS['traverse_array']); //Debug
855 //$GLOBALS['traverse_array']=""; //Debug
857 //Now, build the NEWEST_STATES record structure
858 $session = new stdClass;
859 $session->attemptid = $attempt_id;
860 $session->questionid = backup_todb($res_info['#']['QUESTIONID']['0']['#']);
861 $session->newest = backup_todb($res_info['#']['NEWEST']['0']['#']);
862 $session->newgraded = backup_todb($res_info['#']['NEWGRADED']['0']['#']);
863 $session->sumpenalty = backup_todb($res_info['#']['SUMPENALTY']['0']['#']);
865 if ($res_info['#']['MANUALCOMMENT']['0']['#']) {
866 $session->manualcomment = backup_todb($res_info['#']['MANUALCOMMENT']['0']['#']);
867 } else { // pre 1.7 backups
868 $session->manualcomment = backup_todb($res_info['#']['COMMENT']['0']['#']);
871 //We have to recode the question field
872 $question = backup_getid($restore->backup_unique_code,"question",$session->questionid);
873 if ($question) {
874 $session->questionid = $question->new_id;
875 } else {
876 echo 'Could not recode question id '.$session->questionid.'<br />';
879 //We have to recode the newest field
880 $state = backup_getid($restore->backup_unique_code,"question_states",$session->newest);
881 if ($state) {
882 $session->newest = $state->new_id;
883 } else {
884 echo 'Could not recode newest state id '.$session->newest.'<br />';
887 //If the session has been graded we have to recode the newgraded field
888 if ($session->newgraded) {
889 $state = backup_getid($restore->backup_unique_code,"question_states",$session->newgraded);
890 if ($state) {
891 $session->newgraded = $state->new_id;
892 } else {
893 echo 'Could not recode newest graded state id '.$session->newgraded.'<br />';
897 //The structure is equal to the db, so insert the question_sessions
898 $newid = insert_record ("question_sessions",$session);
902 return $status;
906 * Recode content links in question texts.
907 * @param object $restore the restore metadata object.
908 * @return boolean whether the operation succeeded.
910 function question_decode_content_links_caller($restore) {
911 global $CFG, $QTYPES;
912 $status = true;
913 $i = 1; //Counter to send some output to the browser to avoid timeouts
915 // Get a list of which question types have custom field that will need decoding.
916 $qtypeswithextrafields = array();
917 $qtypeswithhtmlanswers = array();
918 foreach ($QTYPES as $qtype => $qtypeclass) {
919 $qtypeswithextrafields[$qtype] = method_exists($qtypeclass, 'decode_content_links_caller');
920 $qtypeswithhtmlanswers[$qtype] = $qtypeclass->has_html_answers();
922 $extraprocessing = array();
924 $coursemodulecontexts = array();
925 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
926 $coursemodulecontexts[] = $context->id;
927 $cms = get_records('course_modules', 'course', $restore->course_id, '', 'id');
928 if ($cms){
929 foreach ($cms as $cm){
930 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
931 $coursemodulecontexts[] = $context->id;
934 $coursemodulecontextslist = join($coursemodulecontexts, ',');
935 // Decode links in questions.
936 if ($questions = get_records_sql('SELECT q.id, q.qtype, q.questiontext, q.generalfeedback '.
937 'FROM ' . $CFG->prefix . 'question q, '.
938 $CFG->prefix . 'question_categories qc '.
939 'WHERE q.category = qc.id '.
940 'AND qc.contextid IN (' .$coursemodulecontextslist.')')) {
942 foreach ($questions as $question) {
943 $questiontext = restore_decode_content_links_worker($question->questiontext, $restore);
944 $generalfeedback = restore_decode_content_links_worker($question->generalfeedback, $restore);
945 if ($questiontext != $question->questiontext || $generalfeedback != $question->generalfeedback) {
946 $question->questiontext = addslashes($questiontext);
947 $question->generalfeedback = addslashes($generalfeedback);
948 if (!update_record('question', $question)) {
949 $status = false;
953 // Do some output.
954 if (++$i % 5 == 0 && !defined('RESTORE_SILENTLY')) {
955 echo ".";
956 if ($i % 100 == 0) {
957 echo "<br />";
959 backup_flush(300);
962 // Decode any questiontype specific fields.
963 if ($qtypeswithextrafields[$question->qtype]) {
964 if (!array_key_exists($question->qtype, $extraprocessing)) {
965 $extraprocessing[$question->qtype] = array();
967 $extraprocessing[$question->qtype][] = $question->id;
972 // Decode links in answers.
973 if ($answers = get_records_sql('SELECT qa.id, qa.answer, qa.feedback, q.qtype
974 FROM ' . $CFG->prefix . 'question_answers qa,
975 ' . $CFG->prefix . 'question q,
976 ' . $CFG->prefix . 'question_categories qc
977 WHERE qa.question = q.id
978 AND q.category = qc.id '.
979 'AND qc.contextid IN ('.$coursemodulecontextslist.')')) {
981 foreach ($answers as $answer) {
982 $feedback = restore_decode_content_links_worker($answer->feedback, $restore);
983 if ($qtypeswithhtmlanswers[$answer->qtype]) {
984 $answertext = restore_decode_content_links_worker($answer->answer, $restore);
985 } else {
986 $answertext = $answer->answer;
988 if ($feedback != $answer->feedback || $answertext != $answer->answer) {
989 unset($answer->qtype);
990 $answer->feedback = addslashes($feedback);
991 $answer->answer = addslashes($answertext);
992 if (!update_record('question_answers', $answer)) {
993 $status = false;
997 // Do some output.
998 if (++$i % 5 == 0 && !defined('RESTORE_SILENTLY')) {
999 echo ".";
1000 if ($i % 100 == 0) {
1001 echo "<br />";
1003 backup_flush(300);
1008 // Do extra work for certain question types.
1009 foreach ($extraprocessing as $qtype => $questionids) {
1010 if (!$QTYPES[$qtype]->decode_content_links_caller($questionids, $restore, $i)) {
1011 $status = false;
1015 return $status;