Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / backup / restorelib.php
blob112bc8e83dc1a7fad72013fe7d6ada64fa5de7ec
1 <?php //$Id$
2 //Functions used in restore
4 require_once($CFG->libdir.'/gradelib.php');
6 /**
7 * Group backup/restore constants, 0.
8 */
9 define('RESTORE_GROUPS_NONE', 0);
11 /**
12 * Group backup/restore constants, 1.
14 define('RESTORE_GROUPS_ONLY', 1);
16 /**
17 * Group backup/restore constants, 2.
19 define('RESTORE_GROUPINGS_ONLY', 2);
21 /**
22 * Group backup/restore constants, course/all.
24 define('RESTORE_GROUPS_GROUPINGS', 3);
26 //This function unzips a zip file in the same directory that it is
27 //It automatically uses pclzip or command line unzip
28 function restore_unzip ($file) {
30 return unzip_file($file, '', false);
34 //This function checks if moodle.xml seems to be a valid xml file
35 //(exists, has an xml header and a course main tag
36 function restore_check_moodle_file ($file) {
38 $status = true;
40 //Check if it exists
41 if ($status = is_file($file)) {
42 //Open it and read the first 200 bytes (chars)
43 $handle = fopen ($file, "r");
44 $first_chars = fread($handle,200);
45 $status = fclose ($handle);
46 //Chek if it has the requires strings
47 if ($status) {
48 $status = strpos($first_chars,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
49 if ($status !== false) {
50 $status = strpos($first_chars,"<MOODLE_BACKUP>");
55 return $status;
58 //This function iterates over all modules in backup file, searching for a
59 //MODNAME_refresh_events() to execute. Perhaps it should ve moved to central Moodle...
60 function restore_refresh_events($restore) {
62 global $CFG;
63 $status = true;
65 //Take all modules in backup
66 $modules = $restore->mods;
67 //Iterate
68 foreach($modules as $name => $module) {
69 //Only if the module is being restored
70 if (isset($module->restore) && $module->restore == 1) {
71 //Include module library
72 include_once("$CFG->dirroot/mod/$name/lib.php");
73 //If module_refresh_events exists
74 $function_name = $name."_refresh_events";
75 if (function_exists($function_name)) {
76 $status = $function_name($restore->course_id);
80 return $status;
83 //This function makes all the necessary calls to xxxx_decode_content_links_caller()
84 //function in each module, passing them the desired contents to be decoded
85 //from backup format to destination site/course in order to mantain inter-activities
86 //working in the backup/restore process
87 function restore_decode_content_links($restore) {
88 global $CFG;
90 $status = true;
92 if (!defined('RESTORE_SILENTLY')) {
93 echo "<ul>";
96 // Recode links in the course summary.
97 if (!defined('RESTORE_SILENTLY')) {
98 echo '<li>' . get_string('from') . ' ' . get_string('course');
100 $course = get_record('course', 'id', $restore->course_id, '', '', '', '', 'id,summary');
101 $coursesummary = restore_decode_content_links_worker($course->summary, $restore);
102 if ($coursesummary != $course->summary) {
103 $course->summary = addslashes($coursesummary);
104 if (!update_record('course', $course)) {
105 $status = false;
108 if (!defined('RESTORE_SILENTLY')) {
109 echo '</li>';
112 // Recode links in section summaries.
113 $sections = get_records('course_sections', 'course', $restore->course_id, 'id', 'id,summary');
114 if ($sections) {
115 if (!defined('RESTORE_SILENTLY')) {
116 echo '<li>' . get_string('from') . ' ' . get_string('sections');
118 foreach ($sections as $section) {
119 $sectionsummary = restore_decode_content_links_worker($section->summary, $restore);
120 if ($sectionsummary != $section->summary) {
121 $section->summary = addslashes($sectionsummary);
122 if (!update_record('course_sections', $section)) {
123 $status = false;
127 if (!defined('RESTORE_SILENTLY')) {
128 echo '</li>';
132 // Restore links in modules.
133 foreach ($restore->mods as $name => $info) {
134 //If the module is being restored
135 if (isset($info->restore) && $info->restore == 1) {
136 //Check if the xxxx_decode_content_links_caller exists
137 include_once("$CFG->dirroot/mod/$name/restorelib.php");
138 $function_name = $name."_decode_content_links_caller";
139 if (function_exists($function_name)) {
140 if (!defined('RESTORE_SILENTLY')) {
141 echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
143 $status = $function_name($restore) && $status;
144 if (!defined('RESTORE_SILENTLY')) {
145 echo '</li>';
151 // Process all html text also in blocks too
152 if (!defined('RESTORE_SILENTLY')) {
153 echo '<li>'.get_string ('from').' '.get_string('blocks');
156 if ($blocks = get_records('block', 'visible', 1)) {
157 foreach ($blocks as $block) {
158 if ($blockobject = block_instance($block->name)) {
159 $blockobject->decode_content_links_caller($restore);
164 if (!defined('RESTORE_SILENTLY')) {
165 echo '</li>';
168 // Restore links in questions.
169 require_once("$CFG->dirroot/question/restorelib.php");
170 if (!defined('RESTORE_SILENTLY')) {
171 echo '<li>' . get_string('from') . ' ' . get_string('questions', 'quiz');
173 $status = question_decode_content_links_caller($restore) && $status;
174 if (!defined('RESTORE_SILENTLY')) {
175 echo '</li>';
178 if (!defined('RESTORE_SILENTLY')) {
179 echo "</ul>";
182 return $status;
185 //This function is called from all xxxx_decode_content_links_caller(),
186 //its task is to ask all modules (maybe other linkable objects) to restore
187 //links to them.
188 function restore_decode_content_links_worker($content,$restore) {
189 foreach($restore->mods as $name => $info) {
190 $function_name = $name."_decode_content_links";
191 if (function_exists($function_name)) {
192 $content = $function_name($content,$restore);
196 // For each block, call its encode_content_links method
197 static $blockobjects = null;
198 if (!isset($blockobjects)) {
199 $blockobjects = array();
200 if ($blocks = get_records('block', 'visible', 1)) {
201 foreach ($blocks as $block) {
202 if ($blockobject = block_instance($block->name)) {
203 $blockobjects[] = $blockobject;
209 foreach ($blockobjects as $blockobject) {
210 $content = $blockobject->decode_content_links($content,$restore);
213 return $content;
216 //This function converts all the wiki texts in the restored course
217 //to the Markdown format. Used only for backup files prior 2005041100.
218 //It calls every module xxxx_convert_wiki2markdown function
219 function restore_convert_wiki2markdown($restore) {
221 $status = true;
223 if (!defined('RESTORE_SILENTLY')) {
224 echo "<ul>";
226 foreach ($restore->mods as $name => $info) {
227 //If the module is being restored
228 if ($info->restore == 1) {
229 //Check if the xxxx_restore_wiki2markdown exists
230 $function_name = $name."_restore_wiki2markdown";
231 if (function_exists($function_name)) {
232 $status = $function_name($restore);
233 if (!defined('RESTORE_SILENTLY')) {
234 echo "<li>".get_string("modulenameplural",$name);
235 echo '</li>';
240 if (!defined('RESTORE_SILENTLY')) {
241 echo "</ul>";
243 return $status;
246 //This function receives a wiki text in the restore process and
247 //return it with every link to modules " modulename:moduleid"
248 //converted if possible. See the space before modulename!!
249 function restore_decode_wiki_content($content,$restore) {
251 global $CFG;
253 $result = $content;
255 $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
256 //We look for it
257 preg_match_all($searchstring,$content,$foundset);
258 //If found, then we are going to look for its new id (in backup tables)
259 if ($foundset[0]) {
260 //print_object($foundset); //Debug
261 //Iterate over foundset[2]. They are the old_ids
262 foreach($foundset[2] as $old_id) {
263 //We get the needed variables here (course id)
264 $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id);
265 //Personalize the searchstring
266 $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/';
267 //If it is a link to this course, update the link to its new location
268 if($rec->new_id) {
269 //Now replace it
270 $result= preg_replace($searchstring,' $1:'.$rec->new_id.'($2)',$result);
271 } else {
272 //It's a foreign link so redirect it to its original URL
273 $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/$1/view.php?id='.$old_id.'($2)',$result);
277 return $result;
281 //This function read the xml file and store it data from the info zone in an object
282 function restore_read_xml_info ($xml_file) {
284 //We call the main read_xml function, with todo = INFO
285 $info = restore_read_xml ($xml_file,"INFO",false);
287 return $info;
290 //This function read the xml file and store it data from the course header zone in an object
291 function restore_read_xml_course_header ($xml_file) {
293 //We call the main read_xml function, with todo = COURSE_HEADER
294 $info = restore_read_xml ($xml_file,"COURSE_HEADER",false);
296 return $info;
299 //This function read the xml file and store its data from the blocks in a object
300 function restore_read_xml_blocks ($restore, $xml_file) {
302 //We call the main read_xml function, with todo = BLOCKS
303 $info = restore_read_xml ($xml_file,'BLOCKS',$restore);
305 return $info;
308 //This function read the xml file and store its data from the sections in a object
309 function restore_read_xml_sections ($xml_file) {
311 //We call the main read_xml function, with todo = SECTIONS
312 $info = restore_read_xml ($xml_file,"SECTIONS",false);
314 return $info;
317 //This function read the xml file and store its data from the course format in an object
318 function restore_read_xml_formatdata ($xml_file) {
320 //We call the main read_xml function, with todo = FORMATDATA
321 $info = restore_read_xml ($xml_file,'FORMATDATA',false);
323 return $info;
326 //This function read the xml file and store its data from the metacourse in a object
327 function restore_read_xml_metacourse ($xml_file) {
329 //We call the main read_xml function, with todo = METACOURSE
330 $info = restore_read_xml ($xml_file,"METACOURSE",false);
332 return $info;
335 //This function read the xml file and store its data from the gradebook in a object
336 function restore_read_xml_gradebook ($restore, $xml_file) {
338 //We call the main read_xml function, with todo = GRADEBOOK
339 $info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
341 return $info;
344 //This function read the xml file and store its data from the users in
345 //backup_ids->info db (and user's id in $info)
346 function restore_read_xml_users ($restore,$xml_file) {
348 //We call the main read_xml function, with todo = USERS
349 $info = restore_read_xml ($xml_file,"USERS",$restore);
351 return $info;
354 //This function read the xml file and store its data from the messages in
355 //backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
356 function restore_read_xml_messages ($restore,$xml_file) {
358 //We call the main read_xml function, with todo = MESSAGES
359 $info = restore_read_xml ($xml_file,"MESSAGES",$restore);
361 return $info;
364 //This function read the xml file and store its data from the blogs in
365 //backup_ids->blog and backup_ids->blog_tag and db (and their counters in info)
366 function restore_read_xml_blogs ($restore,$xml_file) {
368 //We call the main read_xml function, with todo = BLOGS
369 $info = restore_read_xml ($xml_file,"BLOGS",$restore);
371 return $info;
375 //This function read the xml file and store its data from the questions in
376 //backup_ids->info db (and category's id in $info)
377 function restore_read_xml_questions ($restore,$xml_file) {
379 //We call the main read_xml function, with todo = QUESTIONS
380 $info = restore_read_xml ($xml_file,"QUESTIONS",$restore);
382 return $info;
385 //This function read the xml file and store its data from the scales in
386 //backup_ids->info db (and scale's id in $info)
387 function restore_read_xml_scales ($restore,$xml_file) {
389 //We call the main read_xml function, with todo = SCALES
390 $info = restore_read_xml ($xml_file,"SCALES",$restore);
392 return $info;
395 //This function read the xml file and store its data from the groups in
396 //backup_ids->info db (and group's id in $info)
397 function restore_read_xml_groups ($restore,$xml_file) {
399 //We call the main read_xml function, with todo = GROUPS
400 $info = restore_read_xml ($xml_file,"GROUPS",$restore);
402 return $info;
405 //This function read the xml file and store its data from the groupings in
406 //backup_ids->info db (and grouping's id in $info)
407 function restore_read_xml_groupings ($restore,$xml_file) {
409 //We call the main read_xml function, with todo = GROUPINGS
410 $info = restore_read_xml ($xml_file,"GROUPINGS",$restore);
412 return $info;
415 //This function read the xml file and store its data from the groupings in
416 //backup_ids->info db (and grouping's id in $info)
417 function restore_read_xml_groupings_groups ($restore,$xml_file) {
419 //We call the main read_xml function, with todo = GROUPINGS
420 $info = restore_read_xml ($xml_file,"GROUPINGSGROUPS",$restore);
422 return $info;
425 //This function read the xml file and store its data from the events (course) in
426 //backup_ids->info db (and event's id in $info)
427 function restore_read_xml_events ($restore,$xml_file) {
429 //We call the main read_xml function, with todo = EVENTS
430 $info = restore_read_xml ($xml_file,"EVENTS",$restore);
432 return $info;
435 //This function read the xml file and store its data from the modules in
436 //backup_ids->info
437 function restore_read_xml_modules ($restore,$xml_file) {
439 //We call the main read_xml function, with todo = MODULES
440 $info = restore_read_xml ($xml_file,"MODULES",$restore);
442 return $info;
445 //This function read the xml file and store its data from the logs in
446 //backup_ids->info
447 function restore_read_xml_logs ($restore,$xml_file) {
449 //We call the main read_xml function, with todo = LOGS
450 $info = restore_read_xml ($xml_file,"LOGS",$restore);
452 return $info;
455 function restore_read_xml_roles ($xml_file) {
456 //We call the main read_xml function, with todo = ROLES
457 $info = restore_read_xml ($xml_file,"ROLES",false);
459 return $info;
462 //This function prints the contents from the info parammeter passed
463 function restore_print_info ($info) {
465 global $CFG;
467 $status = true;
468 if ($info) {
469 $table = new object();
470 //This is tha align to every ingo table
471 $table->align = array ("right","left");
472 //This is the nowrap clause
473 $table->wrap = array ("","nowrap");
474 //The width
475 $table->width = "70%";
476 //Put interesting info in table
477 //The backup original name
478 $tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
479 $tab[0][1] = $info->backup_name;
480 //The moodle version
481 $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
482 $tab[1][1] = $info->backup_moodle_release." (".$info->backup_moodle_version.")";
483 //The backup version
484 $tab[2][0] = "<b>".get_string("backupversion").":</b>";
485 $tab[2][1] = $info->backup_backup_release." (".$info->backup_backup_version.")";
486 //The backup date
487 $tab[3][0] = "<b>".get_string("backupdate").":</b>";
488 $tab[3][1] = userdate($info->backup_date);
489 //Print title
490 print_heading(get_string("backup").":");
491 $table->data = $tab;
492 //Print backup general info
493 print_table($table);
495 if ($info->backup_backup_version <= 2005070500) {
496 notify(get_string('backupnonisowarning')); // Message informing that this backup may not work!
499 //Now backup contents in another table
500 $tab = array();
501 //First mods info
502 $mods = $info->mods;
503 $elem = 0;
504 foreach ($mods as $key => $mod) {
505 $tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
506 if ($mod->backup == "false") {
507 $tab[$elem][1] = get_string("notincluded");
508 } else {
509 if ($mod->userinfo == "true") {
510 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
511 } else {
512 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
514 if (isset($mod->instances) && is_array($mod->instances) && count($mod->instances)) {
515 foreach ($mod->instances as $instance) {
516 if ($instance->backup) {
517 $elem++;
518 $tab[$elem][0] = $instance->name;
519 if ($instance->userinfo == 'true') {
520 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
521 } else {
522 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
528 $elem++;
530 //Metacourse info
531 $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
532 if ($info->backup_metacourse == "true") {
533 $tab[$elem][1] = get_string("yes");
534 } else {
535 $tab[$elem][1] = get_string("no");
537 $elem++;
538 //Users info
539 $tab[$elem][0] = "<b>".get_string("users").":</b>";
540 $tab[$elem][1] = get_string($info->backup_users);
541 $elem++;
542 //Logs info
543 $tab[$elem][0] = "<b>".get_string("logs").":</b>";
544 if ($info->backup_logs == "true") {
545 $tab[$elem][1] = get_string("yes");
546 } else {
547 $tab[$elem][1] = get_string("no");
549 $elem++;
550 //User Files info
551 $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
552 if ($info->backup_user_files == "true") {
553 $tab[$elem][1] = get_string("yes");
554 } else {
555 $tab[$elem][1] = get_string("no");
557 $elem++;
558 //Course Files info
559 $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
560 if ($info->backup_course_files == "true") {
561 $tab[$elem][1] = get_string("yes");
562 } else {
563 $tab[$elem][1] = get_string("no");
565 $elem++;
566 //site Files info
567 $tab[$elem][0] = "<b>".get_string("sitefiles").":</b>";
568 if (isset($info->backup_site_files) && $info->backup_site_files == "true") {
569 $tab[$elem][1] = get_string("yes");
570 } else {
571 $tab[$elem][1] = get_string("no");
573 $elem++;
574 //gradebook history info
575 $tab[$elem][0] = "<b>".get_string('gradebookhistories', 'grades').":</b>";
576 if (isset($info->gradebook_histories) && $info->gradebook_histories == "true") {
577 $tab[$elem][1] = get_string("yes");
578 } else {
579 $tab[$elem][1] = get_string("no");
581 $elem++;
582 //Messages info (only showed if present)
583 if ($info->backup_messages == 'true') {
584 $tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
585 $tab[$elem][1] = get_string('yes');
586 $elem++;
587 } else {
588 //Do nothing
590 $elem++;
591 //Blogs info (only showed if present)
592 if (isset($info->backup_blogs) && $info->backup_blogs == 'true') {
593 $tab[$elem][0] = "<b>".get_string('blogs','blog').":</b>";
594 $tab[$elem][1] = get_string('yes');
595 $elem++;
596 } else {
597 //Do nothing
599 $table->data = $tab;
600 //Print title
601 print_heading(get_string("backupdetails").":");
602 //Print backup general info
603 print_table($table);
604 } else {
605 $status = false;
608 return $status;
611 //This function prints the contents from the course_header parammeter passed
612 function restore_print_course_header ($course_header) {
614 $status = true;
615 if ($course_header) {
616 $table = new object();
617 //This is tha align to every ingo table
618 $table->align = array ("right","left");
619 //The width
620 $table->width = "70%";
621 //Put interesting course header in table
622 //The course name
623 $tab[0][0] = "<b>".get_string("name").":</b>";
624 $tab[0][1] = $course_header->course_fullname." (".$course_header->course_shortname.")";
625 //The course summary
626 $tab[1][0] = "<b>".get_string("summary").":</b>";
627 $tab[1][1] = $course_header->course_summary;
628 $table->data = $tab;
629 //Print title
630 print_heading(get_string("course").":");
631 //Print backup course header info
632 print_table($table);
633 } else {
634 $status = false;
636 return $status;
639 //This function create a new course record.
640 //When finished, course_header contains the id of the new course
641 function restore_create_new_course($restore,&$course_header) {
643 global $CFG;
645 $status = true;
647 $fullname = $course_header->course_fullname;
648 $shortname = $course_header->course_shortname;
649 $currentfullname = "";
650 $currentshortname = "";
651 $counter = 0;
652 //Iteratere while the name exists
653 do {
654 if ($counter) {
655 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
656 $suffixshort = "_".$counter;
657 } else {
658 $suffixfull = "";
659 $suffixshort = "";
661 $currentfullname = $fullname.$suffixfull;
662 // Limit the size of shortname - database column accepts <= 100 chars
663 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
664 $coursefull = get_record("course","fullname",addslashes($currentfullname));
665 $courseshort = get_record("course","shortname",addslashes($currentshortname));
666 $counter++;
667 } while ($coursefull || $courseshort);
669 //New name = currentname
670 $course_header->course_fullname = $currentfullname;
671 $course_header->course_shortname = $currentshortname;
673 // first try to get it from restore
674 if ($restore->restore_restorecatto) {
675 $category = get_record('course_categories', 'id', $restore->restore_restorecatto);
678 // else we try to get it from the xml file
679 //Now calculate the category
680 if (empty($category)) {
681 $category = get_record("course_categories","id",$course_header->category->id,
682 "name",addslashes($course_header->category->name));
685 //If no exists, try by name only
686 if (!$category) {
687 $category = get_record("course_categories","name",addslashes($course_header->category->name));
690 //If no exists, get category id 1
691 if (!$category) {
692 $category = get_record("course_categories","id","1");
695 //If category 1 doesn'exists, lets create the course category (get it from backup file)
696 if (!$category) {
697 $ins_category = new object();
698 $ins_category->name = addslashes($course_header->category->name);
699 $ins_category->parent = 0;
700 $ins_category->sortorder = 0;
701 $ins_category->coursecount = 0;
702 $ins_category->visible = 0; //To avoid interferences with the rest of the site
703 $ins_category->timemodified = time();
704 $newid = insert_record("course_categories",$ins_category);
705 $category->id = $newid;
706 $category->name = $course_header->category->name;
708 //If exists, put new category id
709 if ($category) {
710 $course_header->category->id = $category->id;
711 $course_header->category->name = $category->name;
712 //Error, cannot locate category
713 } else {
714 $course_header->category->id = 0;
715 $course_header->category->name = get_string("unknowncategory");
716 $status = false;
719 //Create the course_object
720 if ($status) {
721 $course = new object();
722 $course->category = addslashes($course_header->category->id);
723 $course->password = addslashes($course_header->course_password);
724 $course->fullname = addslashes($course_header->course_fullname);
725 $course->shortname = addslashes($course_header->course_shortname);
726 $course->idnumber = addslashes($course_header->course_idnumber);
727 $course->idnumber = ''; //addslashes($course_header->course_idnumber); // we don't want this at all.
728 $course->summary = backup_todb($course_header->course_summary);
729 $course->format = addslashes($course_header->course_format);
730 $course->showgrades = addslashes($course_header->course_showgrades);
731 $course->newsitems = addslashes($course_header->course_newsitems);
732 $course->teacher = addslashes($course_header->course_teacher);
733 $course->teachers = addslashes($course_header->course_teachers);
734 $course->student = addslashes($course_header->course_student);
735 $course->students = addslashes($course_header->course_students);
736 $course->guest = addslashes($course_header->course_guest);
737 $course->startdate = addslashes($course_header->course_startdate);
738 $course->startdate += $restore->course_startdateoffset;
739 $course->numsections = addslashes($course_header->course_numsections);
740 //$course->showrecent = addslashes($course_header->course_showrecent); INFO: This is out in 1.3
741 $course->maxbytes = addslashes($course_header->course_maxbytes);
742 $course->showreports = addslashes($course_header->course_showreports);
743 if (isset($course_header->course_groupmode)) {
744 $course->groupmode = addslashes($course_header->course_groupmode);
746 if (isset($course_header->course_groupmodeforce)) {
747 $course->groupmodeforce = addslashes($course_header->course_groupmodeforce);
749 if (isset($course_header->course_defaultgroupingid)) {
750 //keep the original now - convert after groupings restored
751 $course->defaultgroupingid = addslashes($course_header->course_defaultgroupingid);
753 $course->lang = addslashes($course_header->course_lang);
754 $course->theme = addslashes($course_header->course_theme);
755 $course->cost = addslashes($course_header->course_cost);
756 $course->currency = isset($course_header->course_currency)?addslashes($course_header->course_currency):'';
757 $course->marker = addslashes($course_header->course_marker);
758 $course->visible = addslashes($course_header->course_visible);
759 $course->hiddensections = addslashes($course_header->course_hiddensections);
760 $course->timecreated = addslashes($course_header->course_timecreated);
761 $course->timemodified = addslashes($course_header->course_timemodified);
762 $course->metacourse = addslashes($course_header->course_metacourse);
763 $course->expirynotify = isset($course_header->course_expirynotify) ? addslashes($course_header->course_expirynotify):0;
764 $course->notifystudents = isset($course_header->course_notifystudents) ? addslashes($course_header->course_notifystudents) : 0;
765 $course->expirythreshold = isset($course_header->course_expirythreshold) ? addslashes($course_header->course_expirythreshold) : 0;
766 $course->enrollable = isset($course_header->course_enrollable) ? addslashes($course_header->course_enrollable) : 1;
767 $course->enrolstartdate = isset($course_header->course_enrolstartdate) ? addslashes($course_header->course_enrolstartdate) : 0;
768 if ($course->enrolstartdate) { //Roll course dates
769 $course->enrolstartdate += $restore->course_startdateoffset;
771 $course->enrolenddate = isset($course_header->course_enrolenddate) ? addslashes($course_header->course_enrolenddate) : 0;
772 if ($course->enrolenddate) { //Roll course dates
773 $course->enrolenddate += $restore->course_startdateoffset;
775 $course->enrolperiod = addslashes($course_header->course_enrolperiod);
776 //Calculate sortorder field
777 $sortmax = get_record_sql('SELECT MAX(sortorder) AS max
778 FROM ' . $CFG->prefix . 'course
779 WHERE category=' . $course->category);
780 if (!empty($sortmax->max)) {
781 $course->sortorder = $sortmax->max + 1;
782 unset($sortmax);
783 } else {
784 $course->sortorder = 100;
787 //Now, recode some languages (Moodle 1.5)
788 if ($course->lang == 'ma_nt') {
789 $course->lang = 'mi_nt';
792 //Disable course->metacourse if avoided in restore config
793 if (!$restore->metacourse) {
794 $course->metacourse = 0;
797 //Check if the theme exists in destination server
798 $themes = get_list_of_themes();
799 if (!in_array($course->theme, $themes)) {
800 $course->theme = '';
803 //Now insert the record
804 $newid = insert_record("course",$course);
805 if ($newid) {
806 //save old and new course id
807 backup_putid ($restore->backup_unique_code,"course",$course_header->course_id,$newid);
808 //Replace old course_id in course_header
809 $course_header->course_id = $newid;
810 } else {
811 $status = false;
815 return $status;
820 //This function creates all the block stuff when restoring courses
821 //It calls selectively to restore_create_block_instances() for 1.5
822 //and above backups. Upwards compatible with old blocks.
823 function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) {
824 global $CFG;
825 $status = true;
827 delete_records('block_instance', 'pageid', $restore->course_id, 'pagetype', PAGE_COURSE_VIEW);
828 if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5
829 if (empty($blockinfo)) {
830 // Looks like it's from Moodle < 1.3. Let's give the course default blocks...
831 $newpage = page_create_object(PAGE_COURSE_VIEW, $restore->course_id);
832 blocks_repopulate_page($newpage);
833 } else {
834 // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup
835 $blockrecords = get_records_select('block', '', '', 'name, id');
836 $temp_blocks_l = array();
837 $temp_blocks_r = array();
838 @list($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo);
839 $temp_blocks = array(BLOCK_POS_LEFT => explode(',', $temp_blocks_l), BLOCK_POS_RIGHT => explode(',', $temp_blocks_r));
840 foreach($temp_blocks as $blockposition => $blocks) {
841 $blockweight = 0;
842 foreach($blocks as $blockname) {
843 if(!isset($blockrecords[$blockname])) {
844 // We don't know anything about this block!
845 continue;
847 $blockinstance = new stdClass;
848 // Remove any - prefix before doing the name-to-id mapping
849 if(substr($blockname, 0, 1) == '-') {
850 $blockname = substr($blockname, 1);
851 $blockinstance->visible = 0;
852 } else {
853 $blockinstance->visible = 1;
855 $blockinstance->blockid = $blockrecords[$blockname]->id;
856 $blockinstance->pageid = $restore->course_id;
857 $blockinstance->pagetype = PAGE_COURSE_VIEW;
858 $blockinstance->position = $blockposition;
859 $blockinstance->weight = $blockweight;
860 if(!$status = insert_record('block_instance', $blockinstance)) {
861 $status = false;
863 ++$blockweight;
867 } else if($backup_block_format == 'instances') {
868 $status = restore_create_block_instances($restore,$xml_file);
871 return $status;
875 //This function creates all the block_instances from xml when restoring in a
876 //new course
877 function restore_create_block_instances($restore,$xml_file) {
878 global $CFG;
879 $status = true;
881 //Check it exists
882 if (!file_exists($xml_file)) {
883 $status = false;
885 //Get info from xml
886 if ($status) {
887 $info = restore_read_xml_blocks($restore,$xml_file);
890 if(empty($info->instances)) {
891 return $status;
894 // First of all, iterate over the blocks to see which distinct pages we have
895 // in our hands and arrange the blocks accordingly.
896 $pageinstances = array();
897 foreach($info->instances as $instance) {
899 //pagetype and pageid black magic, we have to handle the case of blocks for the
900 //course, blocks from other pages in that course etc etc etc.
902 if($instance->pagetype == PAGE_COURSE_VIEW) {
903 // This one's easy...
904 $instance->pageid = $restore->course_id;
906 } else if (!empty($CFG->showblocksonmodpages)) {
907 $parts = explode('-', $instance->pagetype);
908 if($parts[0] == 'mod') {
909 if(!$restore->mods[$parts[1]]->restore) {
910 continue;
912 $getid = backup_getid($restore->backup_unique_code, $parts[1], $instance->pageid);
914 if (empty($getid->new_id)) {
915 // Failed, perhaps the module was not included in the restore MDL-13554
916 continue;
918 $instance->pageid = $getid->new_id;
920 else {
921 // Not invented here ;-)
922 continue;
925 } else {
926 // do not restore activity blocks if disabled
927 continue;
930 if(!isset($pageinstances[$instance->pagetype])) {
931 $pageinstances[$instance->pagetype] = array();
933 if(!isset($pageinstances[$instance->pagetype][$instance->pageid])) {
934 $pageinstances[$instance->pagetype][$instance->pageid] = array();
937 $pageinstances[$instance->pagetype][$instance->pageid][] = $instance;
940 $blocks = get_records_select('block', 'visible = 1', '', 'name, id, multiple');
942 // For each type of page we have restored
943 foreach($pageinstances as $thistypeinstances) {
945 // For each page id of that type
946 foreach($thistypeinstances as $thisidinstances) {
948 $addedblocks = array();
949 $maxweights = array();
951 // For each block instance in that page
952 foreach($thisidinstances as $instance) {
954 if(!isset($blocks[$instance->name])) {
955 //We are trying to restore a block we don't have...
956 continue;
959 //If we have already added this block once and multiples aren't allowed, disregard it
960 if(!$blocks[$instance->name]->multiple && isset($addedblocks[$instance->name])) {
961 continue;
964 //If its the first block we add to a new position, start weight counter equal to 0.
965 if(empty($maxweights[$instance->position])) {
966 $maxweights[$instance->position] = 0;
969 //If the instance weight is greater than the weight counter (we skipped some earlier
970 //blocks most probably), bring it back in line.
971 if($instance->weight > $maxweights[$instance->position]) {
972 $instance->weight = $maxweights[$instance->position];
975 //Add this instance
976 $instance->blockid = $blocks[$instance->name]->id;
978 // This will only be set if we come from 1.7 and above backups
979 // Also, must do this before insert (insert_record unsets id)
980 if (!empty($instance->id)) {
981 $oldid = $instance->id;
982 } else {
983 $oldid = 0;
986 if ($instance->id = insert_record('block_instance', $instance)) {
987 // Create block instance
988 if (!$blockobj = block_instance($instance->name, $instance)) {
989 $status = false;
990 break;
992 // Run the block restore if needed
993 if ($blockobj->backuprestore_instancedata_used()) {
994 // Get restore information
995 $data = backup_getid($restore->backup_unique_code,'block_instance',$oldid);
996 $data->new_id = $instance->id; // For completeness
997 if (!$blockobj->instance_restore($restore, $data)) {
998 $status = false;
999 break;
1002 // Save oldid after block restore process because info will be over-written with blank string
1003 if ($oldid) {
1004 backup_putid ($restore->backup_unique_code,"block_instance",$oldid,$instance->id);
1007 } else {
1008 $status = false;
1009 break;
1012 //Get an object for the block and tell it it's been restored so it can update dates
1013 //etc. if necessary
1014 if ($blockobj = block_instance($instance->name,$instance)) {
1015 $blockobj->after_restore($restore);
1018 //Now we can increment the weight counter
1019 ++$maxweights[$instance->position];
1021 //Keep track of block types we have already added
1022 $addedblocks[$instance->name] = true;
1028 return $status;
1031 //This function creates all the course_sections and course_modules from xml
1032 //when restoring in a new course or simply checks sections and create records
1033 //in backup_ids when restoring in a existing course
1034 function restore_create_sections(&$restore, $xml_file) {
1036 global $CFG,$db;
1038 $status = true;
1039 //Check it exists
1040 if (!file_exists($xml_file)) {
1041 $status = false;
1043 //Get info from xml
1044 if ($status) {
1045 $info = restore_read_xml_sections($xml_file);
1047 //Put the info in the DB, recoding ids and saving the in backup tables
1049 $sequence = "";
1051 if ($info) {
1052 //For each, section, save it to db
1053 foreach ($info->sections as $key => $sect) {
1054 $sequence = "";
1055 $section = new object();
1056 $section->course = $restore->course_id;
1057 $section->section = $sect->number;
1058 $section->summary = backup_todb($sect->summary);
1059 $section->visible = $sect->visible;
1060 $section->sequence = "";
1061 //Now calculate the section's newid
1062 $newid = 0;
1063 if ($restore->restoreto == 2) {
1064 //Save it to db (only if restoring to new course)
1065 $newid = insert_record("course_sections",$section);
1066 } else {
1067 //Get section id when restoring in existing course
1068 $rec = get_record("course_sections","course",$restore->course_id,
1069 "section",$section->section);
1070 //If that section doesn't exist, get section 0 (every mod will be
1071 //asigned there
1072 if(!$rec) {
1073 $rec = get_record("course_sections","course",$restore->course_id,
1074 "section","0");
1076 //New check. If section 0 doesn't exist, insert it here !!
1077 //Teorically this never should happen but, in practice, some users
1078 //have reported this issue.
1079 if(!$rec) {
1080 $zero_sec = new object();
1081 $zero_sec->course = $restore->course_id;
1082 $zero_sec->section = 0;
1083 $zero_sec->summary = "";
1084 $zero_sec->sequence = "";
1085 $newid = insert_record("course_sections",$zero_sec);
1086 $rec->id = $newid;
1087 $rec->sequence = "";
1089 $newid = $rec->id;
1090 $sequence = $rec->sequence;
1092 if ($newid) {
1093 //save old and new section id
1094 backup_putid ($restore->backup_unique_code,"course_sections",$key,$newid);
1095 } else {
1096 $status = false;
1098 //If all is OK, go with associated mods
1099 if ($status) {
1100 //If we have mods in the section
1101 if (!empty($sect->mods)) {
1102 //For each mod inside section
1103 foreach ($sect->mods as $keym => $mod) {
1104 // Yu: This part is called repeatedly for every instance,
1105 // so it is necessary to set the granular flag and check isset()
1106 // when the first instance of this type of mod is processed.
1108 //if (!isset($restore->mods[$mod->type]->granular) && isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) {
1110 if (!isset($restore->mods[$mod->type]->granular)) {
1111 if (isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) {
1112 // This defines whether we want to restore specific
1113 // instances of the modules (granular restore), or
1114 // whether we don't care and just want to restore
1115 // all module instances (non-granular).
1116 $restore->mods[$mod->type]->granular = true;
1117 } else {
1118 $restore->mods[$mod->type]->granular = false;
1122 //Check if we've to restore this module (and instance)
1123 if (!empty($restore->mods[$mod->type]->restore)) {
1124 if (empty($restore->mods[$mod->type]->granular) // we don't care about per instance
1125 || (array_key_exists($mod->instance,$restore->mods[$mod->type]->instances)
1126 && !empty($restore->mods[$mod->type]->instances[$mod->instance]->restore))) {
1128 //Get the module id from modules
1129 $module = get_record("modules","name",$mod->type);
1130 if ($module) {
1131 $course_module = new object();
1132 $course_module->course = $restore->course_id;
1133 $course_module->module = $module->id;
1134 $course_module->section = $newid;
1135 $course_module->added = $mod->added;
1136 $course_module->score = $mod->score;
1137 $course_module->indent = $mod->indent;
1138 $course_module->visible = $mod->visible;
1139 $course_module->groupmode = $mod->groupmode;
1140 if ($mod->groupingid and $grouping = restore_grouping_getid($restore, $mod->groupingid)) {
1141 $course_module->groupingid = $grouping->new_id;
1142 } else {
1143 $course_module->groupingid = 0;
1145 $course_module->groupmembersonly = $mod->groupmembersonly;
1146 $course_module->instance = 0;
1147 //NOTE: The instance (new) is calculated and updated in db in the
1148 // final step of the restore. We don't know it yet.
1149 //print_object($course_module); //Debug
1150 //Save it to db
1151 if ($mod->idnumber) {
1152 if (grade_verify_idnumber($mod->idnumber, $restore->course_id)) {
1153 $course_module->idnumber = $mod->idnumber;
1157 $newidmod = insert_record("course_modules", addslashes_recursive($course_module));
1158 if ($newidmod) {
1159 //save old and new module id
1160 //In the info field, we save the original instance of the module
1161 //to use it later
1162 backup_putid ($restore->backup_unique_code,"course_modules",
1163 $keym,$newidmod,$mod->instance);
1165 $restore->mods[$mod->type]->instances[$mod->instance]->restored_as_course_module = $newidmod;
1166 } else {
1167 $status = false;
1169 //Now, calculate the sequence field
1170 if ($status) {
1171 if ($sequence) {
1172 $sequence .= ",".$newidmod;
1173 } else {
1174 $sequence = $newidmod;
1177 } else {
1178 $status = false;
1185 //If all is OK, update sequence field in course_sections
1186 if ($status) {
1187 if (isset($sequence)) {
1188 $update_rec = new object();
1189 $update_rec->id = $newid;
1190 $update_rec->sequence = $sequence;
1191 $status = update_record("course_sections",$update_rec);
1195 } else {
1196 $status = false;
1198 return $status;
1201 //Called to set up any course-format specific data that may be in the file
1202 function restore_set_format_data($restore,$xml_file) {
1203 global $CFG,$db;
1205 $status = true;
1206 //Check it exists
1207 if (!file_exists($xml_file)) {
1208 return false;
1210 //Load data from XML to info
1211 if(!($info = restore_read_xml_formatdata($xml_file))) {
1212 return false;
1215 //Process format data if there is any
1216 if (isset($info->format_data)) {
1217 if(!$format=get_field('course','format','id',$restore->course_id)) {
1218 return false;
1220 // If there was any data then it must have a restore method
1221 $file=$CFG->dirroot."/course/format/$format/restorelib.php";
1222 if(!file_exists($file)) {
1223 return false;
1225 require_once($file);
1226 $function=$format.'_restore_format_data';
1227 if(!function_exists($function)) {
1228 return false;
1230 return $function($restore,$info->format_data);
1233 // If we got here then there's no data, but that's cool
1234 return true;
1237 //This function creates all the metacourse data from xml, notifying
1238 //about each incidence
1239 function restore_create_metacourse($restore,$xml_file) {
1241 global $CFG,$db;
1243 $status = true;
1244 //Check it exists
1245 if (!file_exists($xml_file)) {
1246 $status = false;
1248 //Get info from xml
1249 if ($status) {
1250 //Load data from XML to info
1251 $info = restore_read_xml_metacourse($xml_file);
1254 //Process info about metacourse
1255 if ($status and $info) {
1256 //Process child records
1257 if (!empty($info->childs)) {
1258 foreach ($info->childs as $child) {
1259 $dbcourse = false;
1260 $dbmetacourse = false;
1261 //Check if child course exists in destination server
1262 //(by id in the same server or by idnumber and shortname in other server)
1263 if ($restore->original_wwwroot == $CFG->wwwroot) {
1264 //Same server, lets see by id
1265 $dbcourse = get_record('course','id',$child->id);
1266 } else {
1267 //Different server, lets see by idnumber and shortname, and only ONE record
1268 $dbcount = count_records('course','idnumber',$child->idnumber,'shortname',$child->shortname);
1269 if ($dbcount == 1) {
1270 $dbcourse = get_record('course','idnumber',$child->idnumber,'shortname',$child->shortname);
1273 //If child course has been found, insert data
1274 if ($dbcourse) {
1275 $dbmetacourse->child_course = $dbcourse->id;
1276 $dbmetacourse->parent_course = $restore->course_id;
1277 $status = insert_record ('course_meta',$dbmetacourse);
1278 } else {
1279 //Child course not found, notice!
1280 if (!defined('RESTORE_SILENTLY')) {
1281 echo '<ul><li>'.get_string ('childcoursenotfound').' ('.$child->id.'/'.$child->idnumber.'/'.$child->shortname.')</li></ul>';
1285 //Now, recreate student enrolments...
1286 sync_metacourse($restore->course_id);
1288 //Process parent records
1289 if (!empty($info->parents)) {
1290 foreach ($info->parents as $parent) {
1291 $dbcourse = false;
1292 $dbmetacourse = false;
1293 //Check if parent course exists in destination server
1294 //(by id in the same server or by idnumber and shortname in other server)
1295 if ($restore->original_wwwroot == $CFG->wwwroot) {
1296 //Same server, lets see by id
1297 $dbcourse = get_record('course','id',$parent->id);
1298 } else {
1299 //Different server, lets see by idnumber and shortname, and only ONE record
1300 $dbcount = count_records('course','idnumber',$parent->idnumber,'shortname',$parent->shortname);
1301 if ($dbcount == 1) {
1302 $dbcourse = get_record('course','idnumber',$parent->idnumber,'shortname',$parent->shortname);
1305 //If parent course has been found, insert data if it is a metacourse
1306 if ($dbcourse) {
1307 if ($dbcourse->metacourse) {
1308 $dbmetacourse->parent_course = $dbcourse->id;
1309 $dbmetacourse->child_course = $restore->course_id;
1310 $status = insert_record ('course_meta',$dbmetacourse);
1311 //Now, recreate student enrolments in parent course
1312 sync_metacourse($dbcourse->id);
1313 } else {
1314 //Parent course isn't metacourse, notice!
1315 if (!defined('RESTORE_SILENTLY')) {
1316 echo '<ul><li>'.get_string ('parentcoursenotmetacourse').' ('.$parent->id.'/'.$parent->idnumber.'/'.$parent->shortname.')</li></ul>';
1319 } else {
1320 //Parent course not found, notice!
1321 if (!defined('RESTORE_SILENTLY')) {
1322 echo '<ul><li>'.get_string ('parentcoursenotfound').' ('.$parent->id.'/'.$parent->idnumber.'/'.$parent->shortname.')</li></ul>';
1329 return $status;
1333 * This function migrades all the pre 1.9 gradebook data from xml
1335 function restore_migrate_old_gradebook($restore,$xml_file) {
1336 global $CFG;
1338 $status = true;
1339 //Check it exists
1340 if (!file_exists($xml_file)) {
1341 return false;
1344 // Get info from xml
1345 // info will contain the number of record to process
1346 $info = restore_read_xml_gradebook($restore, $xml_file);
1348 // If we have info, then process
1349 if (empty($info)) {
1350 return $status;
1353 // make sure top course category exists
1354 $course_category = grade_category::fetch_course_category($restore->course_id);
1355 $course_category->load_grade_item();
1357 // we need to know if all grade items that were backed up are being restored
1358 // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
1359 // i.e. the aggregated grades of that category
1361 $restoreall = true; // set to false if any grade_item is not selected/restored
1362 $importing = !empty($SESSION->restore->importing); // there should not be a way to import old backups, but anyway ;-)
1364 if ($importing) {
1365 $restoreall = false;
1367 } else {
1368 $prev_grade_items = grade_item::fetch_all(array('courseid'=>$restore->course_id));
1369 $prev_grade_cats = grade_category::fetch_all(array('courseid'=>$restore->course_id));
1371 // if any categories already present, skip restore of categories from backup
1372 if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) {
1373 $restoreall = false;
1375 unset($prev_grade_items);
1376 unset($prev_grade_cats);
1379 // force creation of all grade_items - the course_modules already exist
1380 grade_force_full_regrading($restore->course_id);
1381 grade_grab_course_grades($restore->course_id);
1383 // Start ul
1384 if (!defined('RESTORE_SILENTLY')) {
1385 echo '<ul>';
1388 /// Process letters
1389 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
1390 // respect current grade letters if defined
1391 if ($status and $restoreall and !record_exists('grade_letters', 'contextid', $context->id)) {
1392 if (!defined('RESTORE_SILENTLY')) {
1393 echo '<li>'.get_string('gradeletters','grades').'</li>';
1395 // Fetch recordset_size records in each iteration
1396 $recs = get_records_select("backup_ids","table_name = 'grade_letter' AND backup_code = $restore->backup_unique_code",
1398 "old_id");
1399 if ($recs) {
1400 foreach ($recs as $rec) {
1401 // Get the full record from backup_ids
1402 $data = backup_getid($restore->backup_unique_code,'grade_letter',$rec->old_id);
1403 if ($data) {
1404 $info = $data->info;
1405 $dbrec = new object();
1406 $dbrec->contextid = $context->id;
1407 $dbrec->lowerboundary = backup_todb($info['GRADE_LETTER']['#']['GRADE_LOW']['0']['#']);
1408 $dbrec->letter = backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
1409 insert_record('grade_letters', $dbrec);
1415 if (!defined('RESTORE_SILENTLY')) {
1416 echo '<li>'.get_string('categories','grades').'</li>';
1418 //Fetch recordset_size records in each iteration
1419 $recs = get_records_select("backup_ids","table_name = 'grade_category' AND backup_code = $restore->backup_unique_code",
1420 "old_id",
1421 "old_id");
1422 $cat_count = count($recs);
1423 if ($recs) {
1424 foreach ($recs as $rec) {
1425 //Get the full record from backup_ids
1426 $data = backup_getid($restore->backup_unique_code,'grade_category',$rec->old_id);
1427 if ($data) {
1428 //Now get completed xmlized object
1429 $info = $data->info;
1431 if ($restoreall) {
1432 if ($cat_count == 1) {
1433 $course_category->fullname = backup_todb($info['GRADE_CATEGORY']['#']['NAME']['0']['#'], false);
1434 $course_category->droplow = backup_todb($info['GRADE_CATEGORY']['#']['DROP_X_LOWEST']['0']['#'], false);
1435 $course_category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
1436 $course_category->aggregateonlygraded = 0;
1437 $course_category->update('restore');
1438 $grade_category = $course_category;
1440 } else {
1441 $grade_category = new grade_category();
1442 $grade_category->courseid = $restore->course_id;
1443 $grade_category->fullname = backup_todb($info['GRADE_CATEGORY']['#']['NAME']['0']['#'], false);
1444 $grade_category->droplow = backup_todb($info['GRADE_CATEGORY']['#']['DROP_X_LOWEST']['0']['#'], false);
1445 $grade_category->aggregation = GRADE_AGGREGATE_WEIGHTED_MEAN2;
1446 $grade_category->aggregateonlygraded = 0;
1447 $grade_category->insert('restore');
1448 $grade_category->load_grade_item(); // force cretion of grade_item
1451 } else {
1452 $grade_category = null;
1455 /// now, restore grade_items
1456 $items = array();
1457 if (!empty($info['GRADE_CATEGORY']['#']['GRADE_ITEMS']['0']['#']['GRADE_ITEM'])) {
1458 //Iterate over items
1459 foreach ($info['GRADE_CATEGORY']['#']['GRADE_ITEMS']['0']['#']['GRADE_ITEM'] as $ite_info) {
1460 $modname = backup_todb($ite_info['#']['MODULE_NAME']['0']['#'], false);
1461 $olditeminstance = backup_todb($ite_info['#']['CMINSTANCE']['0']['#'], false);
1462 if (!$mod = backup_getid($restore->backup_unique_code,$modname, $olditeminstance)) {
1463 continue; // not restored
1465 $iteminstance = $mod->new_id;
1466 if (!$cm = get_coursemodule_from_instance($modname, $iteminstance, $restore->course_id)) {
1467 continue; // does not exist
1470 if (!$grade_item = grade_item::fetch(array('itemtype'=>'mod', 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance, 'courseid'=>$cm->course, 'itemnumber'=>0))) {
1471 continue; // no item yet??
1474 if ($grade_category) {
1475 $grade_item->sortorder = backup_todb($ite_info['#']['SORT_ORDER']['0']['#'], false);
1476 $grade_item->set_parent($grade_category->id);
1479 if ($importing
1480 or ($grade_item->itemtype == 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule, $olditeminstance))) {
1481 // module instance not selected when restored using granular
1482 // skip this item
1483 continue;
1486 //Now process grade excludes
1487 if (empty($ite_info['#']['GRADE_EXCEPTIONS'])) {
1488 continue;
1491 foreach($ite_info['#']['GRADE_EXCEPTIONS']['0']['#']['GRADE_EXCEPTION'] as $exc_info) {
1492 if ($u = backup_getid($restore->backup_unique_code,"user",backup_todb($exc_info['#']['USERID']['0']['#']))) {
1493 $userid = $u->new_id;
1494 $grade_grade = new grade_grade(array('itemid'=>$grade_item->id, 'userid'=>$userid));
1495 $grade_grade->excluded = 1;
1496 if ($grade_grade->id) {
1497 $grade_grade->update('restore');
1498 } else {
1499 $grade_grade->insert('restore');
1509 if (!defined('RESTORE_SILENTLY')) {
1510 //End ul
1511 echo '</ul>';
1514 return $status;
1518 * This function creates all the gradebook data from xml
1520 function restore_create_gradebook($restore,$xml_file) {
1521 global $CFG;
1523 $status = true;
1524 //Check it exists
1525 if (!file_exists($xml_file)) {
1526 return false;
1529 // Get info from xml
1530 // info will contain the number of record to process
1531 $info = restore_read_xml_gradebook($restore, $xml_file);
1533 // If we have info, then process
1534 if (empty($info)) {
1535 return $status;
1538 if (empty($CFG->disablegradehistory) and isset($info->gradebook_histories) and $info->gradebook_histories == "true") {
1539 $restore_histories = true;
1540 } else {
1541 $restore_histories = false;
1544 // make sure top course category exists
1545 $course_category = grade_category::fetch_course_category($restore->course_id);
1546 $course_category->load_grade_item();
1548 // we need to know if all grade items that were backed up are being restored
1549 // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
1550 // i.e. the aggregated grades of that category
1552 $restoreall = true; // set to false if any grade_item is not selected/restored or already exist
1553 $importing = !empty($SESSION->restore->importing);
1555 if ($importing) {
1556 $restoreall = false;
1558 } else {
1559 $prev_grade_items = grade_item::fetch_all(array('courseid'=>$restore->course_id));
1560 $prev_grade_cats = grade_category::fetch_all(array('courseid'=>$restore->course_id));
1562 // if any categories already present, skip restore of categories from backup - course item or category already exist
1563 if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) {
1564 $restoreall = false;
1566 unset($prev_grade_items);
1567 unset($prev_grade_cats);
1569 if ($restoreall) {
1570 if ($recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = $restore->backup_unique_code", "", "old_id")) {
1571 foreach ($recs as $rec) {
1572 if ($data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id)) {
1574 $info = $data->info;
1575 // do not restore if this grade_item is a mod, and
1576 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1578 if ($itemtype == 'mod') {
1579 $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1580 $itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1582 if (empty($restore->mods[$itemmodule]->granular)) {
1583 continue;
1584 } else if (!empty($restore->mods[$itemmodule]->instances[$olditeminstance]->restore)) {
1585 continue;
1587 // at least one activity should not be restored - do not restore categories and manual items at all
1588 $restoreall = false;
1589 break;
1597 // Start ul
1598 if (!defined('RESTORE_SILENTLY')) {
1599 echo '<ul>';
1602 // array of restored categories - speedup ;-)
1603 $cached_categories = array();
1604 $outcomes = array();
1606 /// Process letters
1607 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
1608 // respect current grade letters if defined
1609 if ($status and $restoreall and !record_exists('grade_letters', 'contextid', $context->id)) {
1610 if (!defined('RESTORE_SILENTLY')) {
1611 echo '<li>'.get_string('gradeletters','grades').'</li>';
1613 // Fetch recordset_size records in each iteration
1614 $recs = get_records_select("backup_ids","table_name = 'grade_letters' AND backup_code = $restore->backup_unique_code",
1616 "old_id");
1617 if ($recs) {
1618 foreach ($recs as $rec) {
1619 // Get the full record from backup_ids
1620 $data = backup_getid($restore->backup_unique_code,'grade_letters',$rec->old_id);
1621 if ($data) {
1622 $info = $data->info;
1623 $dbrec = new object();
1624 $dbrec->contextid = $context->id;
1625 $dbrec->lowerboundary = backup_todb($info['GRADE_LETTER']['#']['LOWERBOUNDARY']['0']['#']);
1626 $dbrec->letter = backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
1627 insert_record('grade_letters', $dbrec);
1633 /// Preprocess outcomes - do not store them yet!
1634 if ($status and !$importing and $restoreall) {
1635 if (!defined('RESTORE_SILENTLY')) {
1636 echo '<li>'.get_string('gradeoutcomes','grades').'</li>';
1638 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes' AND backup_code = '$restore->backup_unique_code'",
1640 "old_id");
1641 if ($recs) {
1642 foreach ($recs as $rec) {
1643 //Get the full record from backup_ids
1644 $data = backup_getid($restore->backup_unique_code,'grade_outcomes',$rec->old_id);
1645 if ($data) {
1646 $info = $data->info;
1648 //first find out if outcome already exists
1649 $shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']);
1651 if ($candidates = get_records_sql("SELECT *
1652 FROM {$CFG->prefix}grade_outcomes
1653 WHERE (courseid IS NULL OR courseid = $restore->course_id)
1654 AND shortname = '$shortname'
1655 ORDER BY courseid ASC, id ASC")) {
1656 $grade_outcome = reset($candidates);
1657 $outcomes[$rec->old_id] = $grade_outcome;
1658 continue;
1661 $dbrec = new object();
1663 if (has_capability('moodle/grade:manageoutcomes', get_context_instance(CONTEXT_SYSTEM))) {
1664 $oldoutcome = backup_todb($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#']);
1665 if (empty($oldoutcome)) {
1666 //site wide
1667 $dbrec->courseid = null;
1668 } else {
1669 //course only
1670 $dbrec->courseid = $restore->course_id;
1672 } else {
1673 // no permission to add site outcomes
1674 $dbrec->courseid = $restore->course_id;
1677 //Get the fields
1678 $dbrec->shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#'], false);
1679 $dbrec->fullname = backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#'], false);
1680 $dbrec->scaleid = backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#'], false);
1681 $dbrec->description = backup_todb($info['GRADE_OUTCOME']['#']['DESCRIPTION']['0']['#'], false);
1682 $dbrec->timecreated = backup_todb($info['GRADE_OUTCOME']['#']['TIMECREATED']['0']['#'], false);
1683 $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME']['#']['TIMEMODIFIED']['0']['#'], false);
1684 $dbrec->usermodified = backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#'], false);
1686 //Need to recode the scaleid
1687 if ($scale = backup_getid($restore->backup_unique_code, 'scale', $dbrec->scaleid)) {
1688 $dbrec->scaleid = $scale->new_id;
1691 //Need to recode the usermodified
1692 if ($modifier = backup_getid($restore->backup_unique_code, 'user', $dbrec->usermodified)) {
1693 $dbrec->usermodified = $modifier->new_id;
1696 $grade_outcome = new grade_outcome($dbrec, false);
1697 $outcomes[$rec->old_id] = $grade_outcome;
1703 /// Process grade items and grades
1704 if ($status) {
1705 if (!defined('RESTORE_SILENTLY')) {
1706 echo '<li>'.get_string('gradeitems','grades').'</li>';
1708 $counter = 0;
1710 //Fetch recordset_size records in each iteration
1711 $recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'",
1712 "id", // restore in the backup order
1713 "old_id");
1715 if ($recs) {
1716 foreach ($recs as $rec) {
1717 //Get the full record from backup_ids
1718 $data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id);
1719 if ($data) {
1720 $info = $data->info;
1722 // first find out if category or normal item
1723 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
1724 if ($itemtype == 'course' or $itemtype == 'category') {
1725 if (!$restoreall or $importing) {
1726 continue;
1729 $oldcat = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
1730 if (!$cdata = backup_getid($restore->backup_unique_code,'grade_categories',$oldcat)) {
1731 continue;
1733 $cinfo = $cdata->info;
1734 unset($cdata);
1735 if ($itemtype == 'course') {
1737 $course_category->fullname = backup_todb($cinfo['GRADE_CATEGORY']['#']['FULLNAME']['0']['#'], false);
1738 $course_category->aggregation = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#'], false);
1739 $course_category->keephigh = backup_todb($cinfo['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#'], false);
1740 $course_category->droplow = backup_todb($cinfo['GRADE_CATEGORY']['#']['DROPLOW']['0']['#'], false);
1741 $course_category->aggregateonlygraded = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEONLYGRADED']['0']['#'], false);
1742 $course_category->aggregateoutcomes = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#'], false);
1743 $course_category->aggregatesubcats = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATESUBCATS']['0']['#'], false);
1744 $course_category->timecreated = backup_todb($cinfo['GRADE_CATEGORY']['#']['TIMECREATED']['0']['#'], false);
1745 $course_category->update('restore');
1747 $status = backup_putid($restore->backup_unique_code,'grade_categories',$oldcat,$course_category->id) && $status;
1748 $cached_categories[$oldcat] = $course_category;
1749 $grade_item = $course_category->get_grade_item();
1751 } else {
1752 $oldparent = backup_todb($cinfo['GRADE_CATEGORY']['#']['PARENT']['0']['#'], false);
1753 if (empty($cached_categories[$oldparent])) {
1754 debugging('parent not found '.$oldparent);
1755 continue; // parent not found, sorry
1757 $grade_category = new grade_category();
1758 $grade_category->courseid = $restore->course_id;
1759 $grade_category->parent = $cached_categories[$oldparent]->id;
1760 $grade_category->fullname = backup_todb($cinfo['GRADE_CATEGORY']['#']['FULLNAME']['0']['#'], false);
1761 $grade_category->aggregation = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#'], false);
1762 $grade_category->keephigh = backup_todb($cinfo['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#'], false);
1763 $grade_category->droplow = backup_todb($cinfo['GRADE_CATEGORY']['#']['DROPLOW']['0']['#'], false);
1764 $grade_category->aggregateonlygraded = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEONLYGRADED']['0']['#'], false);
1765 $grade_category->aggregateoutcomes = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#'], false);
1766 $grade_category->aggregatesubcats = backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATESUBCATS']['0']['#'], false);
1767 $grade_category->timecreated = backup_todb($cinfo['GRADE_CATEGORY']['#']['TIMECREATED']['0']['#'], false);
1768 $grade_category->insert('restore');
1770 $status = backup_putid($restore->backup_unique_code,'grade_categories',$oldcat,$grade_category->id) && $status;
1771 $cached_categories[$oldcat] = $grade_category;
1772 $grade_item = $grade_category->get_grade_item(); // creates grade_item too
1774 unset($cinfo);
1776 $idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#'], false);
1777 if (grade_verify_idnumber($idnumber, $restore->course_id)) {
1778 $grade_item->idnumber = $idnumber;
1781 $grade_item->itemname = backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#'], false);
1782 $grade_item->iteminfo = backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#'], false);
1783 $grade_item->gradetype = backup_todb($info['GRADE_ITEM']['#']['GRADETYPE']['0']['#'], false);
1784 $grade_item->calculation = backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#'], false);
1785 $grade_item->grademax = backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#'], false);
1786 $grade_item->grademin = backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#'], false);
1787 $grade_item->gradepass = backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#'], false);
1788 $grade_item->multfactor = backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#'], false);
1789 $grade_item->plusfactor = backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#'], false);
1790 $grade_item->aggregationcoef = backup_todb($info['GRADE_ITEM']['#']['AGGREGATIONCOEF']['0']['#'], false);
1791 $grade_item->display = backup_todb($info['GRADE_ITEM']['#']['DISPLAY']['0']['#'], false);
1792 $grade_item->decimals = backup_todb($info['GRADE_ITEM']['#']['DECIMALS']['0']['#'], false);
1793 $grade_item->hidden = backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#'], false);
1794 $grade_item->locked = backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#'], false);
1795 $grade_item->locktime = backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#'], false);
1796 $grade_item->timecreated = backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#'], false);
1798 if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false)) {
1799 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false));
1800 $grade_item->scaleid = $scale->new_id;
1803 if (backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'], false)) {
1804 $outcome = backup_getid($restore->backup_unique_code,"grade_outcomes",backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'], false));
1805 $grade_item->outcomeid = $outcome->new_id;
1808 $grade_item->update('restore');
1809 $status = backup_putid($restore->backup_unique_code,"grade_items", $rec->old_id, $grade_item->id) && $status;
1811 } else {
1812 if ($itemtype != 'mod' and (!$restoreall or $importing)) {
1813 // not extra gradebook stuff if restoring individual activities or something already there
1814 continue;
1817 $dbrec = new object();
1819 $dbrec->courseid = $restore->course_id;
1820 $dbrec->itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
1821 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#'], false);
1823 if ($itemtype == 'mod') {
1824 // iteminstance should point to new mod
1825 $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
1826 $mod = backup_getid($restore->backup_unique_code,$dbrec->itemmodule, $olditeminstance);
1827 $dbrec->iteminstance = $mod->new_id;
1828 if (!$cm = get_coursemodule_from_instance($dbrec->itemmodule, $mod->new_id)) {
1829 // item not restored - no item
1830 continue;
1832 // keep in sync with activity idnumber
1833 $dbrec->idnumber = $cm->idnumber;
1835 } else {
1836 $idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#'], false);
1838 if (grade_verify_idnumber($idnumber, $restore->course_id)) {
1839 //make sure the new idnumber is unique
1840 $dbrec->idnumber = $idnumber;
1844 $dbrec->itemname = backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#'], false);
1845 $dbrec->itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
1846 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#'], false);
1847 $dbrec->itemnumber = backup_todb($info['GRADE_ITEM']['#']['ITEMNUMBER']['0']['#'], false);
1848 $dbrec->iteminfo = backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#'], false);
1849 $dbrec->gradetype = backup_todb($info['GRADE_ITEM']['#']['GRADETYPE']['0']['#'], false);
1850 $dbrec->calculation = backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#'], false);
1851 $dbrec->grademax = backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#'], false);
1852 $dbrec->grademin = backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#'], false);
1853 $dbrec->gradepass = backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#'], false);
1854 $dbrec->multfactor = backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#'], false);
1855 $dbrec->plusfactor = backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#'], false);
1856 $dbrec->aggregationcoef = backup_todb($info['GRADE_ITEM']['#']['AGGREGATIONCOEF']['0']['#'], false);
1857 $dbrec->display = backup_todb($info['GRADE_ITEM']['#']['DISPLAY']['0']['#'], false);
1858 $dbrec->decimals = backup_todb($info['GRADE_ITEM']['#']['DECIMALS']['0']['#'], false);
1859 $dbrec->hidden = backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#'], false);
1860 $dbrec->locked = backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#'], false);
1861 $dbrec->locktime = backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#'], false);
1862 $dbrec->timecreated = backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#'], false);
1864 if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false)) {
1865 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false));
1866 $dbrec->scaleid = $scale->new_id;
1869 if (backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'])) {
1870 $oldoutcome = backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#']);
1871 if (empty($outcomes[$oldoutcome])) {
1872 continue; // error!
1874 if (empty($outcomes[$oldoutcome]->id)) {
1875 $outcomes[$oldoutcome]->insert('restore');
1876 $outcomes[$oldoutcome]->use_in($restore->course_id);
1877 backup_putid($restore->backup_unique_code, "grade_outcomes", $oldoutcome, $outcomes[$oldoutcome]->id);
1879 $dbrec->outcomeid = $outcomes[$oldoutcome]->id;
1882 $grade_item = new grade_item($dbrec, false);
1883 $grade_item->insert('restore');
1884 if ($restoreall) {
1885 // set original parent if restored
1886 $oldcat = $info['GRADE_ITEM']['#']['CATEGORYID']['0']['#'];
1887 if (!empty($cached_categories[$oldcat])) {
1888 $grade_item->set_parent($cached_categories[$oldcat]->id);
1891 $status = backup_putid($restore->backup_unique_code,"grade_items", $rec->old_id, $grade_item->id) && $status;
1894 // no need to restore grades if user data is not selected or importing activities
1895 if ($importing
1896 or ($grade_item->itemtype == 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule, $olditeminstance))) {
1897 // module instance not selected when restored using granular
1898 // skip this item
1899 continue;
1902 /// now, restore grade_grades
1903 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'])) {
1904 //Iterate over items
1905 foreach ($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'] as $g_info) {
1907 $grade = new grade_grade();
1908 $grade->itemid = $grade_item->id;
1910 $olduser = backup_todb($g_info['#']['USERID']['0']['#'], false);
1911 $user = backup_getid($restore->backup_unique_code,"user",$olduser);
1912 $grade->userid = $user->new_id;
1914 $grade->rawgrade = backup_todb($g_info['#']['RAWGRADE']['0']['#'], false);
1915 $grade->rawgrademax = backup_todb($g_info['#']['RAWGRADEMAX']['0']['#'], false);
1916 $grade->rawgrademin = backup_todb($g_info['#']['RAWGRADEMIN']['0']['#'], false);
1917 // need to find scaleid
1918 if (backup_todb($g_info['#']['RAWSCALEID']['0']['#'])) {
1919 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($g_info['#']['RAWSCALEID']['0']['#'], false));
1920 $grade->rawscaleid = $scale->new_id;
1923 if (backup_todb($g_info['#']['USERMODIFIED']['0']['#'])) {
1924 if ($modifier = backup_getid($restore->backup_unique_code,"user", backup_todb($g_info['#']['USERMODIFIED']['0']['#'], false))) {
1925 $grade->usermodified = $modifier->new_id;
1929 $grade->finalgrade = backup_todb($g_info['#']['FINALGRADE']['0']['#'], false);
1930 $grade->hidden = backup_todb($g_info['#']['HIDDEN']['0']['#'], false);
1931 $grade->locked = backup_todb($g_info['#']['LOCKED']['0']['#'], false);
1932 $grade->locktime = backup_todb($g_info['#']['LOCKTIME']['0']['#'], false);
1933 $grade->exported = backup_todb($g_info['#']['EXPORTED']['0']['#'], false);
1934 $grade->overridden = backup_todb($g_info['#']['OVERRIDDEN']['0']['#'], false);
1935 $grade->excluded = backup_todb($g_info['#']['EXCLUDED']['0']['#'], false);
1936 $grade->feedback = backup_todb($g_info['#']['FEEDBACK']['0']['#'], false);
1937 $grade->feedbackformat = backup_todb($g_info['#']['FEEDBACKFORMAT']['0']['#'], false);
1938 $grade->information = backup_todb($g_info['#']['INFORMATION']['0']['#'], false);
1939 $grade->informationformat = backup_todb($g_info['#']['INFORMATIONFORMAT']['0']['#'], false);
1940 $grade->timecreated = backup_todb($g_info['#']['TIMECREATED']['0']['#'], false);
1941 $grade->timemodified = backup_todb($g_info['#']['TIMEMODIFIED']['0']['#'], false);
1943 $grade->insert('restore');
1944 backup_putid($restore->backup_unique_code,"grade_grades", backup_todb($g_info['#']['ID']['0']['#']), $grade->id);
1946 $counter++;
1947 if ($counter % 20 == 0) {
1948 if (!defined('RESTORE_SILENTLY')) {
1949 echo ".";
1950 if ($counter % 400 == 0) {
1951 echo "<br />";
1954 backup_flush(300);
1963 /// add outcomes that are not used when doing full restore
1964 if ($status and $restoreall) {
1965 foreach ($outcomes as $oldoutcome=>$grade_outcome) {
1966 if (empty($grade_outcome->id)) {
1967 $grade_outcome->insert('restore');
1968 $grade_outcome->use_in($restore->course_id);
1969 backup_putid($restore->backup_unique_code, "grade_outcomes", $oldoutcome, $grade_outcome->id);
1975 if ($status and !$importing and $restore_histories) {
1976 /// following code is very inefficient
1978 $gchcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_categories_history');
1979 $gghcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_grades_history');
1980 $gihcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_items_history');
1981 $gohcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_outcomes_history');
1983 // Number of records to get in every chunk
1984 $recordset_size = 2;
1986 // process histories
1987 if ($gchcount && $status) {
1988 if (!defined('RESTORE_SILENTLY')) {
1989 echo '<li>'.get_string('gradecategoryhistory','grades').'</li>';
1991 $counter = 0;
1992 while ($counter < $gchcount) {
1993 //Fetch recordset_size records in each iteration
1994 $recs = get_records_select("backup_ids","table_name = 'grade_categories_history' AND backup_code = '$restore->backup_unique_code'",
1995 "old_id",
1996 "old_id",
1997 $counter,
1998 $recordset_size);
1999 if ($recs) {
2000 foreach ($recs as $rec) {
2001 //Get the full record from backup_ids
2002 $data = backup_getid($restore->backup_unique_code,'grade_categories_history',$rec->old_id);
2003 if ($data) {
2004 //Now get completed xmlized object
2005 $info = $data->info;
2006 //traverse_xmlize($info); //Debug
2007 //print_object ($GLOBALS['traverse_array']); //Debug
2008 //$GLOBALS['traverse_array']=""; //Debug
2010 $oldobj = backup_getid($restore->backup_unique_code,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['OLDID']['0']['#']));
2011 if (empty($oldobj->new_id)) {
2012 // if the old object is not being restored, can't restoring its history
2013 $counter++;
2014 continue;
2016 $dbrec->oldid = $oldobj->new_id;
2017 $dbrec->action = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['ACTION']['0']['#']);
2018 $dbrec->source = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['SOURCE']['0']['#']);
2019 $dbrec->timemodified = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2021 // loggeduser might not be restored, e.g. admin
2022 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2023 $dbrec->loggeduser = $oldobj->new_id;
2026 // this item might not have a parent at all, do not skip it if no parent is specified
2027 if (backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#'])) {
2028 $oldobj = backup_getid($restore->backup_unique_code,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#']));
2029 if (empty($oldobj->new_id)) {
2030 // if the parent category not restored
2031 $counter++;
2032 continue;
2035 $dbrec->parent = $oldobj->new_id;
2036 $dbrec->depth = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DEPTH']['0']['#']);
2037 // path needs to be rebuilt
2038 if ($path = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PATH']['0']['#'])) {
2039 // to preserve the path and make it work, we need to replace the categories one by one
2040 // we first get the list of categories in current path
2041 if ($paths = explode("/", $path)) {
2042 $newpath = '';
2043 foreach ($paths as $catid) {
2044 if ($catid) {
2045 // find the new corresponding path
2046 $oldpath = backup_getid($restore->backup_unique_code,"grade_categories", $catid);
2047 $newpath .= "/$oldpath->new_id";
2050 $dbrec->path = $newpath;
2053 $dbrec->fullname = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['FULLNAME']['0']['#']);
2054 $dbrec->aggregation = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGRETGATION']['0']['#']);
2055 $dbrec->keephigh = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['KEEPHIGH']['0']['#']);
2056 $dbrec->droplow = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DROPLOW']['0']['#']);
2058 $dbrec->aggregateonlygraded = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATEONLYGRADED']['0']['#']);
2059 $dbrec->aggregateoutcomes = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATEOUTCOMES']['0']['#']);
2060 $dbrec->aggregatesubcats = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATESUBCATS']['0']['#']);
2062 $dbrec->courseid = $restore->course_id;
2063 insert_record('grade_categories_history', $dbrec);
2064 unset($dbrec);
2067 //Increment counters
2068 $counter++;
2069 //Do some output
2070 if ($counter % 1 == 0) {
2071 if (!defined('RESTORE_SILENTLY')) {
2072 echo ".";
2073 if ($counter % 20 == 0) {
2074 echo "<br />";
2077 backup_flush(300);
2084 // process histories
2085 if ($gghcount && $status) {
2086 if (!defined('RESTORE_SILENTLY')) {
2087 echo '<li>'.get_string('gradegradeshistory','grades').'</li>';
2089 $counter = 0;
2090 while ($counter < $gghcount) {
2091 //Fetch recordset_size records in each iteration
2092 $recs = get_records_select("backup_ids","table_name = 'grade_grades_history' AND backup_code = '$restore->backup_unique_code'",
2093 "old_id",
2094 "old_id",
2095 $counter,
2096 $recordset_size);
2097 if ($recs) {
2098 foreach ($recs as $rec) {
2099 //Get the full record from backup_ids
2100 $data = backup_getid($restore->backup_unique_code,'grade_grades_history',$rec->old_id);
2101 if ($data) {
2102 //Now get completed xmlized object
2103 $info = $data->info;
2104 //traverse_xmlize($info); //Debug
2105 //print_object ($GLOBALS['traverse_array']); //Debug
2106 //$GLOBALS['traverse_array']=""; //Debug
2108 $oldobj = backup_getid($restore->backup_unique_code,"grade_grades", backup_todb($info['GRADE_GRADES_HISTORY']['#']['OLDID']['0']['#']));
2109 if (empty($oldobj->new_id)) {
2110 // if the old object is not being restored, can't restoring its history
2111 $counter++;
2112 continue;
2114 $dbrec->oldid = $oldobj->new_id;
2115 $dbrec->action = backup_todb($info['GRADE_GRADES_HISTORY']['#']['ACTION']['0']['#']);
2116 $dbrec->source = backup_todb($info['GRADE_GRADES_HISTORY']['#']['SOURCE']['0']['#']);
2117 $dbrec->timemodified = backup_todb($info['GRADE_GRADES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2118 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2119 $dbrec->loggeduser = $oldobj->new_id;
2122 $oldobj = backup_getid($restore->backup_unique_code,"grade_items", backup_todb($info['GRADE_GRADES_HISTORY']['#']['ITEMID']['0']['#']));
2123 $dbrec->itemid = $oldobj->new_id;
2124 if (empty($dbrec->itemid)) {
2125 $counter++;
2126 continue; // grade item not being restored
2128 $oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERID']['0']['#']));
2129 $dbrec->userid = $oldobj->new_id;
2130 $dbrec->rawgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADE']['0']['#']);
2131 $dbrec->rawgrademax = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMAX']['0']['#']);
2132 $dbrec->rawgrademin = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMIN']['0']['#']);
2133 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERMODIFIED']['0']['#']))) {
2134 $dbrec->usermodified = $oldobj->new_id;
2137 if (backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWSCALEID']['0']['#'])) {
2138 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWSCALEID']['0']['#']));
2139 $dbrec->rawscaleid = $scale->new_id;
2142 $dbrec->finalgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['FINALGRADE']['0']['#']);
2143 $dbrec->hidden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['HIDDEN']['0']['#']);
2144 $dbrec->locked = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKED']['0']['#']);
2145 $dbrec->locktime = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKTIME']['0']['#']);
2146 $dbrec->exported = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXPORTED']['0']['#']);
2147 $dbrec->overridden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['OVERRIDDEN']['0']['#']);
2148 $dbrec->excluded = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXCLUDED']['0']['#']);
2149 $dbrec->feedback = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACK']['0']['#']);
2150 $dbrec->feedbackformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACKFORMAT']['0']['#']);
2151 $dbrec->information = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATION']['0']['#']);
2152 $dbrec->informationformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATIONFORMAT']['0']['#']);
2154 insert_record('grade_grades_history', $dbrec);
2155 unset($dbrec);
2158 //Increment counters
2159 $counter++;
2160 //Do some output
2161 if ($counter % 1 == 0) {
2162 if (!defined('RESTORE_SILENTLY')) {
2163 echo ".";
2164 if ($counter % 20 == 0) {
2165 echo "<br />";
2168 backup_flush(300);
2175 // process histories
2177 if ($gihcount && $status) {
2178 if (!defined('RESTORE_SILENTLY')) {
2179 echo '<li>'.get_string('gradeitemshistory','grades').'</li>';
2181 $counter = 0;
2182 while ($counter < $gihcount) {
2183 //Fetch recordset_size records in each iteration
2184 $recs = get_records_select("backup_ids","table_name = 'grade_items_history' AND backup_code = '$restore->backup_unique_code'",
2185 "old_id",
2186 "old_id",
2187 $counter,
2188 $recordset_size);
2189 if ($recs) {
2190 foreach ($recs as $rec) {
2191 //Get the full record from backup_ids
2192 $data = backup_getid($restore->backup_unique_code,'grade_items_history',$rec->old_id);
2193 if ($data) {
2194 //Now get completed xmlized object
2195 $info = $data->info;
2196 //traverse_xmlize($info); //Debug
2197 //print_object ($GLOBALS['traverse_array']); //Debug
2198 //$GLOBALS['traverse_array']=""; //Debug
2201 $oldobj = backup_getid($restore->backup_unique_code,"grade_items", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OLDID']['0']['#']));
2202 if (empty($oldobj->new_id)) {
2203 // if the old object is not being restored, can't restoring its history
2204 $counter++;
2205 continue;
2207 $dbrec->oldid = $oldobj->new_id;
2208 $dbrec->action = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ACTION']['0']['#']);
2209 $dbrec->source = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SOURCE']['0']['#']);
2210 $dbrec->timemodified = backup_todb($info['GRADE_ITEM_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2211 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2212 $dbrec->loggeduser = $oldobj->new_id;
2214 $dbrec->courseid = $restore->course_id;
2215 $oldobj = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_ITEM_HISTORY']['#']['CATEGORYID']['0']['#']));
2216 $oldobj->categoryid = $category->new_id;
2217 if (empty($oldobj->categoryid)) {
2218 $counter++;
2219 continue; // category not restored
2222 $dbrec->itemname= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNAME']['0']['#']);
2223 $dbrec->itemtype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMTYPE']['0']['#']);
2224 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMMODULE']['0']['#']);
2226 // code from grade_items restore
2227 $iteminstance = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINSTANCE']['0']['#']);
2228 // do not restore if this grade_item is a mod, and
2229 if ($dbrec->itemtype == 'mod') {
2231 if (!restore_userdata_selected($restore, $dbrec->itemmodule, $iteminstance)) {
2232 // module instance not selected when restored using granular
2233 // skip this item
2234 $counter++;
2235 continue;
2238 // iteminstance should point to new mod
2240 $mod = backup_getid($restore->backup_unique_code,$dbrec->itemmodule, $iteminstance);
2241 $dbrec->iteminstance = $mod->new_id;
2243 } else if ($dbrec->itemtype == 'category') {
2244 // the item instance should point to the new grade category
2246 // only proceed if we are restoring all grade items
2247 if ($restoreall) {
2248 $category = backup_getid($restore->backup_unique_code,'grade_categories', $iteminstance);
2249 $dbrec->iteminstance = $category->new_id;
2250 } else {
2251 // otherwise we can safely ignore this grade item and subsequent
2252 // grade_raws, grade_finals etc
2253 continue;
2255 } elseif ($dbrec->itemtype == 'course') { // We don't restore course type to avoid duplicate course items
2256 if ($restoreall) {
2257 // TODO any special code needed here to restore course item without duplicating it?
2258 // find the course category with depth 1, and course id = current course id
2259 // this would have been already restored
2261 $cat = get_record('grade_categories', 'depth', 1, 'courseid', $restore->course_id);
2262 $dbrec->iteminstance = $cat->id;
2264 } else {
2265 $counter++;
2266 continue;
2270 $dbrec->itemnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNUMBER']['0']['#']);
2271 $dbrec->iteminfo = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINFO']['0']['#']);
2272 $dbrec->idnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['IDNUMBER']['0']['#']);
2273 $dbrec->calculation = backup_todb($info['GRADE_ITEM_HISTORY']['#']['CALCULATION']['0']['#']);
2274 $dbrec->gradetype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADETYPE']['0']['#']);
2275 $dbrec->grademax = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMAX']['0']['#']);
2276 $dbrec->grademin = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMIN']['0']['#']);
2277 if ($oldobj = backup_getid($restore->backup_unique_code,"scale", backup_todb($info['GRADE_ITEM_HISTORY']['#']['SCALEID']['0']['#']))) {
2278 // scaleid is optional
2279 $dbrec->scaleid = $oldobj->new_id;
2281 if ($oldobj = backup_getid($restore->backup_unique_code,"grade_outcomes", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OUTCOMEID']['0']['#']))) {
2282 // outcome is optional
2283 $dbrec->outcomeid = $oldobj->new_id;
2285 $dbrec->gradepass = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEPASS']['0']['#']);
2286 $dbrec->multfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['MULTFACTOR']['0']['#']);
2287 $dbrec->plusfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['PLUSFACTOR']['0']['#']);
2288 $dbrec->aggregationcoef = backup_todb($info['GRADE_ITEM_HISTORY']['#']['AGGREGATIONCOEF']['0']['#']);
2289 $dbrec->sortorder = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SORTORDER']['0']['#']);
2290 $dbrec->display = backup_todb($info['GRADE_ITEM_HISTORY']['#']['DISPLAY']['0']['#']);
2291 $dbrec->decimals = backup_todb($info['GRADE_ITEM_HISTORY']['#']['DECIMALS']['0']['#']);
2292 $dbrec->hidden = backup_todb($info['GRADE_ITEM_HISTORY']['#']['HIDDEN']['0']['#']);
2293 $dbrec->locked = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKED']['0']['#']);
2294 $dbrec->locktime = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKTIME']['0']['#']);
2295 $dbrec->needsupdate = backup_todb($info['GRADE_ITEM_HISTORY']['#']['NEEDSUPDATE']['0']['#']);
2297 insert_record('grade_items_history', $dbrec);
2298 unset($dbrec);
2301 //Increment counters
2302 $counter++;
2303 //Do some output
2304 if ($counter % 1 == 0) {
2305 if (!defined('RESTORE_SILENTLY')) {
2306 echo ".";
2307 if ($counter % 20 == 0) {
2308 echo "<br />";
2311 backup_flush(300);
2318 // process histories
2319 if ($gohcount && $status) {
2320 if (!defined('RESTORE_SILENTLY')) {
2321 echo '<li>'.get_string('gradeoutcomeshistory','grades').'</li>';
2323 $counter = 0;
2324 while ($counter < $gohcount) {
2325 //Fetch recordset_size records in each iteration
2326 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes_history' AND backup_code = '$restore->backup_unique_code'",
2327 "old_id",
2328 "old_id",
2329 $counter,
2330 $recordset_size);
2331 if ($recs) {
2332 foreach ($recs as $rec) {
2333 //Get the full record from backup_ids
2334 $data = backup_getid($restore->backup_unique_code,'grade_outcomes_history',$rec->old_id);
2335 if ($data) {
2336 //Now get completed xmlized object
2337 $info = $data->info;
2338 //traverse_xmlize($info); //Debug
2339 //print_object ($GLOBALS['traverse_array']); //Debug
2340 //$GLOBALS['traverse_array']=""; //Debug
2342 $oldobj = backup_getid($restore->backup_unique_code,"grade_outcomes", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['OLDID']['0']['#']));
2343 if (empty($oldobj->new_id)) {
2344 // if the old object is not being restored, can't restoring its history
2345 $counter++;
2346 continue;
2348 $dbrec->oldid = $oldobj->new_id;
2349 $dbrec->action = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['ACTION']['0']['#']);
2350 $dbrec->source = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SOURCE']['0']['#']);
2351 $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2352 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2353 $dbrec->loggeduser = $oldobj->new_id;
2355 $dbrec->courseid = $restore->course_id;
2356 $dbrec->shortname = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SHORTNAME']['0']['#']);
2357 $dbrec->fullname= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['FULLNAME']['0']['#']);
2358 $oldobj = backup_getid($restore->backup_unique_code,"scale", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SCALEID']['0']['#']));
2359 $dbrec->scaleid = $oldobj->new_id;
2360 $dbrec->description = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['DESCRIPTION']['0']['#']);
2362 insert_record('grade_outcomes_history', $dbrec);
2363 unset($dbrec);
2366 //Increment counters
2367 $counter++;
2368 //Do some output
2369 if ($counter % 1 == 0) {
2370 if (!defined('RESTORE_SILENTLY')) {
2371 echo ".";
2372 if ($counter % 20 == 0) {
2373 echo "<br />";
2376 backup_flush(300);
2384 if (!defined('RESTORE_SILENTLY')) {
2385 //End ul
2386 echo '</ul>';
2388 return $status;
2391 //This function creates all the user, user_students, user_teachers
2392 //user_course_creators and user_admins from xml
2393 function restore_create_users($restore,$xml_file) {
2395 global $CFG, $db;
2396 require_once ($CFG->dirroot.'/tag/lib.php');
2398 $status = true;
2399 //Check it exists
2400 if (!file_exists($xml_file)) {
2401 $status = false;
2403 //Get info from xml
2404 if ($status) {
2405 //info will contain the old_id of every user
2406 //in backup_ids->info will be the real info (serialized)
2407 $info = restore_read_xml_users($restore,$xml_file);
2410 //Now, get evey user_id from $info and user data from $backup_ids
2411 //and create the necessary db structures
2413 if (!empty($info->users)) {
2415 /// Grab mnethosts keyed by wwwroot, to map to id
2416 $mnethosts = get_records('mnet_host', '', '',
2417 'wwwroot', 'wwwroot, id');
2419 /// Get languages for quick search later
2420 $languages = get_list_of_languages();
2422 /// Iterate over all users loaded from xml
2423 $counter = 0;
2424 foreach ($info->users as $userid) {
2425 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
2426 $user = $rec->info;
2427 foreach (array_keys(get_object_vars($user)) as $field) {
2428 if (!is_array($user->$field)) {
2429 $user->$field = backup_todb($user->$field);
2430 if (is_null($user->$field)) {
2431 $user->$field = '';
2436 //Now, recode some languages (Moodle 1.5)
2437 if ($user->lang == 'ma_nt') {
2438 $user->lang = 'mi_nt';
2441 //Country list updates - MDL-13060
2442 //Any user whose country code has been deleted or modified needs to be assigned a valid one.
2443 $country_update_map = array(
2444 'ZR' => 'CD',
2445 'TP' => 'TL',
2446 'FX' => 'FR',
2447 'KO' => 'RS',
2448 'CS' => 'RS',
2449 'WA' => 'GB');
2450 if (array_key_exists($user->country, $country_update_map)) {
2451 $user->country = $country_update_map[$user->country];
2454 //If language does not exist here - use site default
2455 if (!array_key_exists($user->lang, $languages)) {
2456 $user->lang = $CFG->lang;
2459 //Check if it's admin and coursecreator
2460 $is_admin = !empty($user->roles['admin']);
2461 $is_coursecreator = !empty($user->roles['coursecreator']);
2463 //Check if it's teacher and student
2464 $is_teacher = !empty($user->roles['teacher']);
2465 $is_student = !empty($user->roles['student']);
2467 //Check if it's needed
2468 $is_needed = !empty($user->roles['needed']);
2470 //Calculate if it is a course user
2471 //Has role teacher or student or needed
2472 $is_course_user = ($is_teacher or $is_student or $is_needed);
2474 //Calculate mnethostid
2475 if (empty($user->mnethosturl) || $user->mnethosturl===$CFG->wwwroot) {
2476 $user->mnethostid = $CFG->mnet_localhost_id;
2477 } else {
2478 // fast url-to-id lookups
2479 if (isset($mnethosts[$user->mnethosturl])) {
2480 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
2481 } else {
2482 // should not happen, as we check in restore_chech.php
2483 // but handle the error if it does
2484 error("This backup file contains external Moodle Network Hosts that are not configured locally.");
2487 unset($user->mnethosturl);
2489 //To store user->id along all the iteration
2490 $newid=null;
2491 //check if it exists (by username) and get its id
2492 $user_exists = true;
2493 $user_data = get_record("user","username",addslashes($user->username),
2494 'mnethostid', $user->mnethostid);
2495 if (!$user_data) {
2496 $user_exists = false;
2497 } else {
2498 $newid = $user_data->id;
2501 //Flags to see what parts are we going to restore
2502 $create_user = true;
2503 $create_roles = true;
2504 $create_custom_profile_fields = true;
2505 $create_tags = true;
2506 $create_preferences = true;
2508 //If we are restoring course users and it isn't a course user
2509 if ($restore->users == 1 and !$is_course_user) {
2510 //If only restoring course_users and user isn't a course_user, inform to $backup_ids
2511 $status = backup_putid($restore->backup_unique_code,"user",$userid,null,'notincourse');
2512 $create_user = false;
2513 $create_roles = false;
2514 $create_custom_profile_fields = false;
2515 $create_tags = false;
2516 $create_preferences = false;
2519 if ($user_exists and $create_user) {
2520 //If user exists mark its newid in backup_ids (the same than old)
2521 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,'exists');
2522 $create_user = false;
2523 $create_custom_profile_fields = false;
2524 $create_tags = false;
2525 $create_preferences = false;
2528 //Here, if create_user, do it
2529 if ($create_user) {
2530 //Unset the id because it's going to be inserted with a new one
2531 unset ($user->id);
2532 // relink the descriptions
2533 $user->description = stripslashes($user->description);
2535 /// Disable pictures based on global setting or existing empty value (old backups can contain wrong empties)
2536 if (!empty($CFG->disableuserimages) || empty($user->picture)) {
2537 $user->picture = 0;
2540 //We need to analyse the AUTH field to recode it:
2541 // - if the field isn't set, we are in a pre 1.4 backup and we'll
2542 // use manual
2544 if (empty($user->auth)) {
2545 if ($CFG->registerauth == 'email') {
2546 $user->auth = 'email';
2547 } else {
2548 $user->auth = 'manual';
2552 //We need to process the POLICYAGREED field to recalculate it:
2553 // - if the destination site is different (by wwwroot) reset it.
2554 // - if the destination site is the same (by wwwroot), leave it unmodified
2556 if ($restore->original_wwwroot != $CFG->wwwroot) {
2557 $user->policyagreed = 0;
2558 } else {
2559 //Nothing to do, we are in the same server
2562 //Check if the theme exists in destination server
2563 $themes = get_list_of_themes();
2564 if (!in_array($user->theme, $themes)) {
2565 $user->theme = '';
2568 //We are going to create the user
2569 //The structure is exactly as we need
2571 $newid = insert_record ("user", addslashes_recursive($user));
2572 //Put the new id
2573 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,"new");
2576 ///TODO: This seccion is to support pre 1.7 course backups, using old roles
2577 /// teacher, coursecreator, student.... providing a basic mapping to new ones.
2578 /// Someday we'll drop support for them and this section will be safely deleted (2.0?)
2579 //Here, if create_roles, do it as necessary
2580 if ($create_roles) {
2581 //Get the newid and current info from backup_ids
2582 $data = backup_getid($restore->backup_unique_code,"user",$userid);
2583 $newid = $data->new_id;
2584 $currinfo = $data->info.",";
2586 //Now, depending of the role, create records in user_studentes and user_teacher
2587 //and/or mark it in backup_ids
2589 if ($is_admin) {
2590 //If the record (user_admins) doesn't exists
2591 //Only put status in backup_ids
2592 $currinfo = $currinfo."admin,";
2593 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2595 if ($is_coursecreator) {
2596 //If the record (user_coursecreators) doesn't exists
2597 //Only put status in backup_ids
2598 $currinfo = $currinfo."coursecreator,";
2599 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2601 if ($is_needed) {
2602 //Only put status in backup_ids
2603 $currinfo = $currinfo."needed,";
2604 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2606 if ($is_teacher) {
2607 //If the record (teacher) doesn't exists
2608 //Put status in backup_ids
2609 $currinfo = $currinfo."teacher,";
2610 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2611 //Set course and user
2612 $user->roles['teacher']->course = $restore->course_id;
2613 $user->roles['teacher']->userid = $newid;
2615 //Need to analyse the enrol field
2616 // - if it isn't set, set it to $CFG->enrol
2617 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2618 // - if we are in the same server (by wwwroot), maintain it unmodified.
2619 if (empty($user->roles['teacher']->enrol)) {
2620 $user->roles['teacher']->enrol = $CFG->enrol;
2621 } else if ($restore->original_wwwroot != $CFG->wwwroot) {
2622 $user->roles['teacher']->enrol = $CFG->enrol;
2623 } else {
2624 //Nothing to do. Leave it unmodified
2627 $rolesmapping = $restore->rolesmapping;
2628 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
2629 if ($user->roles['teacher']->editall) {
2630 role_assign($rolesmapping['defaultteacheredit'],
2631 $newid,
2633 $context->id,
2634 $user->roles['teacher']->timestart,
2635 $user->roles['teacher']->timeend,
2637 $user->roles['teacher']->enrol);
2639 // editting teacher
2640 } else {
2641 // non editting teacher
2642 role_assign($rolesmapping['defaultteacher'],
2643 $newid,
2645 $context->id,
2646 $user->roles['teacher']->timestart,
2647 $user->roles['teacher']->timeend,
2649 $user->roles['teacher']->enrol);
2652 if ($is_student) {
2654 //Put status in backup_ids
2655 $currinfo = $currinfo."student,";
2656 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2657 //Set course and user
2658 $user->roles['student']->course = $restore->course_id;
2659 $user->roles['student']->userid = $newid;
2661 //Need to analyse the enrol field
2662 // - if it isn't set, set it to $CFG->enrol
2663 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2664 // - if we are in the same server (by wwwroot), maintain it unmodified.
2665 if (empty($user->roles['student']->enrol)) {
2666 $user->roles['student']->enrol = $CFG->enrol;
2667 } else if ($restore->original_wwwroot != $CFG->wwwroot) {
2668 $user->roles['student']->enrol = $CFG->enrol;
2669 } else {
2670 //Nothing to do. Leave it unmodified
2672 $rolesmapping = $restore->rolesmapping;
2673 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
2675 role_assign($rolesmapping['defaultstudent'],
2676 $newid,
2678 $context->id,
2679 $user->roles['student']->timestart,
2680 $user->roles['student']->timeend,
2682 $user->roles['student']->enrol);
2685 if (!$is_course_user) {
2686 //If the record (user) doesn't exists
2687 if (!record_exists("user","id",$newid)) {
2688 //Put status in backup_ids
2689 $currinfo = $currinfo."user,";
2690 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2695 /// Here, if create_custom_profile_fields, do it as necessary
2696 if ($create_custom_profile_fields) {
2697 if (isset($user->user_custom_profile_fields)) {
2698 foreach($user->user_custom_profile_fields as $udata) {
2699 /// If the profile field has data and the profile shortname-datatype is defined in server
2700 if ($udata->field_data) {
2701 if ($field = get_record('user_info_field', 'shortname', $udata->field_name, 'datatype', $udata->field_type)) {
2702 /// Insert the user_custom_profile_field
2703 $rec = new object();
2704 $rec->userid = $newid;
2705 $rec->fieldid = $field->id;
2706 $rec->data = $udata->field_data;
2707 insert_record('user_info_data', $rec);
2714 /// Here, if create_tags, do it as necessary
2715 if ($create_tags) {
2716 /// if tags are enabled and there are user tags
2717 if (!empty($CFG->usetags) && isset($user->user_tags)) {
2718 $tags = array();
2719 foreach($user->user_tags as $user_tag) {
2720 $tags[] = $user_tag->rawname;
2722 tag_set('user', $newid, $tags);
2726 //Here, if create_preferences, do it as necessary
2727 if ($create_preferences) {
2728 if (isset($user->user_preferences)) {
2729 foreach($user->user_preferences as $user_preference) {
2730 //We check if that user_preference exists in DB
2731 if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name)) {
2732 //Prepare the record and insert it
2733 $user_preference->userid = $newid;
2734 $status = insert_record("user_preferences",$user_preference);
2740 //Do some output
2741 $counter++;
2742 if ($counter % 10 == 0) {
2743 if (!defined('RESTORE_SILENTLY')) {
2744 echo ".";
2745 if ($counter % 200 == 0) {
2746 echo "<br />";
2749 backup_flush(300);
2751 } /// End of loop over all the users loaded from xml
2754 return $status;
2757 //This function creates all the structures messages and contacts
2758 function restore_create_messages($restore,$xml_file) {
2760 global $CFG;
2762 $status = true;
2763 //Check it exists
2764 if (!file_exists($xml_file)) {
2765 $status = false;
2767 //Get info from xml
2768 if ($status) {
2769 //info will contain the id and name of every table
2770 //(message, message_read and message_contacts)
2771 //in backup_ids->info will be the real info (serialized)
2772 $info = restore_read_xml_messages($restore,$xml_file);
2774 //If we have info, then process messages & contacts
2775 if ($info > 0) {
2776 //Count how many we have
2777 $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message');
2778 $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_read');
2779 $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_contacts');
2780 if ($unreadcount || $readcount || $contactcount) {
2781 //Start ul
2782 if (!defined('RESTORE_SILENTLY')) {
2783 echo '<ul>';
2785 //Number of records to get in every chunk
2786 $recordset_size = 4;
2788 //Process unread
2789 if ($unreadcount) {
2790 if (!defined('RESTORE_SILENTLY')) {
2791 echo '<li>'.get_string('unreadmessages','message').'</li>';
2793 $counter = 0;
2794 while ($counter < $unreadcount) {
2795 //Fetch recordset_size records in each iteration
2796 $recs = get_records_select("backup_ids","table_name = 'message' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2797 if ($recs) {
2798 foreach ($recs as $rec) {
2799 //Get the full record from backup_ids
2800 $data = backup_getid($restore->backup_unique_code,"message",$rec->old_id);
2801 if ($data) {
2802 //Now get completed xmlized object
2803 $info = $data->info;
2804 //traverse_xmlize($info); //Debug
2805 //print_object ($GLOBALS['traverse_array']); //Debug
2806 //$GLOBALS['traverse_array']=""; //Debug
2807 //Now build the MESSAGE record structure
2808 $dbrec = new object();
2809 $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2810 $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2811 $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2812 $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2813 $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2814 $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2815 //We have to recode the useridfrom field
2816 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
2817 if ($user) {
2818 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2819 $dbrec->useridfrom = $user->new_id;
2821 //We have to recode the useridto field
2822 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
2823 if ($user) {
2824 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2825 $dbrec->useridto = $user->new_id;
2827 //Check if the record doesn't exist in DB!
2828 $exist = get_record('message','useridfrom',$dbrec->useridfrom,
2829 'useridto', $dbrec->useridto,
2830 'timecreated',$dbrec->timecreated);
2831 if (!$exist) {
2832 //Not exist. Insert
2833 $status = insert_record('message',$dbrec);
2834 } else {
2835 //Duplicate. Do nothing
2838 //Do some output
2839 $counter++;
2840 if ($counter % 10 == 0) {
2841 if (!defined('RESTORE_SILENTLY')) {
2842 echo ".";
2843 if ($counter % 200 == 0) {
2844 echo "<br />";
2847 backup_flush(300);
2854 //Process read
2855 if ($readcount) {
2856 if (!defined('RESTORE_SILENTLY')) {
2857 echo '<li>'.get_string('readmessages','message').'</li>';
2859 $counter = 0;
2860 while ($counter < $readcount) {
2861 //Fetch recordset_size records in each iteration
2862 $recs = get_records_select("backup_ids","table_name = 'message_read' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2863 if ($recs) {
2864 foreach ($recs as $rec) {
2865 //Get the full record from backup_ids
2866 $data = backup_getid($restore->backup_unique_code,"message_read",$rec->old_id);
2867 if ($data) {
2868 //Now get completed xmlized object
2869 $info = $data->info;
2870 //traverse_xmlize($info); //Debug
2871 //print_object ($GLOBALS['traverse_array']); //Debug
2872 //$GLOBALS['traverse_array']=""; //Debug
2873 //Now build the MESSAGE_READ record structure
2874 $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2875 $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2876 $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2877 $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2878 $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2879 $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2880 $dbrec->timeread = backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
2881 $dbrec->mailed = backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
2882 //We have to recode the useridfrom field
2883 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
2884 if ($user) {
2885 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2886 $dbrec->useridfrom = $user->new_id;
2888 //We have to recode the useridto field
2889 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
2890 if ($user) {
2891 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2892 $dbrec->useridto = $user->new_id;
2894 //Check if the record doesn't exist in DB!
2895 $exist = get_record('message_read','useridfrom',$dbrec->useridfrom,
2896 'useridto', $dbrec->useridto,
2897 'timecreated',$dbrec->timecreated);
2898 if (!$exist) {
2899 //Not exist. Insert
2900 $status = insert_record('message_read',$dbrec);
2901 } else {
2902 //Duplicate. Do nothing
2905 //Do some output
2906 $counter++;
2907 if ($counter % 10 == 0) {
2908 if (!defined('RESTORE_SILENTLY')) {
2909 echo ".";
2910 if ($counter % 200 == 0) {
2911 echo "<br />";
2914 backup_flush(300);
2921 //Process contacts
2922 if ($contactcount) {
2923 if (!defined('RESTORE_SILENTLY')) {
2924 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
2926 $counter = 0;
2927 while ($counter < $contactcount) {
2928 //Fetch recordset_size records in each iteration
2929 $recs = get_records_select("backup_ids","table_name = 'message_contacts' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2930 if ($recs) {
2931 foreach ($recs as $rec) {
2932 //Get the full record from backup_ids
2933 $data = backup_getid($restore->backup_unique_code,"message_contacts",$rec->old_id);
2934 if ($data) {
2935 //Now get completed xmlized object
2936 $info = $data->info;
2937 //traverse_xmlize($info); //Debug
2938 //print_object ($GLOBALS['traverse_array']); //Debug
2939 //$GLOBALS['traverse_array']=""; //Debug
2940 //Now build the MESSAGE_CONTACTS record structure
2941 $dbrec->userid = backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
2942 $dbrec->contactid = backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
2943 $dbrec->blocked = backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
2944 //We have to recode the userid field
2945 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->userid);
2946 if ($user) {
2947 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
2948 $dbrec->userid = $user->new_id;
2950 //We have to recode the contactid field
2951 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->contactid);
2952 if ($user) {
2953 //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />"; //Debug
2954 $dbrec->contactid = $user->new_id;
2956 //Check if the record doesn't exist in DB!
2957 $exist = get_record('message_contacts','userid',$dbrec->userid,
2958 'contactid', $dbrec->contactid);
2959 if (!$exist) {
2960 //Not exist. Insert
2961 $status = insert_record('message_contacts',$dbrec);
2962 } else {
2963 //Duplicate. Do nothing
2966 //Do some output
2967 $counter++;
2968 if ($counter % 10 == 0) {
2969 if (!defined('RESTORE_SILENTLY')) {
2970 echo ".";
2971 if ($counter % 200 == 0) {
2972 echo "<br />";
2975 backup_flush(300);
2981 if (!defined('RESTORE_SILENTLY')) {
2982 //End ul
2983 echo '</ul>';
2989 return $status;
2992 //This function creates all the structures for blogs and blog tags
2993 function restore_create_blogs($restore,$xml_file) {
2995 global $CFG;
2997 $status = true;
2998 //Check it exists
2999 if (!file_exists($xml_file)) {
3000 $status = false;
3002 //Get info from xml
3003 if ($status) {
3004 //info will contain the number of blogs in the backup file
3005 //in backup_ids->info will be the real info (serialized)
3006 $info = restore_read_xml_blogs($restore,$xml_file);
3008 //If we have info, then process blogs & blog_tags
3009 if ($info > 0) {
3010 //Count how many we have
3011 $blogcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'blog');
3012 if ($blogcount) {
3013 //Number of records to get in every chunk
3014 $recordset_size = 4;
3016 //Process blog
3017 if ($blogcount) {
3018 $counter = 0;
3019 while ($counter < $blogcount) {
3020 //Fetch recordset_size records in each iteration
3021 $recs = get_records_select("backup_ids","table_name = 'blog' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
3022 if ($recs) {
3023 foreach ($recs as $rec) {
3024 //Get the full record from backup_ids
3025 $data = backup_getid($restore->backup_unique_code,"blog",$rec->old_id);
3026 if ($data) {
3027 //Now get completed xmlized object
3028 $info = $data->info;
3029 //traverse_xmlize($info); //Debug
3030 //print_object ($GLOBALS['traverse_array']); //Debug
3031 //$GLOBALS['traverse_array']=""; //Debug
3032 //Now build the BLOG record structure
3033 $dbrec = new object();
3034 $dbrec->module = backup_todb($info['BLOG']['#']['MODULE']['0']['#']);
3035 $dbrec->userid = backup_todb($info['BLOG']['#']['USERID']['0']['#']);
3036 $dbrec->courseid = backup_todb($info['BLOG']['#']['COURSEID']['0']['#']);
3037 $dbrec->groupid = backup_todb($info['BLOG']['#']['GROUPID']['0']['#']);
3038 $dbrec->moduleid = backup_todb($info['BLOG']['#']['MODULEID']['0']['#']);
3039 $dbrec->coursemoduleid = backup_todb($info['BLOG']['#']['COURSEMODULEID']['0']['#']);
3040 $dbrec->subject = backup_todb($info['BLOG']['#']['SUBJECT']['0']['#']);
3041 $dbrec->summary = backup_todb($info['BLOG']['#']['SUMMARY']['0']['#']);
3042 $dbrec->content = backup_todb($info['BLOG']['#']['CONTENT']['0']['#']);
3043 $dbrec->uniquehash = backup_todb($info['BLOG']['#']['UNIQUEHASH']['0']['#']);
3044 $dbrec->rating = backup_todb($info['BLOG']['#']['RATING']['0']['#']);
3045 $dbrec->format = backup_todb($info['BLOG']['#']['FORMAT']['0']['#']);
3046 $dbrec->attachment = backup_todb($info['BLOG']['#']['ATTACHMENT']['0']['#']);
3047 $dbrec->publishstate = backup_todb($info['BLOG']['#']['PUBLISHSTATE']['0']['#']);
3048 $dbrec->lastmodified = backup_todb($info['BLOG']['#']['LASTMODIFIED']['0']['#']);
3049 $dbrec->created = backup_todb($info['BLOG']['#']['CREATED']['0']['#']);
3050 $dbrec->usermodified = backup_todb($info['BLOG']['#']['USERMODIFIED']['0']['#']);
3052 //We have to recode the userid field
3053 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->userid);
3054 if ($user) {
3055 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
3056 $dbrec->userid = $user->new_id;
3059 //Check if the record doesn't exist in DB!
3060 $exist = get_record('post','userid', $dbrec->userid,
3061 'subject', $dbrec->subject,
3062 'created', $dbrec->created);
3063 $newblogid = 0;
3064 if (!$exist) {
3065 //Not exist. Insert
3066 $newblogid = insert_record('post',$dbrec);
3069 //Going to restore related tags. Check they are enabled and we have inserted a blog
3070 if ($CFG->usetags && $newblogid) {
3071 //Look for tags in this blog
3072 if (isset($info['BLOG']['#']['BLOG_TAGS']['0']['#']['BLOG_TAG'])) {
3073 $tagsarr = $info['BLOG']['#']['BLOG_TAGS']['0']['#']['BLOG_TAG'];
3074 //Iterate over tags
3075 $tags = array();
3076 for($i = 0; $i < sizeof($tagsarr); $i++) {
3077 $tag_info = $tagsarr[$i];
3078 ///traverse_xmlize($tag_info); //Debug
3079 ///print_object ($GLOBALS['traverse_array']); //Debug
3080 ///$GLOBALS['traverse_array']=""; //Debug
3082 $name = backup_todb($tag_info['#']['NAME']['0']['#']);
3083 $rawname = backup_todb($tag_info['#']['RAWNAME']['0']['#']);
3085 $tags[] = $rawname; //Rawname is all we need
3087 tag_set('post', $newblogid, $tags); //Add all the tags in one API call
3091 //Do some output
3092 $counter++;
3093 if ($counter % 10 == 0) {
3094 if (!defined('RESTORE_SILENTLY')) {
3095 echo ".";
3096 if ($counter % 200 == 0) {
3097 echo "<br />";
3100 backup_flush(300);
3110 return $status;
3113 //This function creates all the categories and questions
3114 //from xml
3115 function restore_create_questions($restore,$xml_file) {
3117 global $CFG, $db;
3119 $status = true;
3120 //Check it exists
3121 if (!file_exists($xml_file)) {
3122 $status = false;
3124 //Get info from xml
3125 if ($status) {
3126 //info will contain the old_id of every category
3127 //in backup_ids->info will be the real info (serialized)
3128 $info = restore_read_xml_questions($restore,$xml_file);
3130 //Now, if we have anything in info, we have to restore that
3131 //categories/questions
3132 if ($info) {
3133 if ($info !== true) {
3134 $status = $status && restore_question_categories($info, $restore);
3136 } else {
3137 $status = false;
3139 return $status;
3142 //This function creates all the scales
3143 function restore_create_scales($restore,$xml_file) {
3145 global $CFG, $db;
3147 $status = true;
3148 //Check it exists
3149 if (!file_exists($xml_file)) {
3150 $status = false;
3152 //Get info from xml
3153 if ($status) {
3154 //scales will contain the old_id of every scale
3155 //in backup_ids->info will be the real info (serialized)
3156 $scales = restore_read_xml_scales($restore,$xml_file);
3158 //Now, if we have anything in scales, we have to restore that
3159 //scales
3160 if ($scales) {
3161 //Get admin->id for later use
3162 $admin = get_admin();
3163 $adminid = $admin->id;
3164 if ($scales !== true) {
3165 //Iterate over each scale
3166 foreach ($scales as $scale) {
3167 //Get record from backup_ids
3168 $data = backup_getid($restore->backup_unique_code,"scale",$scale->id);
3169 //Init variables
3170 $create_scale = false;
3172 if ($data) {
3173 //Now get completed xmlized object
3174 $info = $data->info;
3175 //traverse_xmlize($info); //Debug
3176 //print_object ($GLOBALS['traverse_array']); //Debug
3177 //$GLOBALS['traverse_array']=""; //Debug
3179 //Now build the SCALE record structure
3180 $sca = new object();
3181 $sca->courseid = backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
3182 $sca->userid = backup_todb($info['SCALE']['#']['USERID']['0']['#']);
3183 $sca->name = backup_todb($info['SCALE']['#']['NAME']['0']['#']);
3184 $sca->scale = backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
3185 $sca->description = backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
3186 $sca->timemodified = backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);
3188 //Now search if that scale exists (by scale field) in course 0 (Standar scale)
3189 //or in restore->course_id course (Personal scale)
3190 if ($sca->courseid == 0) {
3191 $course_to_search = 0;
3192 } else {
3193 $course_to_search = $restore->course_id;
3196 // scale is not course unique, use get_record_sql to suppress warning
3198 $sca_db = get_record_sql("SELECT * FROM {$CFG->prefix}scale
3199 WHERE scale = '$sca->scale'
3200 AND courseid = $course_to_search", true);
3202 //If it doesn't exist, create
3203 if (!$sca_db) {
3204 $create_scale = true;
3206 //If we must create the scale
3207 if ($create_scale) {
3208 //Me must recode the courseid if it's <> 0 (common scale)
3209 if ($sca->courseid != 0) {
3210 $sca->courseid = $restore->course_id;
3212 //We must recode the userid
3213 $user = backup_getid($restore->backup_unique_code,"user",$sca->userid);
3214 if ($user) {
3215 $sca->userid = $user->new_id;
3216 } else {
3217 //Assign it to admin
3218 $sca->userid = $adminid;
3220 //The structure is equal to the db, so insert the scale
3221 $newid = insert_record ("scale",$sca);
3222 } else {
3223 //get current scale id
3224 $newid = $sca_db->id;
3226 if ($newid) {
3227 //We have the newid, update backup_ids
3228 backup_putid($restore->backup_unique_code,"scale",
3229 $scale->id, $newid);
3234 } else {
3235 $status = false;
3237 return $status;
3241 * Recode group ID field, and set group ID based on restore options.
3242 * @return object Group object with new_id field.
3244 function restore_group_getid($restore, $groupid) {
3245 //We have to recode the groupid field
3246 $group = backup_getid($restore->backup_unique_code, 'groups', $groupid);
3248 if ($restore->groups == RESTORE_GROUPS_NONE or $restore->groups == RESTORE_GROUPINGS_ONLY) {
3249 $group->new_id = 0;
3251 return $group;
3255 * Recode grouping ID field, and set grouping ID based on restore options.
3256 * @return object Group object with new_id field.
3258 function restore_grouping_getid($restore, $groupingid) {
3259 //We have to recode the groupid field
3260 $grouping = backup_getid($restore->backup_unique_code, 'groupings', $groupingid);
3262 if ($restore->groups != RESTORE_GROUPS_GROUPINGS and $restore->groups != RESTORE_GROUPINGS_ONLY) {
3263 $grouping->new_id = 0;
3265 return $grouping;
3268 //This function creates all the groups
3269 function restore_create_groups($restore,$xml_file) {
3271 global $CFG;
3273 //Check it exists
3274 if (!file_exists($xml_file)) {
3275 return false;
3277 //Get info from xml
3278 if (!$groups = restore_read_xml_groups($restore,$xml_file)) {
3279 //groups will contain the old_id of every group
3280 //in backup_ids->info will be the real info (serialized)
3281 return false;
3283 } else if ($groups === true) {
3284 return true;
3287 $status = true;
3289 //Iterate over each group
3290 foreach ($groups as $group) {
3291 //Get record from backup_ids
3292 $data = backup_getid($restore->backup_unique_code,"groups",$group->id);
3294 if ($data) {
3295 //Now get completed xmlized object
3296 $info = $data->info;
3297 //traverse_xmlize($info); //Debug
3298 //print_object ($GLOBALS['traverse_array']); //Debug
3299 //$GLOBALS['traverse_array']=""; //Debug
3300 //Now build the GROUP record structure
3301 $gro = new Object();
3302 $gro->courseid = $restore->course_id;
3303 $gro->name = backup_todb($info['GROUP']['#']['NAME']['0']['#']);
3304 $gro->description = backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
3305 if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) {
3306 $gro->enrolmentkey = backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']);
3307 } else {
3308 $gro->enrolmentkey = backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
3310 $gro->picture = backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
3311 $gro->hidepicture = backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
3312 $gro->timecreated = backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
3313 $gro->timemodified = backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
3315 //Now search if that group exists (by name and description field) in
3316 //restore->course_id course
3317 //Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides.
3318 $description_clause = '';
3319 if (!empty($gro->description)) { /// Only for groups having a description
3320 $literal_description = "'" . $gro->description . "'";
3321 $description_clause = " AND " .
3322 sql_compare_text('description') . " = " .
3323 sql_compare_text($literal_description);
3325 if (!$gro_db = get_record_sql("SELECT *
3326 FROM {$CFG->prefix}groups
3327 WHERE courseid = $restore->course_id AND
3328 name = '{$gro->name}'" . $description_clause, true)) {
3329 //If it doesn't exist, create
3330 $newid = insert_record('groups', $gro);
3332 } else {
3333 //get current group id
3334 $newid = $gro_db->id;
3337 if ($newid) {
3338 //We have the newid, update backup_ids
3339 backup_putid($restore->backup_unique_code,"groups", $group->id, $newid);
3340 } else {
3342 $status = false;
3343 continue;
3346 //Now restore members in the groups_members, only if
3347 //users are included
3348 if ($restore->users != 2) {
3349 if (!restore_create_groups_members($newid,$info,$restore)) {
3350 $status = false;
3356 //Now, restore group_files
3357 if ($status) {
3358 $status = restore_group_files($restore);
3361 return $status;
3364 //This function restores the groups_members
3365 function restore_create_groups_members($group_id,$info,$restore) {
3367 if (! isset($info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'])) {
3368 //OK, some groups have no members.
3369 return true;
3371 //Get the members array
3372 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
3374 $status = true;
3376 //Iterate over members
3377 for($i = 0; $i < sizeof($members); $i++) {
3378 $mem_info = $members[$i];
3379 //traverse_xmlize($mem_info); //Debug
3380 //print_object ($GLOBALS['traverse_array']); //Debug
3381 //$GLOBALS['traverse_array']=""; //Debug
3383 //Now, build the GROUPS_MEMBERS record structure
3384 $group_member = new Object();
3385 $group_member->groupid = $group_id;
3386 $group_member->userid = backup_todb($mem_info['#']['USERID']['0']['#']);
3387 $group_member->timeadded = backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
3389 $newid = false;
3391 //We have to recode the userid field
3392 if (!$user = backup_getid($restore->backup_unique_code,"user",$group_member->userid)) {
3393 debugging("group membership can not be restored, user id $group_member->userid not present in backup");
3394 // do not not block the restore
3395 continue;
3398 $group_member->userid = $user->new_id;
3400 //The structure is equal to the db, so insert the groups_members
3401 if (!insert_record ("groups_members", $group_member)) {
3402 $status = false;
3403 continue;
3406 //Do some output
3407 if (($i+1) % 50 == 0) {
3408 if (!defined('RESTORE_SILENTLY')) {
3409 echo ".";
3410 if (($i+1) % 1000 == 0) {
3411 echo "<br />";
3414 backup_flush(300);
3418 return $status;
3421 //This function creates all the groupings
3422 function restore_create_groupings($restore,$xml_file) {
3424 //Check it exists
3425 if (!file_exists($xml_file)) {
3426 return false;
3428 //Get info from xml
3429 if (!$groupings = restore_read_xml_groupings($restore,$xml_file)) {
3430 return false;
3432 } else if ($groupings === true) {
3433 return true;
3436 $status = true;
3438 //Iterate over each group
3439 foreach ($groupings as $grouping) {
3440 if ($data = backup_getid($restore->backup_unique_code,"groupings",$grouping->id)) {
3441 //Now get completed xmlized object
3442 $info = $data->info;
3443 //Now build the GROUPING record structure
3444 $gro = new Object();
3445 ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']);
3446 $gro->courseid = $restore->course_id;
3447 $gro->name = backup_todb($info['GROUPING']['#']['NAME']['0']['#']);
3448 $gro->description = backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']);
3449 $gro->configdata = backup_todb($info['GROUPING']['#']['CONFIGDATA']['0']['#']);
3450 $gro->timecreated = backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']);
3452 //Now search if that group exists (by name and description field) in
3453 if ($gro_db = get_record('groupings', 'courseid', $restore->course_id, 'name', $gro->name, 'description', $gro->description)) {
3454 //get current group id
3455 $newid = $gro_db->id;
3457 } else {
3458 //The structure is equal to the db, so insert the grouping
3459 if (!$newid = insert_record('groupings', $gro)) {
3460 $status = false;
3461 continue;
3465 //We have the newid, update backup_ids
3466 backup_putid($restore->backup_unique_code,"groupings",
3467 $grouping->id, $newid);
3472 // now fix the defaultgroupingid in course
3473 $course = get_record('course', 'id', $restore->course_id);
3474 if ($course->defaultgroupingid) {
3475 if ($grouping = restore_grouping_getid($restore, $course->defaultgroupingid)) {
3476 set_field('course', 'defaultgroupingid', $grouping->new_id, 'id', $course->id);
3477 } else {
3478 set_field('course', 'defaultgroupingid', 0, 'id', $course->id);
3482 return $status;
3485 //This function creates all the groupingsgroups
3486 function restore_create_groupings_groups($restore,$xml_file) {
3488 //Check it exists
3489 if (!file_exists($xml_file)) {
3490 return false;
3492 //Get info from xml
3493 if (!$groupingsgroups = restore_read_xml_groupings_groups($restore,$xml_file)) {
3494 return false;
3496 } else if ($groupingsgroups === true) {
3497 return true;
3500 $status = true;
3502 //Iterate over each group
3503 foreach ($groupingsgroups as $groupinggroup) {
3504 if ($data = backup_getid($restore->backup_unique_code,"groupingsgroups",$groupinggroup->id)) {
3505 //Now get completed xmlized object
3506 $info = $data->info;
3507 //Now build the GROUPING record structure
3508 $gro_member = new Object();
3509 $gro_member->groupingid = backup_todb($info['GROUPINGGROUP']['#']['GROUPINGID']['0']['#']);
3510 $gro_member->groupid = backup_todb($info['GROUPINGGROUP']['#']['GROUPID']['0']['#']);
3511 $gro_member->timeadded = backup_todb($info['GROUPINGGROUP']['#']['TIMEADDED']['0']['#']);
3513 if (!$grouping = backup_getid($restore->backup_unique_code,"groupings",$gro_member->groupingid)) {
3514 $status = false;
3515 continue;
3518 if (!$group = backup_getid($restore->backup_unique_code,"groups",$gro_member->groupid)) {
3519 $status = false;
3520 continue;
3523 $gro_member->groupid = $group->new_id;
3524 $gro_member->groupingid = $grouping->new_id;
3525 if (!get_record('groupings_groups', 'groupid', $gro_member->groupid, 'groupingid', $gro_member->groupingid)) {
3526 if (!insert_record('groupings_groups', $gro_member)) {
3527 $status = false;
3533 return $status;
3536 //This function creates all the course events
3537 function restore_create_events($restore,$xml_file) {
3539 global $CFG, $db;
3541 $status = true;
3542 //Check it exists
3543 if (!file_exists($xml_file)) {
3544 $status = false;
3546 //Get info from xml
3547 if ($status) {
3548 //events will contain the old_id of every event
3549 //in backup_ids->info will be the real info (serialized)
3550 $events = restore_read_xml_events($restore,$xml_file);
3553 //Get admin->id for later use
3554 $admin = get_admin();
3555 $adminid = $admin->id;
3557 //Now, if we have anything in events, we have to restore that
3558 //events
3559 if ($events) {
3560 if ($events !== true) {
3561 //Iterate over each event
3562 foreach ($events as $event) {
3563 //Get record from backup_ids
3564 $data = backup_getid($restore->backup_unique_code,"event",$event->id);
3565 //Init variables
3566 $create_event = false;
3568 if ($data) {
3569 //Now get completed xmlized object
3570 $info = $data->info;
3571 //traverse_xmlize($info); //Debug
3572 //print_object ($GLOBALS['traverse_array']); //Debug
3573 //$GLOBALS['traverse_array']=""; //Debug
3575 //if necessary, write to restorelog and adjust date/time fields
3576 if ($restore->course_startdateoffset) {
3577 restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
3580 //Now build the EVENT record structure
3581 $eve->name = backup_todb($info['EVENT']['#']['NAME']['0']['#']);
3582 $eve->description = backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
3583 $eve->format = backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
3584 $eve->courseid = $restore->course_id;
3585 $eve->groupid = backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
3586 $eve->userid = backup_todb($info['EVENT']['#']['USERID']['0']['#']);
3587 $eve->repeatid = backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
3588 $eve->modulename = "";
3589 if (!empty($info['EVENT']['#']['MODULENAME'])) {
3590 $eve->modulename = backup_todb($info['EVENT']['#']['MODULENAME']['0']['#']);
3592 $eve->instance = 0;
3593 $eve->eventtype = backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
3594 $eve->timestart = backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
3595 $eve->timeduration = backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
3596 $eve->visible = backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
3597 $eve->timemodified = backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
3599 //Now search if that event exists (by name, description, timestart fields) in
3600 //restore->course_id course
3601 $eve_db = get_record_select("event",
3602 "courseid={$eve->courseid} AND name='{$eve->name}' AND description='{$eve->description}' AND timestart=$eve->timestart");
3603 //If it doesn't exist, create
3604 if (!$eve_db) {
3605 $create_event = true;
3607 //If we must create the event
3608 if ($create_event) {
3610 //We must recode the userid
3611 $user = backup_getid($restore->backup_unique_code,"user",$eve->userid);
3612 if ($user) {
3613 $eve->userid = $user->new_id;
3614 } else {
3615 //Assign it to admin
3616 $eve->userid = $adminid;
3619 //We have to recode the groupid field
3620 $group = backup_getid($restore->backup_unique_code,"groups",$eve->groupid);
3621 if ($group) {
3622 $eve->groupid = $group->new_id;
3623 } else {
3624 //Assign it to group 0
3625 $eve->groupid = 0;
3628 //The structure is equal to the db, so insert the event
3629 $newid = insert_record ("event",$eve);
3631 //We must recode the repeatid if the event has it
3632 //The repeatid now refers to the id of the original event. (see Bug#5956)
3633 if ($newid && !empty($eve->repeatid)) {
3634 $repeat_rec = backup_getid($restore->backup_unique_code,"event_repeatid",$eve->repeatid);
3635 if ($repeat_rec) { //Exists, so use it...
3636 $eve->repeatid = $repeat_rec->new_id;
3637 } else { //Doesn't exists, calculate the next and save it
3638 $oldrepeatid = $eve->repeatid;
3639 $eve->repeatid = $newid;
3640 backup_putid($restore->backup_unique_code,"event_repeatid", $oldrepeatid, $eve->repeatid);
3642 $eve->id = $newid;
3643 // update the record to contain the correct repeatid
3644 update_record('event',$eve);
3646 } else {
3647 //get current event id
3648 $newid = $eve_db->id;
3650 if ($newid) {
3651 //We have the newid, update backup_ids
3652 backup_putid($restore->backup_unique_code,"event",
3653 $event->id, $newid);
3658 } else {
3659 $status = false;
3661 return $status;
3664 //This function decode things to make restore multi-site fully functional
3665 //It does this conversions:
3666 // - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
3667 // |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
3669 //Note: Inter-activities linking is being implemented as a final
3670 //step in the restore execution, because we need to have it
3671 //finished to know all the oldid, newid equivaleces
3672 function restore_decode_absolute_links($content) {
3674 global $CFG,$restore;
3675 require_once($CFG->libdir.'/filelib.php');
3677 /// MDL-14072: Prevent NULLs, empties and numbers to be processed by the
3678 /// heavy interlinking. Just a few cpu cycles saved.
3679 if ($content === NULL) {
3680 return NULL;
3681 } else if ($content === '') {
3682 return '';
3683 } else if (is_numeric($content)) {
3684 return $content;
3687 //Now decode wwwroot and file.php calls
3688 $search = array ("$@FILEPHP@$");
3689 $replace = array(get_file_url($restore->course_id));
3690 $result = str_replace($search,$replace,$content);
3692 if ($result != $content && debugging()) { //Debug
3693 if (!defined('RESTORE_SILENTLY')) {
3694 echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />'; //Debug
3696 } //Debug
3698 return $result;
3701 //This function restores the userfiles from the temp (user_files) directory to the
3702 //dataroot/users directory
3703 function restore_user_files($restore) {
3705 global $CFG;
3707 $status = true;
3709 $counter = 0;
3711 // 'users' is the old users folder, 'user' is the new one, with a new hierarchy. Detect which one is here and treat accordingly
3712 //in CFG->dataroot
3713 $dest_dir = $CFG->dataroot."/user";
3714 $status = check_dir_exists($dest_dir,true);
3716 //Now, we iterate over "user_files" records to check if that user dir must be
3717 //copied (and renamed) to the "users" dir.
3718 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/user_files";
3720 //Check if directory exists
3721 $userlist = array();
3723 if (is_dir($rootdir) && ($list = list_directories ($rootdir))) {
3724 $counter = 0;
3725 foreach ($list as $dir) {
3726 // If there are directories in this folder, we are in the new user hierarchy
3727 if ($newlist = list_directories("$rootdir/$dir")) {
3728 foreach ($newlist as $olduserid) {
3729 $userlist[$olduserid] = "$rootdir/$dir/$olduserid";
3731 } else {
3732 $userlist[$dir] = "$rootdir/$dir";
3736 foreach ($userlist as $olduserid => $backup_location) {
3737 //Look for dir like username in backup_ids
3738 //If that user exists in backup_ids
3739 if ($user = backup_getid($restore->backup_unique_code,"user",$olduserid)) {
3740 //Only if user has been created now or if it existed previously, but he hasn't got an image (see bug 1123)
3741 $newuserdir = make_user_directory($user->new_id, true); // Doesn't create the folder, just returns the location
3743 // restore images if new user or image does not exist yet
3744 if (!empty($user->new) or !check_dir_exists($newuserdir)) {
3745 if (make_user_directory($user->new_id)) { // Creates the folder
3746 $status = backup_copy_file($backup_location, $newuserdir, true);
3747 $counter ++;
3749 //Do some output
3750 if ($counter % 2 == 0) {
3751 if (!defined('RESTORE_SILENTLY')) {
3752 echo ".";
3753 if ($counter % 40 == 0) {
3754 echo "<br />";
3757 backup_flush(300);
3763 //If status is ok and whe have dirs created, returns counter to inform
3764 if ($status and $counter) {
3765 return $counter;
3766 } else {
3767 return $status;
3771 //This function restores the groupfiles from the temp (group_files) directory to the
3772 //dataroot/groups directory
3773 function restore_group_files($restore) {
3775 global $CFG;
3777 $status = true;
3779 $counter = 0;
3781 //First, we check to "groups" exists and create is as necessary
3782 //in CFG->dataroot
3783 $dest_dir = $CFG->dataroot.'/groups';
3784 $status = check_dir_exists($dest_dir,true);
3786 //Now, we iterate over "group_files" records to check if that user dir must be
3787 //copied (and renamed) to the "groups" dir.
3788 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/group_files";
3789 //Check if directory exists
3790 if (is_dir($rootdir)) {
3791 $list = list_directories ($rootdir);
3792 if ($list) {
3793 //Iterate
3794 $counter = 0;
3795 foreach ($list as $dir) {
3796 //Look for dir like groupid in backup_ids
3797 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
3798 "table_name","groups",
3799 "old_id",$dir);
3800 //If that group exists in backup_ids
3801 if ($data) {
3802 if (!file_exists($dest_dir."/".$data->new_id)) {
3803 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id,true);
3804 $counter ++;
3806 //Do some output
3807 if ($counter % 2 == 0) {
3808 if (!defined('RESTORE_SILENTLY')) {
3809 echo ".";
3810 if ($counter % 40 == 0) {
3811 echo "<br />";
3814 backup_flush(300);
3820 //If status is ok and whe have dirs created, returns counter to inform
3821 if ($status and $counter) {
3822 return $counter;
3823 } else {
3824 return $status;
3828 //This function restores the course files from the temp (course_files) directory to the
3829 //dataroot/course_id directory
3830 function restore_course_files($restore) {
3832 global $CFG;
3834 $status = true;
3836 $counter = 0;
3838 //First, we check to "course_id" exists and create is as necessary
3839 //in CFG->dataroot
3840 $dest_dir = $CFG->dataroot."/".$restore->course_id;
3841 $status = check_dir_exists($dest_dir,true);
3843 //Now, we iterate over "course_files" records to check if that file/dir must be
3844 //copied to the "dest_dir" dir.
3845 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/course_files";
3846 //Check if directory exists
3847 if (is_dir($rootdir)) {
3848 $list = list_directories_and_files ($rootdir);
3849 if ($list) {
3850 //Iterate
3851 $counter = 0;
3852 foreach ($list as $dir) {
3853 //Copy the dir to its new location
3854 //Only if destination file/dir doesn exists
3855 if (!file_exists($dest_dir."/".$dir)) {
3856 $status = backup_copy_file($rootdir."/".$dir,
3857 $dest_dir."/".$dir,true);
3858 $counter ++;
3860 //Do some output
3861 if ($counter % 2 == 0) {
3862 if (!defined('RESTORE_SILENTLY')) {
3863 echo ".";
3864 if ($counter % 40 == 0) {
3865 echo "<br />";
3868 backup_flush(300);
3873 //If status is ok and whe have dirs created, returns counter to inform
3874 if ($status and $counter) {
3875 return $counter;
3876 } else {
3877 return $status;
3881 //This function restores the site files from the temp (site_files) directory to the
3882 //dataroot/SITEID directory
3883 function restore_site_files($restore) {
3885 global $CFG;
3887 $status = true;
3889 $counter = 0;
3891 //First, we check to "course_id" exists and create is as necessary
3892 //in CFG->dataroot
3893 $dest_dir = $CFG->dataroot."/".SITEID;
3894 $status = check_dir_exists($dest_dir,true);
3896 //Now, we iterate over "site_files" files to check if that file/dir must be
3897 //copied to the "dest_dir" dir.
3898 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/site_files";
3899 //Check if directory exists
3900 if (is_dir($rootdir)) {
3901 $list = list_directories_and_files ($rootdir);
3902 if ($list) {
3903 //Iterate
3904 $counter = 0;
3905 foreach ($list as $dir) {
3906 //Copy the dir to its new location
3907 //Only if destination file/dir doesn exists
3908 if (!file_exists($dest_dir."/".$dir)) {
3909 $status = backup_copy_file($rootdir."/".$dir,
3910 $dest_dir."/".$dir,true);
3911 $counter ++;
3913 //Do some output
3914 if ($counter % 2 == 0) {
3915 if (!defined('RESTORE_SILENTLY')) {
3916 echo ".";
3917 if ($counter % 40 == 0) {
3918 echo "<br />";
3921 backup_flush(300);
3926 //If status is ok and whe have dirs created, returns counter to inform
3927 if ($status and $counter) {
3928 return $counter;
3929 } else {
3930 return $status;
3935 //This function creates all the structures for every module in backup file
3936 //Depending what has been selected.
3937 function restore_create_modules($restore,$xml_file) {
3939 global $CFG;
3940 $status = true;
3941 //Check it exists
3942 if (!file_exists($xml_file)) {
3943 $status = false;
3945 //Get info from xml
3946 if ($status) {
3947 //info will contain the id and modtype of every module
3948 //in backup_ids->info will be the real info (serialized)
3949 $info = restore_read_xml_modules($restore,$xml_file);
3951 //Now, if we have anything in info, we have to restore that mods
3952 //from backup_ids (calling every mod restore function)
3953 if ($info) {
3954 if ($info !== true) {
3955 if (!defined('RESTORE_SILENTLY')) {
3956 echo '<ul>';
3958 //Iterate over each module
3959 foreach ($info as $mod) {
3960 if (empty($restore->mods[$mod->modtype]->granular) // We don't care about per instance, i.e. restore all instances.
3961 || (array_key_exists($mod->id,$restore->mods[$mod->modtype]->instances)
3962 && !empty($restore->mods[$mod->modtype]->instances[$mod->id]->restore))) {
3963 $modrestore = $mod->modtype."_restore_mods";
3964 if (function_exists($modrestore)) { //Debug
3965 // we want to restore all mods even when one fails
3966 // incorrect code here ignored any errors during module restore in 1.6-1.8
3967 $status = $status && $modrestore($mod,$restore);
3968 } else {
3969 //Something was wrong. Function should exist.
3970 $status = false;
3974 if (!defined('RESTORE_SILENTLY')) {
3975 echo '</ul>';
3978 } else {
3979 $status = false;
3981 return $status;
3984 //This function creates all the structures for every log in backup file
3985 //Depending what has been selected.
3986 function restore_create_logs($restore,$xml_file) {
3988 global $CFG,$db;
3990 //Number of records to get in every chunk
3991 $recordset_size = 4;
3992 //Counter, points to current record
3993 $counter = 0;
3994 //To count all the recods to restore
3995 $count_logs = 0;
3997 $status = true;
3998 //Check it exists
3999 if (!file_exists($xml_file)) {
4000 $status = false;
4002 //Get info from xml
4003 if ($status) {
4004 //count_logs will contain the number of logs entries to process
4005 //in backup_ids->info will be the real info (serialized)
4006 $count_logs = restore_read_xml_logs($restore,$xml_file);
4009 //Now, if we have records in count_logs, we have to restore that logs
4010 //from backup_ids. This piece of code makes calls to:
4011 // - restore_log_course() if it's a course log
4012 // - restore_log_user() if it's a user log
4013 // - restore_log_module() if it's a module log.
4014 //And all is segmented in chunks to allow large recordsets to be restored !!
4015 if ($count_logs > 0) {
4016 while ($counter < $count_logs) {
4017 //Get a chunk of records
4018 //Take old_id twice to avoid adodb limitation
4019 $logs = get_records_select("backup_ids","table_name = 'log' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
4020 //We have logs
4021 if ($logs) {
4022 //Iterate
4023 foreach ($logs as $log) {
4024 //Get the full record from backup_ids
4025 $data = backup_getid($restore->backup_unique_code,"log",$log->old_id);
4026 if ($data) {
4027 //Now get completed xmlized object
4028 $info = $data->info;
4029 //traverse_xmlize($info); //Debug
4030 //print_object ($GLOBALS['traverse_array']); //Debug
4031 //$GLOBALS['traverse_array']=""; //Debug
4032 //Now build the LOG record structure
4033 $dblog = new object();
4034 $dblog->time = backup_todb($info['LOG']['#']['TIME']['0']['#']);
4035 $dblog->userid = backup_todb($info['LOG']['#']['USERID']['0']['#']);
4036 $dblog->ip = backup_todb($info['LOG']['#']['IP']['0']['#']);
4037 $dblog->course = $restore->course_id;
4038 $dblog->module = backup_todb($info['LOG']['#']['MODULE']['0']['#']);
4039 $dblog->cmid = backup_todb($info['LOG']['#']['CMID']['0']['#']);
4040 $dblog->action = backup_todb($info['LOG']['#']['ACTION']['0']['#']);
4041 $dblog->url = backup_todb($info['LOG']['#']['URL']['0']['#']);
4042 $dblog->info = backup_todb($info['LOG']['#']['INFO']['0']['#']);
4043 //We have to recode the userid field
4044 $user = backup_getid($restore->backup_unique_code,"user",$dblog->userid);
4045 if ($user) {
4046 //echo "User ".$dblog->userid." to user ".$user->new_id."<br />"; //Debug
4047 $dblog->userid = $user->new_id;
4049 //We have to recode the cmid field (if module isn't "course" or "user")
4050 if ($dblog->module != "course" and $dblog->module != "user") {
4051 $cm = backup_getid($restore->backup_unique_code,"course_modules",$dblog->cmid);
4052 if ($cm) {
4053 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
4054 $dblog->cmid = $cm->new_id;
4055 } else {
4056 $dblog->cmid = 0;
4059 //print_object ($dblog); //Debug
4060 //Now, we redirect to the needed function to make all the work
4061 if ($dblog->module == "course") {
4062 //It's a course log,
4063 $stat = restore_log_course($restore,$dblog);
4064 } elseif ($dblog->module == "user") {
4065 //It's a user log,
4066 $stat = restore_log_user($restore,$dblog);
4067 } else {
4068 //It's a module log,
4069 $stat = restore_log_module($restore,$dblog);
4073 //Do some output
4074 $counter++;
4075 if ($counter % 10 == 0) {
4076 if (!defined('RESTORE_SILENTLY')) {
4077 echo ".";
4078 if ($counter % 200 == 0) {
4079 echo "<br />";
4082 backup_flush(300);
4085 } else {
4086 //We never should arrive here
4087 $counter = $count_logs;
4088 $status = false;
4093 return $status;
4096 //This function inserts a course log record, calculating the URL field as necessary
4097 function restore_log_course($restore,$log) {
4099 $status = true;
4100 $toinsert = false;
4102 //echo "<hr />Before transformations<br />"; //Debug
4103 //print_object($log); //Debug
4104 //Depending of the action, we recode different things
4105 switch ($log->action) {
4106 case "view":
4107 $log->url = "view.php?id=".$log->course;
4108 $log->info = $log->course;
4109 $toinsert = true;
4110 break;
4111 case "guest":
4112 $log->url = "view.php?id=".$log->course;
4113 $toinsert = true;
4114 break;
4115 case "user report":
4116 //recode the info field (it's the user id)
4117 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4118 if ($user) {
4119 $log->info = $user->new_id;
4120 //Now, extract the mode from the url field
4121 $mode = substr(strrchr($log->url,"="),1);
4122 $log->url = "user.php?id=".$log->course."&user=".$log->info."&mode=".$mode;
4123 $toinsert = true;
4125 break;
4126 case "add mod":
4127 //Extract the course_module from the url field
4128 $cmid = substr(strrchr($log->url,"="),1);
4129 //recode the course_module to see it it has been restored
4130 $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
4131 if ($cm) {
4132 $cmid = $cm->new_id;
4133 //Extract the module name and the module id from the info field
4134 $modname = strtok($log->info," ");
4135 $modid = strtok(" ");
4136 //recode the module id to see if it has been restored
4137 $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
4138 if ($mod) {
4139 $modid = $mod->new_id;
4140 //Now I have everything so reconstruct url and info
4141 $log->info = $modname." ".$modid;
4142 $log->url = "../mod/".$modname."/view.php?id=".$cmid;
4143 $toinsert = true;
4146 break;
4147 case "update mod":
4148 //Extract the course_module from the url field
4149 $cmid = substr(strrchr($log->url,"="),1);
4150 //recode the course_module to see it it has been restored
4151 $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
4152 if ($cm) {
4153 $cmid = $cm->new_id;
4154 //Extract the module name and the module id from the info field
4155 $modname = strtok($log->info," ");
4156 $modid = strtok(" ");
4157 //recode the module id to see if it has been restored
4158 $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
4159 if ($mod) {
4160 $modid = $mod->new_id;
4161 //Now I have everything so reconstruct url and info
4162 $log->info = $modname." ".$modid;
4163 $log->url = "../mod/".$modname."/view.php?id=".$cmid;
4164 $toinsert = true;
4167 break;
4168 case "delete mod":
4169 $log->url = "view.php?id=".$log->course;
4170 $toinsert = true;
4171 break;
4172 case "update":
4173 $log->url = "edit.php?id=".$log->course;
4174 $log->info = "";
4175 $toinsert = true;
4176 break;
4177 case "unenrol":
4178 //recode the info field (it's the user id)
4179 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4180 if ($user) {
4181 $log->info = $user->new_id;
4182 $log->url = "view.php?id=".$log->course;
4183 $toinsert = true;
4185 break;
4186 case "enrol":
4187 //recode the info field (it's the user id)
4188 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4189 if ($user) {
4190 $log->info = $user->new_id;
4191 $log->url = "view.php?id=".$log->course;
4192 $toinsert = true;
4194 break;
4195 case "editsection":
4196 //Extract the course_section from the url field
4197 $secid = substr(strrchr($log->url,"="),1);
4198 //recode the course_section to see if it has been restored
4199 $sec = backup_getid($restore->backup_unique_code,"course_sections",$secid);
4200 if ($sec) {
4201 $secid = $sec->new_id;
4202 //Now I have everything so reconstruct url and info
4203 $log->url = "editsection.php?id=".$secid;
4204 $toinsert = true;
4206 break;
4207 case "new":
4208 $log->url = "view.php?id=".$log->course;
4209 $log->info = "";
4210 $toinsert = true;
4211 break;
4212 case "recent":
4213 $log->url = "recent.php?id=".$log->course;
4214 $log->info = "";
4215 $toinsert = true;
4216 break;
4217 case "report log":
4218 $log->url = "report/log/index.php?id=".$log->course;
4219 $log->info = $log->course;
4220 $toinsert = true;
4221 break;
4222 case "report live":
4223 $log->url = "report/log/live.php?id=".$log->course;
4224 $log->info = $log->course;
4225 $toinsert = true;
4226 break;
4227 case "report outline":
4228 $log->url = "report/outline/index.php?id=".$log->course;
4229 $log->info = $log->course;
4230 $toinsert = true;
4231 break;
4232 case "report participation":
4233 $log->url = "report/participation/index.php?id=".$log->course;
4234 $log->info = $log->course;
4235 $toinsert = true;
4236 break;
4237 case "report stats":
4238 $log->url = "report/stats/index.php?id=".$log->course;
4239 $log->info = $log->course;
4240 $toinsert = true;
4241 break;
4242 default:
4243 echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug
4244 break;
4247 //echo "After transformations<br />"; //Debug
4248 //print_object($log); //Debug
4250 //Now if $toinsert is set, insert the record
4251 if ($toinsert) {
4252 //echo "Inserting record<br />"; //Debug
4253 $status = insert_record("log",$log);
4255 return $status;
4258 //This function inserts a user log record, calculating the URL field as necessary
4259 function restore_log_user($restore,$log) {
4261 $status = true;
4262 $toinsert = false;
4264 //echo "<hr />Before transformations<br />"; //Debug
4265 //print_object($log); //Debug
4266 //Depending of the action, we recode different things
4267 switch ($log->action) {
4268 case "view":
4269 //recode the info field (it's the user id)
4270 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4271 if ($user) {
4272 $log->info = $user->new_id;
4273 $log->url = "view.php?id=".$log->info."&course=".$log->course;
4274 $toinsert = true;
4276 break;
4277 case "change password":
4278 //recode the info field (it's the user id)
4279 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4280 if ($user) {
4281 $log->info = $user->new_id;
4282 $log->url = "view.php?id=".$log->info."&course=".$log->course;
4283 $toinsert = true;
4285 break;
4286 case "login":
4287 //recode the info field (it's the user id)
4288 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4289 if ($user) {
4290 $log->info = $user->new_id;
4291 $log->url = "view.php?id=".$log->info."&course=".$log->course;
4292 $toinsert = true;
4294 break;
4295 case "logout":
4296 //recode the info field (it's the user id)
4297 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
4298 if ($user) {
4299 $log->info = $user->new_id;
4300 $log->url = "view.php?id=".$log->info."&course=".$log->course;
4301 $toinsert = true;
4303 break;
4304 case "view all":
4305 $log->url = "view.php?id=".$log->course;
4306 $log->info = "";
4307 $toinsert = true;
4308 case "update":
4309 //We split the url by ampersand char
4310 $first_part = strtok($log->url,"&");
4311 //Get data after the = char. It's the user being updated
4312 $userid = substr(strrchr($first_part,"="),1);
4313 //Recode the user
4314 $user = backup_getid($restore->backup_unique_code,"user",$userid);
4315 if ($user) {
4316 $log->info = "";
4317 $log->url = "view.php?id=".$user->new_id."&course=".$log->course;
4318 $toinsert = true;
4320 break;
4321 default:
4322 echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug
4323 break;
4326 //echo "After transformations<br />"; //Debug
4327 //print_object($log); //Debug
4329 //Now if $toinsert is set, insert the record
4330 if ($toinsert) {
4331 //echo "Inserting record<br />"; //Debug
4332 $status = insert_record("log",$log);
4334 return $status;
4337 //This function inserts a module log record, calculating the URL field as necessary
4338 function restore_log_module($restore,$log) {
4340 $status = true;
4341 $toinsert = false;
4343 //echo "<hr />Before transformations<br />"; //Debug
4344 //print_object($log); //Debug
4346 //Now we see if the required function in the module exists
4347 $function = $log->module."_restore_logs";
4348 if (function_exists($function)) {
4349 //Call the function
4350 $log = $function($restore,$log);
4351 //If everything is ok, mark the insert flag
4352 if ($log) {
4353 $toinsert = true;
4357 //echo "After transformations<br />"; //Debug
4358 //print_object($log); //Debug
4360 //Now if $toinsert is set, insert the record
4361 if ($toinsert) {
4362 //echo "Inserting record<br />"; //Debug
4363 $status = insert_record("log",$log);
4365 return $status;
4368 //This function adjusts the instance field into course_modules. It's executed after
4369 //modules restore. There, we KNOW the new instance id !!
4370 function restore_check_instances($restore) {
4372 global $CFG;
4374 $status = true;
4376 //We are going to iterate over each course_module saved in backup_ids
4377 $course_modules = get_records_sql("SELECT old_id,new_id
4378 FROM {$CFG->prefix}backup_ids
4379 WHERE backup_code = '$restore->backup_unique_code' AND
4380 table_name = 'course_modules'");
4381 if ($course_modules) {
4382 foreach($course_modules as $cm) {
4383 //Get full record, using backup_getids
4384 $cm_module = backup_getid($restore->backup_unique_code,"course_modules",$cm->old_id);
4385 //Now we are going to the REAL course_modules to get its type (field module)
4386 $module = get_record("course_modules","id",$cm_module->new_id);
4387 if ($module) {
4388 //We know the module type id. Get the name from modules
4389 $type = get_record("modules","id",$module->module);
4390 if ($type) {
4391 //We know the type name and the old_id. Get its new_id
4392 //from backup_ids. It's the instance !!!
4393 $instance = backup_getid($restore->backup_unique_code,$type->name,$cm_module->info);
4394 if ($instance) {
4395 //We have the new instance, so update the record in course_modules
4396 $module->instance = $instance->new_id;
4397 //print_object ($module); //Debug
4398 $status = update_record("course_modules",$module);
4399 } else {
4400 $status = false;
4402 } else {
4403 $status = false;
4405 } else {
4406 $status = false;
4408 // MDL-14326 remove empty course modules instance's (credit goes to John T. Macklin from Remote Learner)
4409 $course_modules_inst_zero = get_records_sql("SELECT id, course, instance
4410 FROM {$CFG->prefix}course_modules
4411 WHERE id = '$cm_module->new_id' AND
4412 instance = '0'");
4414 if($course_modules_inst_zero){ // Clean up the invalid instances
4415 foreach($course_modules_inst_zero as $course_modules_inst){
4416 delete_records('course_modules', 'id',$course_modules_inst->id);
4421 /// Finally, calculate modinfo cache.
4422 rebuild_course_cache($restore->course_id);
4426 return $status;
4429 //=====================================================================================
4430 //== ==
4431 //== XML Functions (SAX) ==
4432 //== ==
4433 //=====================================================================================
4435 //This is the class used to do all the xml parse
4436 class MoodleParser {
4438 var $level = 0; //Level we are
4439 var $counter = 0; //Counter
4440 var $tree = array(); //Array of levels we are
4441 var $content = ""; //Content under current level
4442 var $todo = ""; //What we hav to do when parsing
4443 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
4444 var $temp = ""; //Temp storage.
4445 var $preferences = ""; //Preferences about what to load !!
4446 var $finished = false; //Flag to say xml_parse to stop
4448 //This function is used to get the current contents property value
4449 //They are trimed (and converted from utf8 if needed)
4450 function getContents() {
4451 return trim($this->content);
4454 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4455 function startElementInfo($parser, $tagName, $attrs) {
4456 //Refresh properties
4457 $this->level++;
4458 $this->tree[$this->level] = $tagName;
4460 //Output something to avoid browser timeouts...
4461 //backup_flush();
4463 //Check if we are into INFO zone
4464 //if ($this->tree[2] == "INFO") //Debug
4465 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4468 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4469 function startElementRoles($parser, $tagName, $attrs) {
4470 //Refresh properties
4471 $this->level++;
4472 $this->tree[$this->level] = $tagName;
4474 //Output something to avoid browser timeouts...
4475 //backup_flush();
4477 //Check if we are into INFO zone
4478 //if ($this->tree[2] == "INFO") //Debug
4479 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4483 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
4484 function startElementCourseHeader($parser, $tagName, $attrs) {
4485 //Refresh properties
4486 $this->level++;
4487 $this->tree[$this->level] = $tagName;
4489 //Output something to avoid browser timeouts...
4490 //backup_flush();
4492 //Check if we are into COURSE_HEADER zone
4493 //if ($this->tree[3] == "HEADER") //Debug
4494 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4497 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
4498 function startElementBlocks($parser, $tagName, $attrs) {
4499 //Refresh properties
4500 $this->level++;
4501 $this->tree[$this->level] = $tagName;
4503 //Output something to avoid browser timeouts...
4504 //backup_flush();
4506 //Check if we are into BLOCKS zone
4507 //if ($this->tree[3] == "BLOCKS") //Debug
4508 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4510 //If we are under a BLOCK tag under a BLOCKS zone, accumule it
4511 if (isset($this->tree[4]) and isset($this->tree[3])) { //
4512 if ($this->tree[4] == "BLOCK" and $this->tree[3] == "BLOCKS") {
4513 if (!isset($this->temp)) {
4514 $this->temp = "";
4516 $this->temp .= "<".$tagName.">";
4521 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
4522 function startElementSections($parser, $tagName, $attrs) {
4523 //Refresh properties
4524 $this->level++;
4525 $this->tree[$this->level] = $tagName;
4527 //Output something to avoid browser timeouts...
4528 //backup_flush();
4530 //Check if we are into SECTIONS zone
4531 //if ($this->tree[3] == "SECTIONS") //Debug
4532 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4535 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4536 function startElementFormatData($parser, $tagName, $attrs) {
4537 //Refresh properties
4538 $this->level++;
4539 $this->tree[$this->level] = $tagName;
4541 //Output something to avoid browser timeouts...
4542 //backup_flush();
4544 //Accumulate all the data inside this tag
4545 if (isset($this->tree[3]) && $this->tree[3] == "FORMATDATA") {
4546 if (!isset($this->temp)) {
4547 $this->temp = '';
4549 $this->temp .= "<".$tagName.">";
4552 //Check if we are into FORMATDATA zone
4553 //if ($this->tree[3] == "FORMATDATA") //Debug
4554 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4557 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4558 function startElementMetacourse($parser, $tagName, $attrs) {
4560 //Refresh properties
4561 $this->level++;
4562 $this->tree[$this->level] = $tagName;
4564 //Output something to avoid browser timeouts...
4565 //backup_flush();
4567 //Check if we are into METACOURSE zone
4568 //if ($this->tree[3] == "METACOURSE") //Debug
4569 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4572 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4573 function startElementGradebook($parser, $tagName, $attrs) {
4575 //Refresh properties
4576 $this->level++;
4577 $this->tree[$this->level] = $tagName;
4579 //Output something to avoid browser timeouts...
4580 //backup_flush();
4582 //Check if we are into GRADEBOOK zone
4583 //if ($this->tree[3] == "GRADEBOOK") //Debug
4584 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4586 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4587 if (isset($this->tree[5]) and isset($this->tree[3])) {
4588 if (($this->tree[5] == "GRADE_ITEM" || $this->tree[5] == "GRADE_CATEGORY" || $this->tree[5] == "GRADE_LETTER" || $this->tree[5] == "GRADE_OUTCOME" || $this->tree[5] == "GRADE_OUTCOMES_COURSE" || $this->tree[5] == "GRADE_CATEGORIES_HISTORY" || $this->tree[5] == "GRADE_GRADES_HISTORY" || $this->tree[5] == "GRADE_TEXT_HISTORY" || $this->tree[5] == "GRADE_ITEM_HISTORY" || $this->tree[5] == "GRADE_OUTCOME_HISTORY") && ($this->tree[3] == "GRADEBOOK")) {
4590 if (!isset($this->temp)) {
4591 $this->temp = "";
4593 $this->temp .= "<".$tagName.">";
4598 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4599 function startElementOldGradebook($parser, $tagName, $attrs) {
4601 //Refresh properties
4602 $this->level++;
4603 $this->tree[$this->level] = $tagName;
4605 //Output something to avoid browser timeouts...
4606 //backup_flush();
4608 //Check if we are into GRADEBOOK zone
4609 //if ($this->tree[3] == "GRADEBOOK") //Debug
4610 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4612 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4613 if (isset($this->tree[5]) and isset($this->tree[3])) {
4614 if (($this->tree[5] == "GRADE_PREFERENCE" || $this->tree[5] == "GRADE_LETTER" || $this->tree[5] == "GRADE_CATEGORY" ) && ($this->tree[3] == "GRADEBOOK")) {
4615 if (!isset($this->temp)) {
4616 $this->temp = "";
4618 $this->temp .= "<".$tagName.">";
4624 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
4625 function startElementUsers($parser, $tagName, $attrs) {
4626 //Refresh properties
4627 $this->level++;
4628 $this->tree[$this->level] = $tagName;
4630 //Check if we are into USERS zone
4631 //if ($this->tree[3] == "USERS") //Debug
4632 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4635 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
4636 function startElementMessages($parser, $tagName, $attrs) {
4637 //Refresh properties
4638 $this->level++;
4639 $this->tree[$this->level] = $tagName;
4641 //Output something to avoid browser timeouts...
4642 //backup_flush();
4644 //Check if we are into MESSAGES zone
4645 //if ($this->tree[3] == "MESSAGES") //Debug
4646 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4648 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
4649 if (isset($this->tree[4]) and isset($this->tree[3])) {
4650 if (($this->tree[4] == "MESSAGE" || (isset($this->tree[5]) && $this->tree[5] == "CONTACT" )) and ($this->tree[3] == "MESSAGES")) {
4651 if (!isset($this->temp)) {
4652 $this->temp = "";
4654 $this->temp .= "<".$tagName.">";
4659 //This is the startTag handler we use where we are reading the blogs zone (todo="BLOGS")
4660 function startElementBlogs($parser, $tagName, $attrs) {
4661 //Refresh properties
4662 $this->level++;
4663 $this->tree[$this->level] = $tagName;
4665 //Output something to avoid browser timeouts...
4666 //backup_flush();
4668 //Check if we are into BLOGS zone
4669 //if ($this->tree[3] == "BLOGS") //Debug
4670 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4672 //If we are under a BLOG tag under a BLOGS zone, accumule it
4673 if (isset($this->tree[4]) and isset($this->tree[3])) {
4674 if ($this->tree[4] == "BLOG" and $this->tree[3] == "BLOGS") {
4675 if (!isset($this->temp)) {
4676 $this->temp = "";
4678 $this->temp .= "<".$tagName.">";
4683 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4684 function startElementQuestions($parser, $tagName, $attrs) {
4685 //Refresh properties
4686 $this->level++;
4687 $this->tree[$this->level] = $tagName;
4689 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
4690 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
4691 //} //Debug
4693 //Output something to avoid browser timeouts...
4694 //backup_flush();
4696 //Check if we are into QUESTION_CATEGORIES zone
4697 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
4698 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4700 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
4701 if (isset($this->tree[4]) and isset($this->tree[3])) {
4702 if (($this->tree[4] == "QUESTION_CATEGORY") and ($this->tree[3] == "QUESTION_CATEGORIES")) {
4703 if (!isset($this->temp)) {
4704 $this->temp = "";
4706 $this->temp .= "<".$tagName.">";
4711 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
4712 function startElementScales($parser, $tagName, $attrs) {
4713 //Refresh properties
4714 $this->level++;
4715 $this->tree[$this->level] = $tagName;
4717 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
4718 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
4719 //} //Debug
4721 //Output something to avoid browser timeouts...
4722 //backup_flush();
4724 //Check if we are into SCALES zone
4725 //if ($this->tree[3] == "SCALES") //Debug
4726 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4728 //If we are under a SCALE tag under a SCALES zone, accumule it
4729 if (isset($this->tree[4]) and isset($this->tree[3])) {
4730 if (($this->tree[4] == "SCALE") and ($this->tree[3] == "SCALES")) {
4731 if (!isset($this->temp)) {
4732 $this->temp = "";
4734 $this->temp .= "<".$tagName.">";
4739 function startElementGroups($parser, $tagName, $attrs) {
4740 //Refresh properties
4741 $this->level++;
4742 $this->tree[$this->level] = $tagName;
4744 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
4745 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
4746 //} //Debug
4748 //Output something to avoid browser timeouts...
4749 //backup_flush();
4751 //Check if we are into GROUPS zone
4752 //if ($this->tree[3] == "GROUPS") //Debug
4753 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4755 //If we are under a GROUP tag under a GROUPS zone, accumule it
4756 if (isset($this->tree[4]) and isset($this->tree[3])) {
4757 if (($this->tree[4] == "GROUP") and ($this->tree[3] == "GROUPS")) {
4758 if (!isset($this->temp)) {
4759 $this->temp = "";
4761 $this->temp .= "<".$tagName.">";
4766 function startElementGroupings($parser, $tagName, $attrs) {
4767 //Refresh properties
4768 $this->level++;
4769 $this->tree[$this->level] = $tagName;
4771 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
4772 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
4773 //} //Debug
4775 //Output something to avoid browser timeouts...
4776 //backup_flush();
4778 //Check if we are into GROUPINGS zone
4779 //if ($this->tree[3] == "GROUPINGS") //Debug
4780 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4782 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
4783 if (isset($this->tree[4]) and isset($this->tree[3])) {
4784 if (($this->tree[4] == "GROUPING") and ($this->tree[3] == "GROUPINGS")) {
4785 if (!isset($this->temp)) {
4786 $this->temp = "";
4788 $this->temp .= "<".$tagName.">";
4793 function startElementGroupingsGroups($parser, $tagName, $attrs) {
4794 //Refresh properties
4795 $this->level++;
4796 $this->tree[$this->level] = $tagName;
4798 //if ($tagName == "GROUPINGGROUP" && $this->tree[3] == "GROUPINGSGROUPS") { //Debug
4799 // echo "<P>GROUPINGSGROUP: ".strftime ("%X",time()),"-"; //Debug
4800 //} //Debug
4802 //Output something to avoid browser timeouts...
4803 backup_flush();
4805 //Check if we are into GROUPINGSGROUPS zone
4806 //if ($this->tree[3] == "GROUPINGSGROUPS") //Debug
4807 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4809 //If we are under a GROUPINGGROUP tag under a GROUPINGSGROUPS zone, accumule it
4810 if (isset($this->tree[4]) and isset($this->tree[3])) {
4811 if (($this->tree[4] == "GROUPINGGROUP") and ($this->tree[3] == "GROUPINGSGROUPS")) {
4812 if (!isset($this->temp)) {
4813 $this->temp = "";
4815 $this->temp .= "<".$tagName.">";
4820 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
4821 function startElementEvents($parser, $tagName, $attrs) {
4822 //Refresh properties
4823 $this->level++;
4824 $this->tree[$this->level] = $tagName;
4826 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
4827 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
4828 //} //Debug
4830 //Output something to avoid browser timeouts...
4831 //backup_flush();
4833 //Check if we are into EVENTS zone
4834 //if ($this->tree[3] == "EVENTS") //Debug
4835 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4837 //If we are under a EVENT tag under a EVENTS zone, accumule it
4838 if (isset($this->tree[4]) and isset($this->tree[3])) {
4839 if (($this->tree[4] == "EVENT") and ($this->tree[3] == "EVENTS")) {
4840 if (!isset($this->temp)) {
4841 $this->temp = "";
4843 $this->temp .= "<".$tagName.">";
4848 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
4849 function startElementModules($parser, $tagName, $attrs) {
4850 //Refresh properties
4851 $this->level++;
4852 $this->tree[$this->level] = $tagName;
4854 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
4855 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
4856 //} //Debug
4858 //Output something to avoid browser timeouts...
4859 //backup_flush();
4861 //Check if we are into MODULES zone
4862 //if ($this->tree[3] == "MODULES") //Debug
4863 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4865 //If we are under a MOD tag under a MODULES zone, accumule it
4866 if (isset($this->tree[4]) and isset($this->tree[3])) {
4867 if (($this->tree[4] == "MOD") and ($this->tree[3] == "MODULES")) {
4868 if (!isset($this->temp)) {
4869 $this->temp = "";
4871 $this->temp .= "<".$tagName.">";
4876 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
4877 function startElementLogs($parser, $tagName, $attrs) {
4878 //Refresh properties
4879 $this->level++;
4880 $this->tree[$this->level] = $tagName;
4882 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
4883 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
4884 //} //Debug
4886 //Output something to avoid browser timeouts...
4887 //backup_flush();
4889 //Check if we are into LOGS zone
4890 //if ($this->tree[3] == "LOGS") //Debug
4891 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4893 //If we are under a LOG tag under a LOGS zone, accumule it
4894 if (isset($this->tree[4]) and isset($this->tree[3])) {
4895 if (($this->tree[4] == "LOG") and ($this->tree[3] == "LOGS")) {
4896 if (!isset($this->temp)) {
4897 $this->temp = "";
4899 $this->temp .= "<".$tagName.">";
4904 //This is the startTag default handler we use when todo is undefined
4905 function startElement($parser, $tagName, $attrs) {
4906 $this->level++;
4907 $this->tree[$this->level] = $tagName;
4909 //Output something to avoid browser timeouts...
4910 //backup_flush();
4912 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4915 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
4916 function endElementInfo($parser, $tagName) {
4917 //Check if we are into INFO zone
4918 if ($this->tree[2] == "INFO") {
4919 //if (trim($this->content)) //Debug
4920 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4921 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4922 //Dependig of different combinations, do different things
4923 if ($this->level == 3) {
4924 switch ($tagName) {
4925 case "NAME":
4926 $this->info->backup_name = $this->getContents();
4927 break;
4928 case "MOODLE_VERSION":
4929 $this->info->backup_moodle_version = $this->getContents();
4930 break;
4931 case "MOODLE_RELEASE":
4932 $this->info->backup_moodle_release = $this->getContents();
4933 break;
4934 case "BACKUP_VERSION":
4935 $this->info->backup_backup_version = $this->getContents();
4936 break;
4937 case "BACKUP_RELEASE":
4938 $this->info->backup_backup_release = $this->getContents();
4939 break;
4940 case "DATE":
4941 $this->info->backup_date = $this->getContents();
4942 break;
4943 case "ORIGINAL_WWWROOT":
4944 $this->info->original_wwwroot = $this->getContents();
4945 break;
4946 case "MNET_EXTERNALUSERS":
4947 $this->info->mnet_externalusers = $this->getContents();
4948 break;
4951 if ($this->tree[3] == "DETAILS") {
4952 if ($this->level == 4) {
4953 switch ($tagName) {
4954 case "METACOURSE":
4955 $this->info->backup_metacourse = $this->getContents();
4956 break;
4957 case "USERS":
4958 $this->info->backup_users = $this->getContents();
4959 break;
4960 case "LOGS":
4961 $this->info->backup_logs = $this->getContents();
4962 break;
4963 case "USERFILES":
4964 $this->info->backup_user_files = $this->getContents();
4965 break;
4966 case "COURSEFILES":
4967 $this->info->backup_course_files = $this->getContents();
4968 break;
4969 case "SITEFILES":
4970 $this->info->backup_site_files = $this->getContents();
4971 break;
4972 case "GRADEBOOKHISTORIES":
4973 $this->info->gradebook_histories = $this->getContents();
4974 break;
4975 case "MESSAGES":
4976 $this->info->backup_messages = $this->getContents();
4977 break;
4978 case "BLOGS":
4979 $this->info->backup_blogs = $this->getContents();
4980 break;
4981 case 'BLOCKFORMAT':
4982 $this->info->backup_block_format = $this->getContents();
4983 break;
4986 if ($this->level == 5) {
4987 switch ($tagName) {
4988 case "NAME":
4989 $this->info->tempName = $this->getContents();
4990 break;
4991 case "INCLUDED":
4992 $this->info->mods[$this->info->tempName]->backup = $this->getContents();
4993 break;
4994 case "USERINFO":
4995 $this->info->mods[$this->info->tempName]->userinfo = $this->getContents();
4996 break;
4999 if ($this->level == 7) {
5000 switch ($tagName) {
5001 case "ID":
5002 $this->info->tempId = $this->getContents();
5003 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->id = $this->info->tempId;
5004 break;
5005 case "NAME":
5006 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->name = $this->getContents();
5007 break;
5008 case "INCLUDED":
5009 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->backup = $this->getContents();
5010 break;
5011 case "USERINFO":
5012 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->userinfo = $this->getContents();
5013 break;
5019 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
5020 //Speed up a lot (avoid parse all)
5021 if ($tagName == "INFO") {
5022 $this->finished = true;
5025 //Clear things
5026 $this->tree[$this->level] = "";
5027 $this->level--;
5028 $this->content = "";
5032 function endElementRoles($parser, $tagName) {
5033 //Check if we are into INFO zone
5034 if ($this->tree[2] == "ROLES") {
5036 if ($this->tree[3] == "ROLE") {
5037 if ($this->level == 4) {
5038 switch ($tagName) {
5039 case "ID": // this is the old id
5040 $this->info->tempid = $this->getContents();
5041 $this->info->roles[$this->info->tempid]->id = $this->info->tempid;
5042 break;
5043 case "NAME":
5044 $this->info->roles[$this->info->tempid]->name = $this->getContents();;
5045 break;
5046 case "SHORTNAME":
5047 $this->info->roles[$this->info->tempid]->shortname = $this->getContents();;
5048 break;
5049 case "NAMEINCOURSE": // custom name of the role in course
5050 $this->info->roles[$this->info->tempid]->nameincourse = $this->getContents();;
5051 break;
5054 if ($this->level == 6) {
5055 switch ($tagName) {
5056 case "NAME":
5057 $this->info->tempcapname = $this->getContents();
5058 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->name = $this->getContents();
5059 break;
5060 case "PERMISSION":
5061 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->permission = $this->getContents();
5062 break;
5063 case "TIMEMODIFIED":
5064 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->timemodified = $this->getContents();
5065 break;
5066 case "MODIFIERID":
5067 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->modifierid = $this->getContents();
5068 break;
5074 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
5075 //Speed up a lot (avoid parse all)
5076 if ($tagName == "ROLES") {
5077 $this->finished = true;
5080 //Clear things
5081 $this->tree[$this->level] = "";
5082 $this->level--;
5083 $this->content = "";
5087 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
5088 function endElementCourseHeader($parser, $tagName) {
5089 //Check if we are into COURSE_HEADER zone
5090 if ($this->tree[3] == "HEADER") {
5091 //if (trim($this->content)) //Debug
5092 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5093 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5094 //Dependig of different combinations, do different things
5095 if ($this->level == 4) {
5096 switch ($tagName) {
5097 case "ID":
5098 $this->info->course_id = $this->getContents();
5099 break;
5100 case "PASSWORD":
5101 $this->info->course_password = $this->getContents();
5102 break;
5103 case "FULLNAME":
5104 $this->info->course_fullname = $this->getContents();
5105 break;
5106 case "SHORTNAME":
5107 $this->info->course_shortname = $this->getContents();
5108 break;
5109 case "IDNUMBER":
5110 $this->info->course_idnumber = $this->getContents();
5111 break;
5112 case "SUMMARY":
5113 $this->info->course_summary = $this->getContents();
5114 break;
5115 case "FORMAT":
5116 $this->info->course_format = $this->getContents();
5117 break;
5118 case "SHOWGRADES":
5119 $this->info->course_showgrades = $this->getContents();
5120 break;
5121 case "BLOCKINFO":
5122 $this->info->blockinfo = $this->getContents();
5123 break;
5124 case "NEWSITEMS":
5125 $this->info->course_newsitems = $this->getContents();
5126 break;
5127 case "TEACHER":
5128 $this->info->course_teacher = $this->getContents();
5129 break;
5130 case "TEACHERS":
5131 $this->info->course_teachers = $this->getContents();
5132 break;
5133 case "STUDENT":
5134 $this->info->course_student = $this->getContents();
5135 break;
5136 case "STUDENTS":
5137 $this->info->course_students = $this->getContents();
5138 break;
5139 case "GUEST":
5140 $this->info->course_guest = $this->getContents();
5141 break;
5142 case "STARTDATE":
5143 $this->info->course_startdate = $this->getContents();
5144 break;
5145 case "NUMSECTIONS":
5146 $this->info->course_numsections = $this->getContents();
5147 break;
5148 //case "SHOWRECENT": INFO: This is out in 1.3
5149 // $this->info->course_showrecent = $this->getContents();
5150 // break;
5151 case "MAXBYTES":
5152 $this->info->course_maxbytes = $this->getContents();
5153 break;
5154 case "SHOWREPORTS":
5155 $this->info->course_showreports = $this->getContents();
5156 break;
5157 case "GROUPMODE":
5158 $this->info->course_groupmode = $this->getContents();
5159 break;
5160 case "GROUPMODEFORCE":
5161 $this->info->course_groupmodeforce = $this->getContents();
5162 break;
5163 case "DEFAULTGROUPINGID":
5164 $this->info->course_defaultgroupingid = $this->getContents();
5165 break;
5166 case "LANG":
5167 $this->info->course_lang = $this->getContents();
5168 break;
5169 case "THEME":
5170 $this->info->course_theme = $this->getContents();
5171 break;
5172 case "COST":
5173 $this->info->course_cost = $this->getContents();
5174 break;
5175 case "CURRENCY":
5176 $this->info->course_currency = $this->getContents();
5177 break;
5178 case "MARKER":
5179 $this->info->course_marker = $this->getContents();
5180 break;
5181 case "VISIBLE":
5182 $this->info->course_visible = $this->getContents();
5183 break;
5184 case "HIDDENSECTIONS":
5185 $this->info->course_hiddensections = $this->getContents();
5186 break;
5187 case "TIMECREATED":
5188 $this->info->course_timecreated = $this->getContents();
5189 break;
5190 case "TIMEMODIFIED":
5191 $this->info->course_timemodified = $this->getContents();
5192 break;
5193 case "METACOURSE":
5194 $this->info->course_metacourse = $this->getContents();
5195 break;
5196 case "EXPIRENOTIFY":
5197 $this->info->course_expirynotify = $this->getContents();
5198 break;
5199 case "NOTIFYSTUDENTS":
5200 $this->info->course_notifystudents = $this->getContents();
5201 break;
5202 case "EXPIRYTHRESHOLD":
5203 $this->info->course_expirythreshold = $this->getContents();
5204 break;
5205 case "ENROLLABLE":
5206 $this->info->course_enrollable = $this->getContents();
5207 break;
5208 case "ENROLSTARTDATE":
5209 $this->info->course_enrolstartdate = $this->getContents();
5210 break;
5211 case "ENROLENDDATE":
5212 $this->info->course_enrolenddate = $this->getContents();
5213 break;
5214 case "ENROLPERIOD":
5215 $this->info->course_enrolperiod = $this->getContents();
5216 break;
5219 if ($this->tree[4] == "CATEGORY") {
5220 if ($this->level == 5) {
5221 switch ($tagName) {
5222 case "ID":
5223 $this->info->category->id = $this->getContents();
5224 break;
5225 case "NAME":
5226 $this->info->category->name = $this->getContents();
5227 break;
5232 if ($this->tree[4] == "ROLES_ASSIGNMENTS") {
5233 if ($this->level == 6) {
5234 switch ($tagName) {
5235 case "NAME":
5236 $this->info->tempname = $this->getContents();
5237 break;
5238 case "SHORTNAME":
5239 $this->info->tempshortname = $this->getContents();
5240 break;
5241 case "ID":
5242 $this->info->tempid = $this->getContents();
5243 break;
5247 if ($this->level == 8) {
5248 switch ($tagName) {
5249 case "USERID":
5250 $this->info->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5251 $this->info->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5252 $this->info->tempuser = $this->getContents();
5253 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5254 break;
5255 case "HIDDEN":
5256 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5257 break;
5258 case "TIMESTART":
5259 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5260 break;
5261 case "TIMEEND":
5262 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5263 break;
5264 case "TIMEMODIFIED":
5265 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5266 break;
5267 case "MODIFIERID":
5268 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5269 break;
5270 case "ENROL":
5271 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5272 break;
5273 case "SORTORDER":
5274 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5275 break;
5279 } /// ends role_assignments
5281 if ($this->tree[4] == "ROLES_OVERRIDES") {
5282 if ($this->level == 6) {
5283 switch ($tagName) {
5284 case "NAME":
5285 $this->info->tempname = $this->getContents();
5286 break;
5287 case "SHORTNAME":
5288 $this->info->tempshortname = $this->getContents();
5289 break;
5290 case "ID":
5291 $this->info->tempid = $this->getContents();
5292 break;
5296 if ($this->level == 8) {
5297 switch ($tagName) {
5298 case "NAME":
5299 $this->info->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5300 $this->info->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5301 $this->info->tempname = $this->getContents(); // change to name of capability
5302 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5303 break;
5304 case "PERMISSION":
5305 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5306 break;
5307 case "TIMEMODIFIED":
5308 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5309 break;
5310 case "MODIFIERID":
5311 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5312 break;
5315 } /// ends role_overrides
5318 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
5319 //Speed up a lot (avoid parse all)
5320 if ($tagName == "HEADER") {
5321 $this->finished = true;
5324 //Clear things
5325 $this->tree[$this->level] = "";
5326 $this->level--;
5327 $this->content = "";
5331 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
5332 function endElementBlocks($parser, $tagName) {
5333 //Check if we are into BLOCKS zone
5334 if ($this->tree[3] == 'BLOCKS') {
5335 //if (trim($this->content)) //Debug
5336 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5337 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5339 // Collect everything into $this->temp
5340 if (!isset($this->temp)) {
5341 $this->temp = "";
5343 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5345 //Dependig of different combinations, do different things
5346 if ($this->level == 4) {
5347 switch ($tagName) {
5348 case 'BLOCK':
5349 //We've finalized a block, get it
5350 $this->info->instances[] = $this->info->tempinstance;
5351 unset($this->info->tempinstance);
5353 //Also, xmlize INSTANCEDATA and save to db
5354 //Prepend XML standard header to info gathered
5355 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5356 //Call to xmlize for this portion of xml data (one BLOCK)
5357 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5358 $data = xmlize($xml_data,0);
5359 //echo strftime ("%X",time())."<p>"; //Debug
5360 //traverse_xmlize($data); //Debug
5361 //print_object ($GLOBALS['traverse_array']); //Debug
5362 //$GLOBALS['traverse_array']=""; //Debug
5363 //Check for instancedata, is exists, then save to DB
5364 if (isset($data['BLOCK']['#']['INSTANCEDATA']['0']['#'])) {
5365 //Get old id
5366 $oldid = $data['BLOCK']['#']['ID']['0']['#'];
5367 //Get instancedata
5369 if ($data = $data['BLOCK']['#']['INSTANCEDATA']['0']['#']) {
5370 //Restore code calls this multiple times - so might already have the newid
5371 if ($newid = backup_getid($this->preferences->backup_unique_code,'block_instance',$oldid)) {
5372 $newid = $newid->new_id;
5373 } else {
5374 $newid = null;
5376 //Save to DB, we will use it later
5377 $status = backup_putid($this->preferences->backup_unique_code,'block_instance',$oldid,$newid,$data);
5380 //Reset temp
5381 unset($this->temp);
5383 break;
5384 default:
5385 die($tagName);
5388 if ($this->level == 5) {
5389 switch ($tagName) {
5390 case 'ID':
5391 $this->info->tempinstance->id = $this->getContents();
5392 case 'NAME':
5393 $this->info->tempinstance->name = $this->getContents();
5394 break;
5395 case 'PAGEID':
5396 $this->info->tempinstance->pageid = $this->getContents();
5397 break;
5398 case 'PAGETYPE':
5399 $this->info->tempinstance->pagetype = $this->getContents();
5400 break;
5401 case 'POSITION':
5402 $this->info->tempinstance->position = $this->getContents();
5403 break;
5404 case 'WEIGHT':
5405 $this->info->tempinstance->weight = $this->getContents();
5406 break;
5407 case 'VISIBLE':
5408 $this->info->tempinstance->visible = $this->getContents();
5409 break;
5410 case 'CONFIGDATA':
5411 $this->info->tempinstance->configdata = $this->getContents();
5412 break;
5413 default:
5414 break;
5418 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
5419 if ($this->level == 7) {
5420 switch ($tagName) {
5421 case "NAME":
5422 $this->info->tempname = $this->getContents();
5423 break;
5424 case "SHORTNAME":
5425 $this->info->tempshortname = $this->getContents();
5426 break;
5427 case "ID":
5428 $this->info->tempid = $this->getContents(); // temp roleid
5429 break;
5433 if ($this->level == 9) {
5435 switch ($tagName) {
5436 case "USERID":
5437 $this->info->tempinstance->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5439 $this->info->tempinstance->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5441 $this->info->tempuser = $this->getContents();
5443 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5444 break;
5445 case "HIDDEN":
5446 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5447 break;
5448 case "TIMESTART":
5449 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5450 break;
5451 case "TIMEEND":
5452 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5453 break;
5454 case "TIMEMODIFIED":
5455 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5456 break;
5457 case "MODIFIERID":
5458 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5459 break;
5460 case "ENROL":
5461 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5462 break;
5463 case "SORTORDER":
5464 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5465 break;
5469 } /// ends role_assignments
5471 if ($this->tree[5] == "ROLES_OVERRIDES") {
5472 if ($this->level == 7) {
5473 switch ($tagName) {
5474 case "NAME":
5475 $this->info->tempname = $this->getContents();
5476 break;
5477 case "SHORTNAME":
5478 $this->info->tempshortname = $this->getContents();
5479 break;
5480 case "ID":
5481 $this->info->tempid = $this->getContents(); // temp roleid
5482 break;
5486 if ($this->level == 9) {
5487 switch ($tagName) {
5488 case "NAME":
5490 $this->info->tempinstance->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5491 $this->info->tempinstance->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5492 $this->info->tempname = $this->getContents(); // change to name of capability
5493 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5494 break;
5495 case "PERMISSION":
5496 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5497 break;
5498 case "TIMEMODIFIED":
5499 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5500 break;
5501 case "MODIFIERID":
5502 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5503 break;
5506 } /// ends role_overrides
5509 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
5510 //Speed up a lot (avoid parse all)
5511 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
5512 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
5513 if ($this->tree[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
5514 $this->finished = true;
5517 //Clear things
5518 $this->tree[$this->level] = '';
5519 $this->level--;
5520 $this->content = "";
5523 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
5524 function endElementSections($parser, $tagName) {
5525 //Check if we are into SECTIONS zone
5526 if ($this->tree[3] == "SECTIONS") {
5527 //if (trim($this->content)) //Debug
5528 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5529 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5530 //Dependig of different combinations, do different things
5531 if ($this->level == 4) {
5532 switch ($tagName) {
5533 case "SECTION":
5534 //We've finalized a section, get it
5535 $this->info->sections[$this->info->tempsection->id] = $this->info->tempsection;
5536 unset($this->info->tempsection);
5539 if ($this->level == 5) {
5540 switch ($tagName) {
5541 case "ID":
5542 $this->info->tempsection->id = $this->getContents();
5543 break;
5544 case "NUMBER":
5545 $this->info->tempsection->number = $this->getContents();
5546 break;
5547 case "SUMMARY":
5548 $this->info->tempsection->summary = $this->getContents();
5549 break;
5550 case "VISIBLE":
5551 $this->info->tempsection->visible = $this->getContents();
5552 break;
5555 if ($this->level == 6) {
5556 switch ($tagName) {
5557 case "MOD":
5558 if (!isset($this->info->tempmod->groupmode)) {
5559 $this->info->tempmod->groupmode = 0;
5561 if (!isset($this->info->tempmod->groupingid)) {
5562 $this->info->tempmod->groupingid = 0;
5564 if (!isset($this->info->tempmod->groupmembersonly)) {
5565 $this->info->tempmod->groupmembersonly = 0;
5567 if (!isset($this->info->tempmod->idnumber)) {
5568 $this->info->tempmod->idnumber = null;
5571 //We've finalized a mod, get it
5572 $this->info->tempsection->mods[$this->info->tempmod->id]->type =
5573 $this->info->tempmod->type;
5574 $this->info->tempsection->mods[$this->info->tempmod->id]->instance =
5575 $this->info->tempmod->instance;
5576 $this->info->tempsection->mods[$this->info->tempmod->id]->added =
5577 $this->info->tempmod->added;
5578 $this->info->tempsection->mods[$this->info->tempmod->id]->score =
5579 $this->info->tempmod->score;
5580 $this->info->tempsection->mods[$this->info->tempmod->id]->indent =
5581 $this->info->tempmod->indent;
5582 $this->info->tempsection->mods[$this->info->tempmod->id]->visible =
5583 $this->info->tempmod->visible;
5584 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmode =
5585 $this->info->tempmod->groupmode;
5586 $this->info->tempsection->mods[$this->info->tempmod->id]->groupingid =
5587 $this->info->tempmod->groupingid;
5588 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmembersonly =
5589 $this->info->tempmod->groupmembersonly;
5590 $this->info->tempsection->mods[$this->info->tempmod->id]->idnumber =
5591 $this->info->tempmod->idnumber;
5593 unset($this->info->tempmod);
5596 if ($this->level == 7) {
5597 switch ($tagName) {
5598 case "ID":
5599 $this->info->tempmod->id = $this->getContents();
5600 break;
5601 case "TYPE":
5602 $this->info->tempmod->type = $this->getContents();
5603 break;
5604 case "INSTANCE":
5605 $this->info->tempmod->instance = $this->getContents();
5606 break;
5607 case "ADDED":
5608 $this->info->tempmod->added = $this->getContents();
5609 break;
5610 case "SCORE":
5611 $this->info->tempmod->score = $this->getContents();
5612 break;
5613 case "INDENT":
5614 $this->info->tempmod->indent = $this->getContents();
5615 break;
5616 case "VISIBLE":
5617 $this->info->tempmod->visible = $this->getContents();
5618 break;
5619 case "GROUPMODE":
5620 $this->info->tempmod->groupmode = $this->getContents();
5621 break;
5622 case "GROUPINGID":
5623 $this->info->tempmod->groupingid = $this->getContents();
5624 break;
5625 case "GROUPMEMBERSONLY":
5626 $this->info->tempmod->groupmembersonly = $this->getContents();
5627 break;
5628 case "IDNUMBER":
5629 $this->info->tempmod->idnumber = $this->getContents();
5630 break;
5631 default:
5632 break;
5636 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_ASSIGNMENTS") {
5638 if ($this->level == 9) {
5639 switch ($tagName) {
5640 case "NAME":
5641 $this->info->tempname = $this->getContents();
5642 break;
5643 case "SHORTNAME":
5644 $this->info->tempshortname = $this->getContents();
5645 break;
5646 case "ID":
5647 $this->info->tempid = $this->getContents(); // temp roleid
5648 break;
5652 if ($this->level == 11) {
5653 switch ($tagName) {
5654 case "USERID":
5655 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5657 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5659 $this->info->tempuser = $this->getContents();
5661 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5662 break;
5663 case "HIDDEN":
5664 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5665 break;
5666 case "TIMESTART":
5667 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5668 break;
5669 case "TIMEEND":
5670 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5671 break;
5672 case "TIMEMODIFIED":
5673 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5674 break;
5675 case "MODIFIERID":
5676 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5677 break;
5678 case "ENROL":
5679 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5680 break;
5681 case "SORTORDER":
5682 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5683 break;
5687 } /// ends role_assignments
5689 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_OVERRIDES") {
5690 if ($this->level == 9) {
5691 switch ($tagName) {
5692 case "NAME":
5693 $this->info->tempname = $this->getContents();
5694 break;
5695 case "SHORTNAME":
5696 $this->info->tempshortname = $this->getContents();
5697 break;
5698 case "ID":
5699 $this->info->tempid = $this->getContents(); // temp roleid
5700 break;
5704 if ($this->level == 11) {
5705 switch ($tagName) {
5706 case "NAME":
5708 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5709 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5710 $this->info->tempname = $this->getContents(); // change to name of capability
5711 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5712 break;
5713 case "PERMISSION":
5714 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5715 break;
5716 case "TIMEMODIFIED":
5717 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5718 break;
5719 case "MODIFIERID":
5720 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5721 break;
5724 } /// ends role_overrides
5728 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
5729 //Speed up a lot (avoid parse all)
5730 if ($tagName == "SECTIONS") {
5731 $this->finished = true;
5734 //Clear things
5735 $this->tree[$this->level] = "";
5736 $this->level--;
5737 $this->content = "";
5741 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
5742 function endElementFormatData($parser, $tagName) {
5743 //Check if we are into FORMATDATA zone
5744 if ($this->tree[3] == 'FORMATDATA') {
5745 if (!isset($this->temp)) {
5746 $this->temp = '';
5748 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5751 if($tagName=='FORMATDATA') {
5752 //Did we have any data? If not don't bother
5753 if($this->temp!='<FORMATDATA></FORMATDATA>') {
5754 //Prepend XML standard header to info gathered
5755 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5756 $this->temp='';
5758 //Call to xmlize for this portion of xml data (the FORMATDATA block)
5759 $this->info->format_data = xmlize($xml_data,0);
5761 //Stop parsing at end of FORMATDATA
5762 $this->finished=true;
5765 //Clear things
5766 $this->tree[$this->level] = "";
5767 $this->level--;
5768 $this->content = "";
5771 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
5772 function endElementMetacourse($parser, $tagName) {
5773 //Check if we are into METACOURSE zone
5774 if ($this->tree[3] == 'METACOURSE') {
5775 //if (trim($this->content)) //Debug
5776 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5777 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5778 //Dependig of different combinations, do different things
5779 if ($this->level == 5) {
5780 switch ($tagName) {
5781 case 'CHILD':
5782 //We've finalized a child, get it
5783 $this->info->childs[] = $this->info->tempmeta;
5784 unset($this->info->tempmeta);
5785 break;
5786 case 'PARENT':
5787 //We've finalized a parent, get it
5788 $this->info->parents[] = $this->info->tempmeta;
5789 unset($this->info->tempmeta);
5790 break;
5791 default:
5792 die($tagName);
5795 if ($this->level == 6) {
5796 switch ($tagName) {
5797 case 'ID':
5798 $this->info->tempmeta->id = $this->getContents();
5799 break;
5800 case 'IDNUMBER':
5801 $this->info->tempmeta->idnumber = $this->getContents();
5802 break;
5803 case 'SHORTNAME':
5804 $this->info->tempmeta->shortname = $this->getContents();
5805 break;
5810 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
5811 //Speed up a lot (avoid parse all)
5812 if ($this->tree[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
5813 $this->finished = true;
5816 //Clear things
5817 $this->tree[$this->level] = '';
5818 $this->level--;
5819 $this->content = "";
5822 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5823 function endElementGradebook($parser, $tagName) {
5824 //Check if we are into GRADEBOOK zone
5825 if ($this->tree[3] == "GRADEBOOK") {
5826 //if (trim($this->content)) //Debug
5827 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5828 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
5829 //Acumulate data to info (content + close tag)
5830 //Reconvert: strip htmlchars again and trim to generate xml data
5831 if (!isset($this->temp)) {
5832 $this->temp = "";
5834 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5835 // We have finished outcome, grade_category or grade_item, reset accumulated
5836 // data because they are close tags
5837 if ($this->level == 4) {
5838 $this->temp = "";
5840 //If we've finished a grade item, xmlize it an save to db
5841 if (($this->level == 5) and ($tagName == "GRADE_ITEM")) {
5842 //Prepend XML standard header to info gathered
5843 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5844 //Call to xmlize for this portion of xml data (one PREFERENCE)
5845 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5846 $data = xmlize($xml_data,0);
5847 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
5848 $this->counter++;
5849 //Save to db
5851 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items', $item_id,
5852 null,$data);
5853 //Create returning info
5854 $this->info = $this->counter;
5855 //Reset temp
5857 unset($this->temp);
5860 //If we've finished a grade_category, xmlize it an save to db
5861 if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
5862 //Prepend XML standard header to info gathered
5863 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5864 //Call to xmlize for this portion of xml data (one CATECORY)
5865 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5866 $data = xmlize($xml_data,0);
5867 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5868 $this->counter++;
5869 //Save to db
5870 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories' ,$category_id,
5871 null,$data);
5872 //Create returning info
5873 $this->info = $this->counter;
5874 //Reset temp
5875 unset($this->temp);
5878 if (($this->level == 5) and ($tagName == "GRADE_LETTER")) {
5879 //Prepend XML standard header to info gathered
5880 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5881 //Call to xmlize for this portion of xml data (one CATECORY)
5882 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5883 $data = xmlize($xml_data,0);
5884 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
5885 $this->counter++;
5886 //Save to db
5887 $status = backup_putid($this->preferences->backup_unique_code, 'grade_letters' ,$letter_id,
5888 null,$data);
5889 //Create returning info
5890 $this->info = $this->counter;
5891 //Reset temp
5892 unset($this->temp);
5895 //If we've finished a grade_outcome, xmlize it an save to db
5896 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME")) {
5897 //Prepend XML standard header to info gathered
5898 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5899 //Call to xmlize for this portion of xml data (one CATECORY)
5900 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5901 $data = xmlize($xml_data,0);
5902 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
5903 $this->counter++;
5904 //Save to db
5905 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes' ,$outcome_id,
5906 null,$data);
5907 //Create returning info
5908 $this->info = $this->counter;
5909 //Reset temp
5910 unset($this->temp);
5913 //If we've finished a grade_outcomes_course, xmlize it an save to db
5914 if (($this->level == 5) and ($tagName == "GRADE_OUTCOMES_COURSE")) {
5915 //Prepend XML standard header to info gathered
5916 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5917 //Call to xmlize for this portion of xml data (one CATECORY)
5918 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5919 $data = xmlize($xml_data,0);
5920 $outcomes_course_id = $data["GRADE_OUTCOMES_COURSE"]["#"]["ID"]["0"]["#"];
5921 $this->counter++;
5922 //Save to db
5923 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_courses' ,$outcomes_course_id,
5924 null,$data);
5925 //Create returning info
5926 $this->info = $this->counter;
5927 //Reset temp
5928 unset($this->temp);
5931 if (($this->level == 5) and ($tagName == "GRADE_CATEGORIES_HISTORY")) {
5932 //Prepend XML standard header to info gathered
5933 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5934 //Call to xmlize for this portion of xml data (one PREFERENCE)
5935 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5936 $data = xmlize($xml_data,0);
5937 $id = $data["GRADE_CATEGORIES_HISTORY"]["#"]["ID"]["0"]["#"];
5938 $this->counter++;
5939 //Save to db
5941 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories_history', $id,
5942 null,$data);
5943 //Create returning info
5944 $this->info = $this->counter;
5945 //Reset temp
5947 unset($this->temp);
5950 if (($this->level == 5) and ($tagName == "GRADE_GRADES_HISTORY")) {
5951 //Prepend XML standard header to info gathered
5952 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5953 //Call to xmlize for this portion of xml data (one PREFERENCE)
5954 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5955 $data = xmlize($xml_data,0);
5956 $id = $data["GRADE_GRADES_HISTORY"]["#"]["ID"]["0"]["#"];
5957 $this->counter++;
5958 //Save to db
5960 $status = backup_putid($this->preferences->backup_unique_code, 'grade_grades_history', $id,
5961 null,$data);
5962 //Create returning info
5963 $this->info = $this->counter;
5964 //Reset temp
5966 unset($this->temp);
5969 if (($this->level == 5) and ($tagName == "GRADE_ITEM_HISTORY")) {
5970 //Prepend XML standard header to info gathered
5971 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5972 //Call to xmlize for this portion of xml data (one PREFERENCE)
5973 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5974 $data = xmlize($xml_data,0);
5975 $id = $data["GRADE_ITEM_HISTORY"]["#"]["ID"]["0"]["#"];
5976 $this->counter++;
5977 //Save to db
5979 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items_history', $id,
5980 null,$data);
5981 //Create returning info
5982 $this->info = $this->counter;
5983 //Reset temp
5985 unset($this->temp);
5988 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME_HISTORY")) {
5989 //Prepend XML standard header to info gathered
5990 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5991 //Call to xmlize for this portion of xml data (one PREFERENCE)
5992 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5993 $data = xmlize($xml_data,0);
5994 $id = $data["GRADE_OUTCOME_HISTORY"]["#"]["ID"]["0"]["#"];
5995 $this->counter++;
5996 //Save to db
5998 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_history', $id,
5999 null,$data);
6000 //Create returning info
6001 $this->info = $this->counter;
6002 //Reset temp
6004 unset($this->temp);
6008 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
6009 //Speed up a lot (avoid parse all)
6010 if ($tagName == "GRADEBOOK" and $this->level == 3) {
6011 $this->finished = true;
6012 $this->counter = 0;
6015 //Clear things
6016 $this->tree[$this->level] = "";
6017 $this->level--;
6018 $this->content = "";
6022 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
6023 function endElementOldGradebook($parser, $tagName) {
6024 //Check if we are into GRADEBOOK zone
6025 if ($this->tree[3] == "GRADEBOOK") {
6026 //if (trim($this->content)) //Debug
6027 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6028 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
6029 //Acumulate data to info (content + close tag)
6030 //Reconvert: strip htmlchars again and trim to generate xml data
6031 if (!isset($this->temp)) {
6032 $this->temp = "";
6034 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6035 //We have finished preferences, letters or categories, reset accumulated
6036 //data because they are close tags
6037 if ($this->level == 4) {
6038 $this->temp = "";
6040 //If we've finished a message, xmlize it an save to db
6041 if (($this->level == 5) and ($tagName == "GRADE_PREFERENCE")) {
6042 //Prepend XML standard header to info gathered
6043 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6044 //Call to xmlize for this portion of xml data (one PREFERENCE)
6045 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6046 $data = xmlize($xml_data,0);
6047 //echo strftime ("%X",time())."<p>"; //Debug
6048 //traverse_xmlize($data); //Debug
6049 //print_object ($GLOBALS['traverse_array']); //Debug
6050 //$GLOBALS['traverse_array']=""; //Debug
6051 //Now, save data to db. We'll use it later
6052 //Get id and status from data
6053 $preference_id = $data["GRADE_PREFERENCE"]["#"]["ID"]["0"]["#"];
6054 $this->counter++;
6055 //Save to db
6056 $status = backup_putid($this->preferences->backup_unique_code, 'grade_preferences', $preference_id,
6057 null,$data);
6058 //Create returning info
6059 $this->info = $this->counter;
6060 //Reset temp
6061 unset($this->temp);
6063 //If we've finished a grade_letter, xmlize it an save to db
6064 if (($this->level == 5) and ($tagName == "GRADE_LETTER")) {
6065 //Prepend XML standard header to info gathered
6066 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6067 //Call to xmlize for this portion of xml data (one LETTER)
6068 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6069 $data = xmlize($xml_data,0);
6070 //echo strftime ("%X",time())."<p>"; //Debug
6071 //traverse_xmlize($data); //Debug
6072 //print_object ($GLOBALS['traverse_array']); //Debug
6073 //$GLOBALS['traverse_array']=""; //Debug
6074 //Now, save data to db. We'll use it later
6075 //Get id and status from data
6076 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
6077 $this->counter++;
6078 //Save to db
6079 $status = backup_putid($this->preferences->backup_unique_code, 'grade_letter' ,$letter_id,
6080 null,$data);
6081 //Create returning info
6082 $this->info = $this->counter;
6083 //Reset temp
6084 unset($this->temp);
6087 //If we've finished a grade_category, xmlize it an save to db
6088 if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
6089 //Prepend XML standard header to info gathered
6090 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6091 //Call to xmlize for this portion of xml data (one CATECORY)
6092 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6093 $data = xmlize($xml_data,0);
6094 //echo strftime ("%X",time())."<p>"; //Debug
6095 //traverse_xmlize($data); //Debug
6096 //print_object ($GLOBALS['traverse_array']); //Debug
6097 //$GLOBALS['traverse_array']=""; //Debug
6098 //Now, save data to db. We'll use it later
6099 //Get id and status from data
6100 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
6101 $this->counter++;
6102 //Save to db
6103 $status = backup_putid($this->preferences->backup_unique_code, 'grade_category' ,$category_id,
6104 null,$data);
6105 //Create returning info
6106 $this->info = $this->counter;
6107 //Reset temp
6108 unset($this->temp);
6112 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
6113 //Speed up a lot (avoid parse all)
6114 if ($tagName == "GRADEBOOK" and $this->level == 3) {
6115 $this->finished = true;
6116 $this->counter = 0;
6119 //Clear things
6120 $this->tree[$this->level] = "";
6121 $this->level--;
6122 $this->content = "";
6126 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
6127 function endElementUsers($parser, $tagName) {
6128 global $CFG;
6129 //Check if we are into USERS zone
6130 if ($this->tree[3] == "USERS") {
6131 //if (trim($this->content)) //Debug
6132 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6133 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6134 //Dependig of different combinations, do different things
6135 if ($this->level == 4) {
6136 switch ($tagName) {
6137 case "USER":
6138 //Increment counter
6139 $this->counter++;
6140 //Save to db, only save if record not already exist
6141 // if there already is an new_id for this entry, just use that new_id?
6142 $newuser = backup_getid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id);
6143 if (isset($newuser->new_id)) {
6144 $newid = $newuser->new_id;
6145 } else {
6146 $newid = null;
6149 backup_putid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id,
6150 $newid,$this->info->tempuser);
6152 //Do some output
6153 if ($this->counter % 10 == 0) {
6154 if (!defined('RESTORE_SILENTLY')) {
6155 echo ".";
6156 if ($this->counter % 200 == 0) {
6157 echo "<br />";
6160 backup_flush(300);
6163 //Delete temp obejct
6164 unset($this->info->tempuser);
6165 break;
6169 if ($this->level == 5) {
6170 switch ($tagName) {
6171 case "ID":
6172 $this->info->users[$this->getContents()] = $this->getContents();
6173 $this->info->tempuser->id = $this->getContents();
6174 break;
6175 case "AUTH":
6176 $this->info->tempuser->auth = $this->getContents();
6177 break;
6178 case "CONFIRMED":
6179 $this->info->tempuser->confirmed = $this->getContents();
6180 break;
6181 case "POLICYAGREED":
6182 $this->info->tempuser->policyagreed = $this->getContents();
6183 break;
6184 case "DELETED":
6185 $this->info->tempuser->deleted = $this->getContents();
6186 break;
6187 case "USERNAME":
6188 $this->info->tempuser->username = $this->getContents();
6189 break;
6190 case "PASSWORD":
6191 $this->info->tempuser->password = $this->getContents();
6192 break;
6193 case "IDNUMBER":
6194 $this->info->tempuser->idnumber = $this->getContents();
6195 break;
6196 case "FIRSTNAME":
6197 $this->info->tempuser->firstname = $this->getContents();
6198 break;
6199 case "LASTNAME":
6200 $this->info->tempuser->lastname = $this->getContents();
6201 break;
6202 case "EMAIL":
6203 $this->info->tempuser->email = $this->getContents();
6204 break;
6205 case "EMAILSTOP":
6206 $this->info->tempuser->emailstop = $this->getContents();
6207 break;
6208 case "ICQ":
6209 $this->info->tempuser->icq = $this->getContents();
6210 break;
6211 case "SKYPE":
6212 $this->info->tempuser->skype = $this->getContents();
6213 break;
6214 case "AIM":
6215 $this->info->tempuser->aim = $this->getContents();
6216 break;
6217 case "YAHOO":
6218 $this->info->tempuser->yahoo = $this->getContents();
6219 break;
6220 case "MSN":
6221 $this->info->tempuser->msn = $this->getContents();
6222 break;
6223 case "PHONE1":
6224 $this->info->tempuser->phone1 = $this->getContents();
6225 break;
6226 case "PHONE2":
6227 $this->info->tempuser->phone2 = $this->getContents();
6228 break;
6229 case "INSTITUTION":
6230 $this->info->tempuser->institution = $this->getContents();
6231 break;
6232 case "DEPARTMENT":
6233 $this->info->tempuser->department = $this->getContents();
6234 break;
6235 case "ADDRESS":
6236 $this->info->tempuser->address = $this->getContents();
6237 break;
6238 case "CITY":
6239 $this->info->tempuser->city = $this->getContents();
6240 break;
6241 case "COUNTRY":
6242 $this->info->tempuser->country = $this->getContents();
6243 break;
6244 case "LANG":
6245 $this->info->tempuser->lang = $this->getContents();
6246 break;
6247 case "THEME":
6248 $this->info->tempuser->theme = $this->getContents();
6249 break;
6250 case "TIMEZONE":
6251 $this->info->tempuser->timezone = $this->getContents();
6252 break;
6253 case "FIRSTACCESS":
6254 $this->info->tempuser->firstaccess = $this->getContents();
6255 break;
6256 case "LASTACCESS":
6257 $this->info->tempuser->lastaccess = $this->getContents();
6258 break;
6259 case "LASTLOGIN":
6260 $this->info->tempuser->lastlogin = $this->getContents();
6261 break;
6262 case "CURRENTLOGIN":
6263 $this->info->tempuser->currentlogin = $this->getContents();
6264 break;
6265 case "LASTIP":
6266 $this->info->tempuser->lastip = $this->getContents();
6267 break;
6268 case "SECRET":
6269 $this->info->tempuser->secret = $this->getContents();
6270 break;
6271 case "PICTURE":
6272 $this->info->tempuser->picture = $this->getContents();
6273 break;
6274 case "URL":
6275 $this->info->tempuser->url = $this->getContents();
6276 break;
6277 case "DESCRIPTION":
6278 $this->info->tempuser->description = $this->getContents();
6279 break;
6280 case "MAILFORMAT":
6281 $this->info->tempuser->mailformat = $this->getContents();
6282 break;
6283 case "MAILDIGEST":
6284 $this->info->tempuser->maildigest = $this->getContents();
6285 break;
6286 case "MAILDISPLAY":
6287 $this->info->tempuser->maildisplay = $this->getContents();
6288 break;
6289 case "HTMLEDITOR":
6290 $this->info->tempuser->htmleditor = $this->getContents();
6291 break;
6292 case "AJAX":
6293 $this->info->tempuser->ajax = $this->getContents();
6294 break;
6295 case "AUTOSUBSCRIBE":
6296 $this->info->tempuser->autosubscribe = $this->getContents();
6297 break;
6298 case "TRACKFORUMS":
6299 $this->info->tempuser->trackforums = $this->getContents();
6300 break;
6301 case "MNETHOSTURL":
6302 $this->info->tempuser->mnethosturl = $this->getContents();
6303 break;
6304 case "TIMEMODIFIED":
6305 $this->info->tempuser->timemodified = $this->getContents();
6306 break;
6307 default:
6308 break;
6312 if ($this->level == 6 && $this->tree[5]!="ROLES_ASSIGNMENTS" && $this->tree[5]!="ROLES_OVERRIDES") {
6313 switch ($tagName) {
6314 case "ROLE":
6315 //We've finalized a role, get it
6316 $this->info->tempuser->roles[$this->info->temprole->type] = $this->info->temprole;
6317 unset($this->info->temprole);
6318 break;
6319 case "USER_PREFERENCE":
6320 //We've finalized a user_preference, get it
6321 $this->info->tempuser->user_preferences[$this->info->tempuserpreference->name] = $this->info->tempuserpreference;
6322 unset($this->info->tempuserpreference);
6323 break;
6324 case "USER_CUSTOM_PROFILE_FIELD":
6325 //We've finalized a user_custom_profile_field, get it
6326 $this->info->tempuser->user_custom_profile_fields[] = $this->info->tempusercustomprofilefield;
6327 unset($this->info->tempusercustomprofilefield);
6328 break;
6329 case "USER_TAG":
6330 //We've finalized a user_tag, get it
6331 $this->info->tempuser->user_tags[] = $this->info->tempusertag;
6332 unset($this->info->tempusertag);
6333 break;
6334 default:
6335 break;
6339 if ($this->level == 7 && $this->tree[5]!="ROLES_ASSIGNMENTS" && $this->tree[5]!="ROLES_OVERRIDES") {
6340 /// If we are reading roles
6341 if($this->tree[6] == 'ROLE') {
6342 switch ($tagName) {
6343 case "TYPE":
6344 $this->info->temprole->type = $this->getContents();
6345 break;
6346 case "AUTHORITY":
6347 $this->info->temprole->authority = $this->getContents();
6348 break;
6349 case "TEA_ROLE":
6350 $this->info->temprole->tea_role = $this->getContents();
6351 break;
6352 case "EDITALL":
6353 $this->info->temprole->editall = $this->getContents();
6354 break;
6355 case "TIMESTART":
6356 $this->info->temprole->timestart = $this->getContents();
6357 break;
6358 case "TIMEEND":
6359 $this->info->temprole->timeend = $this->getContents();
6360 break;
6361 case "TIMEMODIFIED":
6362 $this->info->temprole->timemodified = $this->getContents();
6363 break;
6364 case "TIMESTART":
6365 $this->info->temprole->timestart = $this->getContents();
6366 break;
6367 case "TIMEEND":
6368 $this->info->temprole->timeend = $this->getContents();
6369 break;
6370 case "TIME":
6371 $this->info->temprole->time = $this->getContents();
6372 break;
6373 case "TIMEACCESS":
6374 $this->info->temprole->timeaccess = $this->getContents();
6375 break;
6376 case "ENROL":
6377 $this->info->temprole->enrol = $this->getContents();
6378 break;
6379 default:
6380 break;
6382 /// If we are reading user_preferences
6383 } else if ($this->tree[6] == 'USER_PREFERENCE') {
6384 switch ($tagName) {
6385 case "NAME":
6386 $this->info->tempuserpreference->name = $this->getContents();
6387 break;
6388 case "VALUE":
6389 $this->info->tempuserpreference->value = $this->getContents();
6390 break;
6391 default:
6392 break;
6394 /// If we are reading user_custom_profile_fields
6395 } else if ($this->tree[6] == 'USER_CUSTOM_PROFILE_FIELD') {
6396 switch ($tagName) {
6397 case "FIELD_NAME":
6398 $this->info->tempusercustomprofilefield->field_name = $this->getContents();
6399 break;
6400 case "FIELD_TYPE":
6401 $this->info->tempusercustomprofilefield->field_type = $this->getContents();
6402 break;
6403 case "FIELD_DATA":
6404 $this->info->tempusercustomprofilefield->field_data = $this->getContents();
6405 break;
6406 default:
6407 break;
6409 /// If we are reading user_tags
6410 } else if ($this->tree[6] == 'USER_TAG') {
6411 switch ($tagName) {
6412 case "NAME":
6413 $this->info->tempusertag->name = $this->getContents();
6414 break;
6415 case "RAWNAME":
6416 $this->info->tempusertag->rawname = $this->getContents();
6417 break;
6418 default:
6419 break;
6424 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
6426 if ($this->level == 7) {
6427 switch ($tagName) {
6428 case "NAME":
6429 $this->info->tempname = $this->getContents();
6430 break;
6431 case "SHORTNAME":
6432 $this->info->tempshortname = $this->getContents();
6433 break;
6434 case "ID":
6435 $this->info->tempid = $this->getContents(); // temp roleid
6436 break;
6440 if ($this->level == 9) {
6442 switch ($tagName) {
6443 case "USERID":
6444 $this->info->tempuser->roleassignments[$this->info->tempid]->name = $this->info->tempname;
6446 $this->info->tempuser->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
6448 $this->info->tempuserid = $this->getContents();
6450 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->userid = $this->getContents();
6451 break;
6452 case "HIDDEN":
6453 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->hidden = $this->getContents();
6454 break;
6455 case "TIMESTART":
6456 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timestart = $this->getContents();
6457 break;
6458 case "TIMEEND":
6459 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timeend = $this->getContents();
6460 break;
6461 case "TIMEMODIFIED":
6462 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timemodified = $this->getContents();
6463 break;
6464 case "MODIFIERID":
6465 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->modifierid = $this->getContents();
6466 break;
6467 case "ENROL":
6468 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->enrol = $this->getContents();
6469 break;
6470 case "SORTORDER":
6471 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->sortorder = $this->getContents();
6472 break;
6476 } /// ends role_assignments
6478 if ($this->tree[5] == "ROLES_OVERRIDES") {
6479 if ($this->level == 7) {
6480 switch ($tagName) {
6481 case "NAME":
6482 $this->info->tempname = $this->getContents();
6483 break;
6484 case "SHORTNAME":
6485 $this->info->tempshortname = $this->getContents();
6486 break;
6487 case "ID":
6488 $this->info->tempid = $this->getContents(); // temp roleid
6489 break;
6493 if ($this->level == 9) {
6494 switch ($tagName) {
6495 case "NAME":
6497 $this->info->tempuser->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
6498 $this->info->tempuser->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
6499 $this->info->tempname = $this->getContents(); // change to name of capability
6500 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
6501 break;
6502 case "PERMISSION":
6503 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
6504 break;
6505 case "TIMEMODIFIED":
6506 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
6507 break;
6508 case "MODIFIERID":
6509 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
6510 break;
6513 } /// ends role_overrides
6515 } // closes if this->tree[3]=="users"
6517 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
6518 //Speed up a lot (avoid parse all)
6519 if ($tagName == "USERS" and $this->level == 3) {
6520 $this->finished = true;
6521 $this->counter = 0;
6524 //Clear things
6525 $this->tree[$this->level] = "";
6526 $this->level--;
6527 $this->content = "";
6531 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
6532 function endElementMessages($parser, $tagName) {
6533 //Check if we are into MESSAGES zone
6534 if ($this->tree[3] == "MESSAGES") {
6535 //if (trim($this->content)) //Debug
6536 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6537 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
6538 //Acumulate data to info (content + close tag)
6539 //Reconvert: strip htmlchars again and trim to generate xml data
6540 if (!isset($this->temp)) {
6541 $this->temp = "";
6543 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6544 //If we've finished a message, xmlize it an save to db
6545 if (($this->level == 4) and ($tagName == "MESSAGE")) {
6546 //Prepend XML standard header to info gathered
6547 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6548 //Call to xmlize for this portion of xml data (one MESSAGE)
6549 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6550 $data = xmlize($xml_data,0);
6551 //echo strftime ("%X",time())."<p>"; //Debug
6552 //traverse_xmlize($data); //Debug
6553 //print_object ($GLOBALS['traverse_array']); //Debug
6554 //$GLOBALS['traverse_array']=""; //Debug
6555 //Now, save data to db. We'll use it later
6556 //Get id and status from data
6557 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
6558 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
6559 if ($message_status == "READ") {
6560 $table = "message_read";
6561 } else {
6562 $table = "message";
6564 $this->counter++;
6565 //Save to db
6566 $status = backup_putid($this->preferences->backup_unique_code, $table,$message_id,
6567 null,$data);
6568 //Create returning info
6569 $this->info = $this->counter;
6570 //Reset temp
6571 unset($this->temp);
6573 //If we've finished a contact, xmlize it an save to db
6574 if (($this->level == 5) and ($tagName == "CONTACT")) {
6575 //Prepend XML standard header to info gathered
6576 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6577 //Call to xmlize for this portion of xml data (one MESSAGE)
6578 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6579 $data = xmlize($xml_data,0);
6580 //echo strftime ("%X",time())."<p>"; //Debug
6581 //traverse_xmlize($data); //Debug
6582 //print_object ($GLOBALS['traverse_array']); //Debug
6583 //$GLOBALS['traverse_array']=""; //Debug
6584 //Now, save data to db. We'll use it later
6585 //Get id and status from data
6586 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
6587 $this->counter++;
6588 //Save to db
6589 $status = backup_putid($this->preferences->backup_unique_code, 'message_contacts' ,$contact_id,
6590 null,$data);
6591 //Create returning info
6592 $this->info = $this->counter;
6593 //Reset temp
6594 unset($this->temp);
6598 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
6599 //Speed up a lot (avoid parse all)
6600 if ($tagName == "MESSAGES" and $this->level == 3) {
6601 $this->finished = true;
6602 $this->counter = 0;
6605 //Clear things
6606 $this->tree[$this->level] = "";
6607 $this->level--;
6608 $this->content = "";
6612 //This is the endTag handler we use where we are reading the blogs zone (todo="BLOGS")
6613 function endElementBlogs($parser, $tagName) {
6614 //Check if we are into BLOGS zone
6615 if ($this->tree[3] == "BLOGS") {
6616 //if (trim($this->content)) //Debug
6617 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6618 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
6619 //Acumulate data to info (content + close tag)
6620 //Reconvert: strip htmlchars again and trim to generate xml data
6621 if (!isset($this->temp)) {
6622 $this->temp = "";
6624 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6625 //If we've finished a blog, xmlize it an save to db
6626 if (($this->level == 4) and ($tagName == "BLOG")) {
6627 //Prepend XML standard header to info gathered
6628 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6629 //Call to xmlize for this portion of xml data (one BLOG)
6630 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6631 $data = xmlize($xml_data,0);
6632 //echo strftime ("%X",time())."<p>"; //Debug
6633 //traverse_xmlize($data); //Debug
6634 //print_object ($GLOBALS['traverse_array']); //Debug
6635 //$GLOBALS['traverse_array']=""; //Debug
6636 //Now, save data to db. We'll use it later
6637 //Get id from data
6638 $blog_id = $data["BLOG"]["#"]["ID"]["0"]["#"];
6639 $this->counter++;
6640 //Save to db
6641 $status = backup_putid($this->preferences->backup_unique_code, 'blog', $blog_id,
6642 null,$data);
6643 //Create returning info
6644 $this->info = $this->counter;
6645 //Reset temp
6646 unset($this->temp);
6650 //Stop parsing if todo = BLOGS and tagName = BLOGS (end of the tag, of course)
6651 //Speed up a lot (avoid parse all)
6652 if ($tagName == "BLOGS" and $this->level == 3) {
6653 $this->finished = true;
6654 $this->counter = 0;
6657 //Clear things
6658 $this->tree[$this->level] = "";
6659 $this->level--;
6660 $this->content = "";
6664 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
6665 function endElementQuestions($parser, $tagName) {
6666 //Check if we are into QUESTION_CATEGORIES zone
6667 if ($this->tree[3] == "QUESTION_CATEGORIES") {
6668 //if (trim($this->content)) //Debug
6669 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6670 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6671 //Acumulate data to info (content + close tag)
6672 //Reconvert: strip htmlchars again and trim to generate xml data
6673 if (!isset($this->temp)) {
6674 $this->temp = "";
6676 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6677 //If we've finished a mod, xmlize it an save to db
6678 if (($this->level == 4) and ($tagName == "QUESTION_CATEGORY")) {
6679 //Prepend XML standard header to info gathered
6680 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6681 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
6682 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6683 $data = xmlize($xml_data,0);
6684 //echo strftime ("%X",time())."<p>"; //Debug
6685 //traverse_xmlize($data); //Debug
6686 //print_object ($GLOBALS['traverse_array']); //Debug
6687 //$GLOBALS['traverse_array']=""; //Debug
6688 //Now, save data to db. We'll use it later
6689 //Get id from data
6690 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
6691 //Save to db
6692 $status = backup_putid($this->preferences->backup_unique_code,"question_categories",$category_id,
6693 null,$data);
6694 //Create returning info
6695 $ret_info = new object();
6696 $ret_info->id = $category_id;
6697 $this->info[] = $ret_info;
6698 //Reset temp
6699 unset($this->temp);
6703 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
6704 //Speed up a lot (avoid parse all)
6705 if ($tagName == "QUESTION_CATEGORIES" and $this->level == 3) {
6706 $this->finished = true;
6709 //Clear things
6710 $this->tree[$this->level] = "";
6711 $this->level--;
6712 $this->content = "";
6716 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
6717 function endElementScales($parser, $tagName) {
6718 //Check if we are into SCALES zone
6719 if ($this->tree[3] == "SCALES") {
6720 //if (trim($this->content)) //Debug
6721 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6722 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6723 //Acumulate data to info (content + close tag)
6724 //Reconvert: strip htmlchars again and trim to generate xml data
6725 if (!isset($this->temp)) {
6726 $this->temp = "";
6728 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6729 //If we've finished a scale, xmlize it an save to db
6730 if (($this->level == 4) and ($tagName == "SCALE")) {
6731 //Prepend XML standard header to info gathered
6732 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6733 //Call to xmlize for this portion of xml data (one SCALE)
6734 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6735 $data = xmlize($xml_data,0);
6736 //echo strftime ("%X",time())."<p>"; //Debug
6737 //traverse_xmlize($data); //Debug
6738 //print_object ($GLOBALS['traverse_array']); //Debug
6739 //$GLOBALS['traverse_array']=""; //Debug
6740 //Now, save data to db. We'll use it later
6741 //Get id and from data
6742 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
6743 //Save to db
6744 $status = backup_putid($this->preferences->backup_unique_code,"scale",$scale_id,
6745 null,$data);
6746 //Create returning info
6747 $ret_info = new object();
6748 $ret_info->id = $scale_id;
6749 $this->info[] = $ret_info;
6750 //Reset temp
6751 unset($this->temp);
6755 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
6756 //Speed up a lot (avoid parse all)
6757 if ($tagName == "SCALES" and $this->level == 3) {
6758 $this->finished = true;
6761 //Clear things
6762 $this->tree[$this->level] = "";
6763 $this->level--;
6764 $this->content = "";
6768 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
6769 function endElementGroups($parser, $tagName) {
6770 //Check if we are into GROUPS zone
6771 if ($this->tree[3] == "GROUPS") {
6772 //if (trim($this->content)) //Debug
6773 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6774 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6775 //Acumulate data to info (content + close tag)
6776 //Reconvert: strip htmlchars again and trim to generate xml data
6777 if (!isset($this->temp)) {
6778 $this->temp = "";
6780 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6781 //If we've finished a group, xmlize it an save to db
6782 if (($this->level == 4) and ($tagName == "GROUP")) {
6783 //Prepend XML standard header to info gathered
6784 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6785 //Call to xmlize for this portion of xml data (one GROUP)
6786 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6787 $data = xmlize($xml_data,0);
6788 //echo strftime ("%X",time())."<p>"; //Debug
6789 //traverse_xmlize($data); //Debug
6790 //print_object ($GLOBALS['traverse_array']); //Debug
6791 //$GLOBALS['traverse_array']=""; //Debug
6792 //Now, save data to db. We'll use it later
6793 //Get id and from data
6794 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
6795 //Save to db
6796 $status = backup_putid($this->preferences->backup_unique_code,"groups",$group_id,
6797 null,$data);
6798 //Create returning info
6799 $ret_info = new Object();
6800 $ret_info->id = $group_id;
6801 $this->info[] = $ret_info;
6802 //Reset temp
6803 unset($this->temp);
6807 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
6808 //Speed up a lot (avoid parse all)
6809 if ($tagName == "GROUPS" and $this->level == 3) {
6810 $this->finished = true;
6813 //Clear things
6814 $this->tree[$this->level] = "";
6815 $this->level--;
6816 $this->content = "";
6820 //This is the endTag handler we use where we are reading the groupings zone (todo="GROUPINGS")
6821 function endElementGroupings($parser, $tagName) {
6822 //Check if we are into GROUPINGS zone
6823 if ($this->tree[3] == "GROUPINGS") {
6824 //Acumulate data to info (content + close tag)
6825 //Reconvert: strip htmlchars again and trim to generate xml data
6826 if (!isset($this->temp)) {
6827 $this->temp = "";
6829 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6830 //If we've finished a group, xmlize it an save to db
6831 if (($this->level == 4) and ($tagName == "GROUPING")) {
6832 //Prepend XML standard header to info gathered
6833 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6834 //Call to xmlize for this portion of xml data (one GROUPING)
6835 $data = xmlize($xml_data,0);
6836 //Now, save data to db. We'll use it later
6837 //Get id and from data
6838 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
6839 //Save to db
6840 $status = backup_putid($this->preferences->backup_unique_code,"groupings",$grouping_id,
6841 null,$data);
6842 //Create returning info
6843 $ret_info = new Object();
6844 $ret_info->id = $grouping_id;
6845 $this->info[] = $ret_info;
6846 //Reset temp
6847 unset($this->temp);
6851 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6852 //Speed up a lot (avoid parse all)
6853 if ($tagName == "GROUPINGS" and $this->level == 3) {
6854 $this->finished = true;
6857 //Clear things
6858 $this->tree[$this->level] = "";
6859 $this->level--;
6860 $this->content = "";
6864 //This is the endTag handler we use where we are reading the groupingsgroups zone (todo="GROUPINGGROUPS")
6865 function endElementGroupingsGroups($parser, $tagName) {
6866 //Check if we are into GROUPINGSGROUPS zone
6867 if ($this->tree[3] == "GROUPINGSGROUPS") {
6868 //Acumulate data to info (content + close tag)
6869 //Reconvert: strip htmlchars again and trim to generate xml data
6870 if (!isset($this->temp)) {
6871 $this->temp = "";
6873 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6874 //If we've finished a group, xmlize it an save to db
6875 if (($this->level == 4) and ($tagName == "GROUPINGGROUP")) {
6876 //Prepend XML standard header to info gathered
6877 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6878 //Call to xmlize for this portion of xml data (one GROUPING)
6879 $data = xmlize($xml_data,0);
6880 //Now, save data to db. We'll use it later
6881 //Get id and from data
6882 $groupinggroup_id = $data["GROUPINGGROUP"]["#"]["ID"]["0"]["#"];
6883 //Save to db
6884 $status = backup_putid($this->preferences->backup_unique_code,"groupingsgroups",$groupinggroup_id,
6885 null,$data);
6886 //Create returning info
6887 $ret_info = new Object();
6888 $ret_info->id = $groupinggroup_id;
6889 $this->info[] = $ret_info;
6890 //Reset temp
6891 unset($this->temp);
6895 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6896 //Speed up a lot (avoid parse all)
6897 if ($tagName == "GROUPINGSGROUPS" and $this->level == 3) {
6898 $this->finished = true;
6901 //Clear things
6902 $this->tree[$this->level] = "";
6903 $this->level--;
6904 $this->content = "";
6908 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
6909 function endElementEvents($parser, $tagName) {
6910 //Check if we are into EVENTS zone
6911 if ($this->tree[3] == "EVENTS") {
6912 //if (trim($this->content)) //Debug
6913 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6914 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6915 //Acumulate data to info (content + close tag)
6916 //Reconvert: strip htmlchars again and trim to generate xml data
6917 if (!isset($this->temp)) {
6918 $this->temp = "";
6920 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6921 //If we've finished a event, xmlize it an save to db
6922 if (($this->level == 4) and ($tagName == "EVENT")) {
6923 //Prepend XML standard header to info gathered
6924 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6925 //Call to xmlize for this portion of xml data (one EVENT)
6926 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6927 $data = xmlize($xml_data,0);
6928 //echo strftime ("%X",time())."<p>"; //Debug
6929 //traverse_xmlize($data); //Debug
6930 //print_object ($GLOBALS['traverse_array']); //Debug
6931 //$GLOBALS['traverse_array']=""; //Debug
6932 //Now, save data to db. We'll use it later
6933 //Get id and from data
6934 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
6935 //Save to db
6936 $status = backup_putid($this->preferences->backup_unique_code,"event",$event_id,
6937 null,$data);
6938 //Create returning info
6939 $ret_info = new object();
6940 $ret_info->id = $event_id;
6941 $this->info[] = $ret_info;
6942 //Reset temp
6943 unset($this->temp);
6947 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
6948 //Speed up a lot (avoid parse all)
6949 if ($tagName == "EVENTS" and $this->level == 3) {
6950 $this->finished = true;
6953 //Clear things
6954 $this->tree[$this->level] = "";
6955 $this->level--;
6956 $this->content = "";
6960 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
6961 function endElementModules($parser, $tagName) {
6962 //Check if we are into MODULES zone
6963 if ($this->tree[3] == "MODULES") {
6964 //if (trim($this->content)) //Debug
6965 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6966 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6967 //Acumulate data to info (content + close tag)
6968 //Reconvert: strip htmlchars again and trim to generate xml data
6969 if (!isset($this->temp)) {
6970 $this->temp = "";
6972 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6973 //If we've finished a mod, xmlize it an save to db
6974 if (($this->level == 4) and ($tagName == "MOD")) {
6975 //Prepend XML standard header to info gathered
6976 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6977 //Call to xmlize for this portion of xml data (one MOD)
6978 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6979 $data = xmlize($xml_data,0);
6980 //echo strftime ("%X",time())."<p>"; //Debug
6981 //traverse_xmlize($data); //Debug
6982 //print_object ($GLOBALS['traverse_array']); //Debug
6983 //$GLOBALS['traverse_array']=""; //Debug
6984 //Now, save data to db. We'll use it later
6985 //Get id and modtype from data
6986 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
6987 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
6988 //Only if we've selected to restore it
6989 if (!empty($this->preferences->mods[$mod_type]->restore)) {
6990 //Save to db
6991 $status = backup_putid($this->preferences->backup_unique_code,$mod_type,$mod_id,
6992 null,$data);
6993 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6994 //Create returning info
6995 $ret_info = new object();
6996 $ret_info->id = $mod_id;
6997 $ret_info->modtype = $mod_type;
6998 $this->info[] = $ret_info;
7000 //Reset temp
7001 unset($this->temp);
7007 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
7008 //Speed up a lot (avoid parse all)
7009 if ($tagName == "MODULES" and $this->level == 3) {
7010 $this->finished = true;
7013 //Clear things
7014 $this->tree[$this->level] = "";
7015 $this->level--;
7016 $this->content = "";
7020 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
7021 function endElementLogs($parser, $tagName) {
7022 //Check if we are into LOGS zone
7023 if ($this->tree[3] == "LOGS") {
7024 //if (trim($this->content)) //Debug
7025 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
7026 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
7027 //Acumulate data to info (content + close tag)
7028 //Reconvert: strip htmlchars again and trim to generate xml data
7029 if (!isset($this->temp)) {
7030 $this->temp = "";
7032 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
7033 //If we've finished a log, xmlize it an save to db
7034 if (($this->level == 4) and ($tagName == "LOG")) {
7035 //Prepend XML standard header to info gathered
7036 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
7037 //Call to xmlize for this portion of xml data (one LOG)
7038 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
7039 $data = xmlize($xml_data,0);
7040 //echo strftime ("%X",time())."<p>"; //Debug
7041 //traverse_xmlize($data); //Debug
7042 //print_object ($GLOBALS['traverse_array']); //Debug
7043 //$GLOBALS['traverse_array']=""; //Debug
7044 //Now, save data to db. We'll use it later
7045 //Get id and modtype from data
7046 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
7047 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
7048 //We only save log entries from backup file if they are:
7049 // - Course logs
7050 // - User logs
7051 // - Module logs about one restored module
7052 if ($log_module == "course" or
7053 $log_module == "user" or
7054 $this->preferences->mods[$log_module]->restore) {
7055 //Increment counter
7056 $this->counter++;
7057 //Save to db
7058 $status = backup_putid($this->preferences->backup_unique_code,"log",$log_id,
7059 null,$data);
7060 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
7061 //Create returning info
7062 $this->info = $this->counter;
7064 //Reset temp
7065 unset($this->temp);
7069 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
7070 //Speed up a lot (avoid parse all)
7071 if ($tagName == "LOGS" and $this->level == 3) {
7072 $this->finished = true;
7073 $this->counter = 0;
7076 //Clear things
7077 $this->tree[$this->level] = "";
7078 $this->level--;
7079 $this->content = "";
7083 //This is the endTag default handler we use when todo is undefined
7084 function endElement($parser, $tagName) {
7085 if (trim($this->content)) //Debug
7086 echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
7087 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
7089 //Clear things
7090 $this->tree[$this->level] = "";
7091 $this->level--;
7092 $this->content = "";
7095 //This is the handler to read data contents (simple accumule it)
7096 function characterData($parser, $data) {
7097 $this->content .= $data;
7101 //This function executes the MoodleParser
7102 function restore_read_xml ($xml_file,$todo,$preferences) {
7104 $status = true;
7106 $xml_parser = xml_parser_create('UTF-8');
7107 $moodle_parser = new MoodleParser();
7108 $moodle_parser->todo = $todo;
7109 $moodle_parser->preferences = $preferences;
7110 xml_set_object($xml_parser,$moodle_parser);
7111 //Depending of the todo we use some element_handler or another
7112 if ($todo == "INFO") {
7113 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
7114 } else if ($todo == "ROLES") {
7115 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
7116 } else if ($todo == "COURSE_HEADER") {
7117 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
7118 } else if ($todo == 'BLOCKS') {
7119 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
7120 } else if ($todo == "SECTIONS") {
7121 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
7122 } else if ($todo == 'FORMATDATA') {
7123 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
7124 } else if ($todo == "METACOURSE") {
7125 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
7126 } else if ($todo == "GRADEBOOK") {
7127 if ($preferences->backup_version > 2007090500) {
7128 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
7129 } else {
7130 xml_set_element_handler($xml_parser, "startElementOldGradebook", "endElementOldGradebook");
7132 } else if ($todo == "USERS") {
7133 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
7134 } else if ($todo == "MESSAGES") {
7135 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
7136 } else if ($todo == "BLOGS") {
7137 xml_set_element_handler($xml_parser, "startElementBlogs", "endElementBlogs");
7138 } else if ($todo == "QUESTIONS") {
7139 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
7140 } else if ($todo == "SCALES") {
7141 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
7142 } else if ($todo == "GROUPS") {
7143 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
7144 } else if ($todo == "GROUPINGS") {
7145 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
7146 } else if ($todo == "GROUPINGSGROUPS") {
7147 xml_set_element_handler($xml_parser, "startElementGroupingsGroups", "endElementGroupingsGroups");
7148 } else if ($todo == "EVENTS") {
7149 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
7150 } else if ($todo == "MODULES") {
7151 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
7152 } else if ($todo == "LOGS") {
7153 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
7154 } else {
7155 //Define default handlers (must no be invoked when everything become finished)
7156 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
7158 xml_set_character_data_handler($xml_parser, "characterData");
7159 $fp = fopen($xml_file,"r")
7160 or $status = false;
7161 if ($status) {
7162 // MDL-9290 performance improvement on reading large xml
7163 $lasttime = time(); // crmas
7164 while ($data = fread($fp, 4096) and !$moodle_parser->finished) {
7166 if ((time() - $lasttime) > 5) {
7167 $lasttime = time();
7168 backup_flush(1);
7171 xml_parse($xml_parser, $data, feof($fp))
7172 or die(sprintf("XML error: %s at line %d",
7173 xml_error_string(xml_get_error_code($xml_parser)),
7174 xml_get_current_line_number($xml_parser)));
7176 fclose($fp);
7178 //Get info from parser
7179 $info = $moodle_parser->info;
7181 //Clear parser mem
7182 xml_parser_free($xml_parser);
7184 if ($status && !empty($info)) {
7185 return $info;
7186 } else {
7187 return $status;
7192 * @param string $errorstr passed by reference, if silent is true,
7193 * errorstr will be populated and this function will return false rather than calling error() or notify()
7194 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
7195 * redirect to the next step in the restore process, instead will return $backup_unique_code
7197 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
7199 global $CFG, $SESSION;
7201 //Prepend dataroot to variable to have the absolute path
7202 $file = $CFG->dataroot."/".$file;
7204 if (!defined('RESTORE_SILENTLY')) {
7205 //Start the main table
7206 echo "<table cellpadding=\"5\">";
7207 echo "<tr><td>";
7209 //Start the mail ul
7210 echo "<ul>";
7213 //Check the file exists
7214 if (!is_file($file)) {
7215 if (!defined('RESTORE_SILENTLY')) {
7216 error ("File not exists ($file)");
7217 } else {
7218 $errorstr = "File not exists ($file)";
7219 return false;
7223 //Check the file name ends with .zip
7224 if (!substr($file,-4) == ".zip") {
7225 if (!defined('RESTORE_SILENTLY')) {
7226 error ("File has an incorrect extension");
7227 } else {
7228 $errorstr = 'File has an incorrect extension';
7229 return false;
7233 //Now calculate the unique_code for this restore
7234 $backup_unique_code = time();
7236 //Now check and create the backup dir (if it doesn't exist)
7237 if (!defined('RESTORE_SILENTLY')) {
7238 echo "<li>".get_string("creatingtemporarystructures").'</li>';
7240 $status = check_and_create_backup_dir($backup_unique_code);
7241 //Empty dir
7242 if ($status) {
7243 $status = clear_backup_dir($backup_unique_code);
7246 //Now delete old data and directories under dataroot/temp/backup
7247 if ($status) {
7248 if (!defined('RESTORE_SILENTLY')) {
7249 echo "<li>".get_string("deletingolddata").'</li>';
7251 $status = backup_delete_old_data();
7254 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
7255 if ($status) {
7256 if (!defined('RESTORE_SILENTLY')) {
7257 echo "<li>".get_string("copyingzipfile").'</li>';
7259 if (! $status = backup_copy_file($file,$CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
7260 if (!defined('RESTORE_SILENTLY')) {
7261 notify("Error copying backup file. Invalid name or bad perms.");
7262 } else {
7263 $errorstr = "Error copying backup file. Invalid name or bad perms";
7264 return false;
7269 //Now unzip the file
7270 if ($status) {
7271 if (!defined('RESTORE_SILENTLY')) {
7272 echo "<li>".get_string("unzippingbackup").'</li>';
7274 if (! $status = restore_unzip ($CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
7275 if (!defined('RESTORE_SILENTLY')) {
7276 notify("Error unzipping backup file. Invalid zip file.");
7277 } else {
7278 $errorstr = "Error unzipping backup file. Invalid zip file.";
7279 return false;
7284 //Check for Blackboard backups and convert
7285 if ($status){
7286 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
7287 if (!defined('RESTORE_SILENTLY')) {
7288 echo "<li>".get_string("checkingforbbexport").'</li>';
7290 $status = blackboard_convert($CFG->dataroot."/temp/backup/".$backup_unique_code);
7293 //Now check for the moodle.xml file
7294 if ($status) {
7295 $xml_file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
7296 if (!defined('RESTORE_SILENTLY')) {
7297 echo "<li>".get_string("checkingbackup").'</li>';
7299 if (! $status = restore_check_moodle_file ($xml_file)) {
7300 if (!is_file($xml_file)) {
7301 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
7302 } else {
7303 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
7305 if (!defined('RESTORE_SILENTLY')) {
7306 notify($errorstr);
7307 } else {
7308 return false;
7313 $info = "";
7314 $course_header = "";
7316 //Now read the info tag (all)
7317 if ($status) {
7318 if (!defined('RESTORE_SILENTLY')) {
7319 echo "<li>".get_string("readinginfofrombackup").'</li>';
7321 //Reading info from file
7322 $info = restore_read_xml_info ($xml_file);
7323 //Reading course_header from file
7324 $course_header = restore_read_xml_course_header ($xml_file);
7326 if(!is_object($course_header)){
7327 // ensure we fail if there is no course header
7328 $course_header = false;
7332 if (!defined('RESTORE_SILENTLY')) {
7333 //End the main ul
7334 echo "</ul>\n";
7336 //End the main table
7337 echo "</td></tr>";
7338 echo "</table>";
7341 //We compare Moodle's versions
7342 if ($CFG->version < $info->backup_moodle_version && $status) {
7343 $message = new object();
7344 $message->serverversion = $CFG->version;
7345 $message->serverrelease = $CFG->release;
7346 $message->backupversion = $info->backup_moodle_version;
7347 $message->backuprelease = $info->backup_moodle_release;
7348 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
7352 //Now we print in other table, the backup and the course it contains info
7353 if ($info and $course_header and $status) {
7354 //First, the course info
7355 if (!defined('RESTORE_SILENTLY')) {
7356 $status = restore_print_course_header($course_header);
7358 //Now, the backup info
7359 if ($status) {
7360 if (!defined('RESTORE_SILENTLY')) {
7361 $status = restore_print_info($info);
7366 //Save course header and info into php session
7367 if ($status) {
7368 $SESSION->info = $info;
7369 $SESSION->course_header = $course_header;
7372 //Finally, a little form to continue
7373 //with some hidden fields
7374 if ($status) {
7375 if (!defined('RESTORE_SILENTLY')) {
7376 echo "<br /><div style='text-align:center'>";
7377 $hidden["backup_unique_code"] = $backup_unique_code;
7378 $hidden["launch"] = "form";
7379 $hidden["file"] = $file;
7380 $hidden["id"] = $id;
7381 print_single_button("restore.php", $hidden, get_string("continue"),"post");
7382 echo "</div>";
7384 else {
7385 if (empty($noredirect)) {
7386 redirect($CFG->wwwroot.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
7387 } else {
7388 return $backup_unique_code;
7393 if (!$status) {
7394 if (!defined('RESTORE_SILENTLY')) {
7395 error ("An error has ocurred");
7396 } else {
7397 $errorstr = "An error has occured"; // helpful! :P
7398 return false;
7401 return true;
7404 function restore_setup_for_check(&$restore,$backup_unique_code) {
7405 global $SESSION;
7406 $restore->backup_unique_code=$backup_unique_code;
7407 $restore->users = 2; // yuk
7408 $restore->course_files = $SESSION->restore->restore_course_files;
7409 $restore->site_files = $SESSION->restore->restore_site_files;
7410 if ($allmods = get_records("modules")) {
7411 foreach ($allmods as $mod) {
7412 $modname = $mod->name;
7413 $var = "restore_".$modname;
7414 //Now check that we have that module info in the backup file
7415 if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
7416 $restore->$var = 1;
7420 return true;
7423 function backup_to_restore_array($backup,$k=0) {
7424 if (is_array($backup) ) {
7425 foreach ($backup as $key => $value) {
7426 $newkey = str_replace('backup','restore',$key);
7427 $restore[$newkey] = backup_to_restore_array($value,$key);
7430 else if (is_object($backup)) {
7431 $tmp = get_object_vars($backup);
7432 foreach ($tmp as $key => $value) {
7433 $newkey = str_replace('backup','restore',$key);
7434 $restore->$newkey = backup_to_restore_array($value,$key);
7437 else {
7438 $newkey = str_replace('backup','restore',$k);
7439 $restore = $backup;
7441 return $restore;
7445 * compatibility function
7446 * checks for per-instance backups AND
7447 * older per-module backups
7448 * and returns whether userdata has been selected.
7450 function restore_userdata_selected($restore,$modname,$modid) {
7451 // check first for per instance array
7452 if (!empty($restore->mods[$modname]->granular)) { // supports per instance
7453 return array_key_exists($modid,$restore->mods[$modname]->instances)
7454 && !empty($restore->mods[$modname]->instances[$modid]->userinfo);
7457 //print_object($restore->mods[$modname]);
7458 return !empty($restore->mods[$modname]->userinfo);
7461 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
7463 global $CFG, $USER;
7464 $status = true;
7466 //Checks for the required files/functions to restore every module
7467 //and include them
7468 if ($allmods = get_records("modules") ) {
7469 foreach ($allmods as $mod) {
7470 $modname = $mod->name;
7471 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
7472 //If file exists and we have selected to restore that type of module
7473 if ((file_exists($modfile)) and !empty($restore->mods[$modname]) and ($restore->mods[$modname]->restore)) {
7474 include_once($modfile);
7479 if (!defined('RESTORE_SILENTLY')) {
7480 //Start the main table
7481 echo "<table cellpadding=\"5\">";
7482 echo "<tr><td>";
7484 //Start the main ul
7485 echo "<ul>";
7488 //Localtion of the xml file
7489 $xml_file = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/moodle.xml";
7491 //If we've selected to restore into new course
7492 //create it (course)
7493 //Saving conversion id variables into backup_tables
7494 if ($restore->restoreto == 2) {
7495 if (!defined('RESTORE_SILENTLY')) {
7496 echo '<li>'.get_string('creatingnewcourse') . '</li>';
7498 $oldidnumber = $course_header->course_idnumber;
7499 if (!$status = restore_create_new_course($restore,$course_header)) {
7500 if (!defined('RESTORE_SILENTLY')) {
7501 notify("Error while creating the new empty course.");
7502 } else {
7503 $errorstr = "Error while creating the new empty course.";
7504 return false;
7508 //Print course fullname and shortname and category
7509 if ($status) {
7510 if (!defined('RESTORE_SILENTLY')) {
7511 echo "<ul>";
7512 echo "<li>".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
7513 echo "<li>".get_string("category").": ".$course_header->category->name.'</li>';
7514 if (!empty($oldidnumber)) {
7515 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
7517 echo "</ul>";
7518 //Put the destination course_id
7520 $restore->course_id = $course_header->course_id;
7523 if ($status = restore_open_html($restore,$course_header)){
7524 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
7527 } else {
7528 $course = get_record("course","id",$restore->course_id);
7529 if ($course) {
7530 if (!defined('RESTORE_SILENTLY')) {
7531 echo "<li>".get_string("usingexistingcourse");
7532 echo "<ul>";
7533 echo "<li>".get_string("from").": ".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
7534 echo "<li>".get_string("to").": ". format_string($course->fullname) ." (".format_string($course->shortname).")".'</li>';
7535 if (($restore->deleting)) {
7536 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
7537 } else {
7538 echo "<li>".get_string("addingdatatoexisting").'</li>';
7540 echo "</ul></li>";
7542 //If we have selected to restore deleting, we do it now.
7543 if ($restore->deleting) {
7544 if (!defined('RESTORE_SILENTLY')) {
7545 echo "<li>".get_string("deletingolddata").'</li>';
7547 $status = remove_course_contents($restore->course_id,false) and
7548 delete_dir_contents($CFG->dataroot."/".$restore->course_id,"backupdata");
7549 if ($status) {
7550 //Now , this situation is equivalent to the "restore to new course" one (we
7551 //have a course record and nothing more), so define it as "to new course"
7552 $restore->restoreto = 2;
7553 } else {
7554 if (!defined('RESTORE_SILENTLY')) {
7555 notify("An error occurred while deleting some of the course contents.");
7556 } else {
7557 $errrostr = "An error occurred while deleting some of the course contents.";
7558 return false;
7562 } else {
7563 if (!defined('RESTORE_SILENTLY')) {
7564 notify("Error opening existing course.");
7565 $status = false;
7566 } else {
7567 $errorstr = "Error opening existing course.";
7568 return false;
7573 //Now create users as needed
7574 if ($status and ($restore->users == 0 or $restore->users == 1)) {
7575 if (!defined('RESTORE_SILENTLY')) {
7576 echo "<li>".get_string("creatingusers")."<br />";
7578 if (!$status = restore_create_users($restore,$xml_file)) {
7579 if (!defined('RESTORE_SILENTLY')) {
7580 notify("Could not restore users.");
7581 } else {
7582 $errorstr = "Could not restore users.";
7583 return false;
7587 //Now print info about the work done
7588 if ($status) {
7589 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
7590 where backup_code = '$restore->backup_unique_code' and
7591 table_name = 'user'");
7592 //We've records
7593 if ($recs) {
7594 $new_count = 0;
7595 $exists_count = 0;
7596 $student_count = 0;
7597 $teacher_count = 0;
7598 $counter = 0;
7599 //Iterate, filling counters
7600 foreach ($recs as $rec) {
7601 //Get full record, using backup_getids
7602 $record = backup_getid($restore->backup_unique_code,"user",$rec->old_id);
7603 if (strpos($record->info,"new") !== false) {
7604 $new_count++;
7606 if (strpos($record->info,"exists") !== false) {
7607 $exists_count++;
7609 if (strpos($record->info,"student") !== false) {
7610 $student_count++;
7611 } else if (strpos($record->info,"teacher") !== false) {
7612 $teacher_count++;
7614 //Do some output
7615 $counter++;
7616 if ($counter % 10 == 0) {
7617 if (!defined('RESTORE_SILENTLY')) {
7618 echo ".";
7619 if ($counter % 200 == 0) {
7620 echo "<br />";
7623 backup_flush(300);
7626 if (!defined('RESTORE_SILENTLY')) {
7627 //Now print information gathered
7628 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
7629 echo "<ul>";
7630 echo "<li>".get_string("students").": ".$student_count.'</li>';
7631 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
7632 echo "</ul>";
7634 } else {
7635 if (!defined('RESTORE_SILENTLY')) {
7636 notify("No users were found!");
7637 } // no need to return false here, it's recoverable.
7641 if (!defined('RESTORE_SILENTLY')) {
7642 echo "</li>";
7647 //Now create groups as needed
7648 if ($status and ($restore->groups == RESTORE_GROUPS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) {
7649 if (!defined('RESTORE_SILENTLY')) {
7650 echo "<li>".get_string("creatinggroups");
7652 if (!$status = restore_create_groups($restore,$xml_file)) {
7653 if (!defined('RESTORE_SILENTLY')) {
7654 notify("Could not restore groups!");
7655 } else {
7656 $errorstr = "Could not restore groups!";
7657 return false;
7660 if (!defined('RESTORE_SILENTLY')) {
7661 echo '</li>';
7665 //Now create groupings as needed
7666 if ($status and ($restore->groups == RESTORE_GROUPINGS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) {
7667 if (!defined('RESTORE_SILENTLY')) {
7668 echo "<li>".get_string("creatinggroupings");
7670 if (!$status = restore_create_groupings($restore,$xml_file)) {
7671 if (!defined('RESTORE_SILENTLY')) {
7672 notify("Could not restore groupings!");
7673 } else {
7674 $errorstr = "Could not restore groupings!";
7675 return false;
7678 if (!defined('RESTORE_SILENTLY')) {
7679 echo '</li>';
7683 //Now create groupingsgroups as needed
7684 if ($status and $restore->groups == RESTORE_GROUPS_GROUPINGS) {
7685 if (!defined('RESTORE_SILENTLY')) {
7686 echo "<li>".get_string("creatinggroupingsgroups");
7688 if (!$status = restore_create_groupings_groups($restore,$xml_file)) {
7689 if (!defined('RESTORE_SILENTLY')) {
7690 notify("Could not restore groups in groupings!");
7691 } else {
7692 $errorstr = "Could not restore groups in groupings!";
7693 return false;
7696 if (!defined('RESTORE_SILENTLY')) {
7697 echo '</li>';
7702 //Now create the course_sections and their associated course_modules
7703 //we have to do this after groups and groupings are restored, because we need the new groupings id
7704 if ($status) {
7705 //Into new course
7706 if ($restore->restoreto == 2) {
7707 if (!defined('RESTORE_SILENTLY')) {
7708 echo "<li>".get_string("creatingsections");
7710 if (!$status = restore_create_sections($restore,$xml_file)) {
7711 if (!defined('RESTORE_SILENTLY')) {
7712 notify("Error creating sections in the existing course.");
7713 } else {
7714 $errorstr = "Error creating sections in the existing course.";
7715 return false;
7718 if (!defined('RESTORE_SILENTLY')) {
7719 echo '</li>';
7721 //Into existing course
7722 } else if ($restore->restoreto == 0 or $restore->restoreto == 1) {
7723 if (!defined('RESTORE_SILENTLY')) {
7724 echo "<li>".get_string("checkingsections");
7726 if (!$status = restore_create_sections($restore,$xml_file)) {
7727 if (!defined('RESTORE_SILENTLY')) {
7728 notify("Error creating sections in the existing course.");
7729 } else {
7730 $errorstr = "Error creating sections in the existing course.";
7731 return false;
7734 if (!defined('RESTORE_SILENTLY')) {
7735 echo '</li>';
7737 //Error
7738 } else {
7739 if (!defined('RESTORE_SILENTLY')) {
7740 notify("Neither a new course or an existing one was specified.");
7741 $status = false;
7742 } else {
7743 $errorstr = "Neither a new course or an existing one was specified.";
7744 return false;
7749 //Now create metacourse info
7750 if ($status and $restore->metacourse) {
7751 //Only to new courses!
7752 if ($restore->restoreto == 2) {
7753 if (!defined('RESTORE_SILENTLY')) {
7754 echo "<li>".get_string("creatingmetacoursedata");
7756 if (!$status = restore_create_metacourse($restore,$xml_file)) {
7757 if (!defined('RESTORE_SILENTLY')) {
7758 notify("Error creating metacourse in the course.");
7759 } else {
7760 $errorstr = "Error creating metacourse in the course.";
7761 return false;
7764 if (!defined('RESTORE_SILENTLY')) {
7765 echo '</li>';
7771 //Now create categories and questions as needed
7772 if ($status) {
7773 include_once("$CFG->dirroot/question/restorelib.php");
7774 if (!defined('RESTORE_SILENTLY')) {
7775 echo "<li>".get_string("creatingcategoriesandquestions");
7776 echo "<ul>";
7778 if (!$status = restore_create_questions($restore,$xml_file)) {
7779 if (!defined('RESTORE_SILENTLY')) {
7780 notify("Could not restore categories and questions!");
7781 } else {
7782 $errorstr = "Could not restore categories and questions!";
7783 return false;
7786 if (!defined('RESTORE_SILENTLY')) {
7787 echo "</ul></li>";
7791 //Now create user_files as needed
7792 if ($status and ($restore->user_files)) {
7793 if (!defined('RESTORE_SILENTLY')) {
7794 echo "<li>".get_string("copyinguserfiles");
7796 if (!$status = restore_user_files($restore)) {
7797 if (!defined('RESTORE_SILENTLY')) {
7798 notify("Could not restore user files!");
7799 } else {
7800 $errorstr = "Could not restore user files!";
7801 return false;
7804 //If all is ok (and we have a counter)
7805 if ($status and ($status !== true)) {
7806 //Inform about user dirs created from backup
7807 if (!defined('RESTORE_SILENTLY')) {
7808 echo "<ul>";
7809 echo "<li>".get_string("userzones").": ".$status;
7810 echo "</li></ul>";
7813 if (!defined('RESTORE_SILENTLY')) {
7814 echo '</li>';
7818 //Now create course files as needed
7819 if ($status and ($restore->course_files)) {
7820 if (!defined('RESTORE_SILENTLY')) {
7821 echo "<li>".get_string("copyingcoursefiles");
7823 if (!$status = restore_course_files($restore)) {
7824 if (empty($status)) {
7825 notify("Could not restore course files!");
7826 } else {
7827 $errorstr = "Could not restore course files!";
7828 return false;
7831 //If all is ok (and we have a counter)
7832 if ($status and ($status !== true)) {
7833 //Inform about user dirs created from backup
7834 if (!defined('RESTORE_SILENTLY')) {
7835 echo "<ul>";
7836 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7837 echo "</ul>";
7840 if (!defined('RESTORE_SILENTLY')) {
7841 echo "</li>";
7846 //Now create site files as needed
7847 if ($status and ($restore->site_files)) {
7848 if (!defined('RESTORE_SILENTLY')) {
7849 echo "<li>".get_string('copyingsitefiles');
7851 if (!$status = restore_site_files($restore)) {
7852 if (empty($status)) {
7853 notify("Could not restore site files!");
7854 } else {
7855 $errorstr = "Could not restore site files!";
7856 return false;
7859 //If all is ok (and we have a counter)
7860 if ($status and ($status !== true)) {
7861 //Inform about user dirs created from backup
7862 if (!defined('RESTORE_SILENTLY')) {
7863 echo "<ul>";
7864 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7865 echo "</ul>";
7868 if (!defined('RESTORE_SILENTLY')) {
7869 echo "</li>";
7873 //Now create messages as needed
7874 if ($status and ($restore->messages)) {
7875 if (!defined('RESTORE_SILENTLY')) {
7876 echo "<li>".get_string("creatingmessagesinfo");
7878 if (!$status = restore_create_messages($restore,$xml_file)) {
7879 if (!defined('RESTORE_SILENTLY')) {
7880 notify("Could not restore messages!");
7881 } else {
7882 $errorstr = "Could not restore messages!";
7883 return false;
7886 if (!defined('RESTORE_SILENTLY')) {
7887 echo "</li>";
7891 //Now create blogs as needed
7892 if ($status and ($restore->blogs)) {
7893 if (!defined('RESTORE_SILENTLY')) {
7894 echo "<li>".get_string("creatingblogsinfo");
7896 if (!$status = restore_create_blogs($restore,$xml_file)) {
7897 if (!defined('RESTORE_SILENTLY')) {
7898 notify("Could not restore blogs!");
7899 } else {
7900 $errorstr = "Could not restore blogs!";
7901 return false;
7904 if (!defined('RESTORE_SILENTLY')) {
7905 echo "</li>";
7909 //Now create scales as needed
7910 if ($status) {
7911 if (!defined('RESTORE_SILENTLY')) {
7912 echo "<li>".get_string("creatingscales");
7914 if (!$status = restore_create_scales($restore,$xml_file)) {
7915 if (!defined('RESTORE_SILENTLY')) {
7916 notify("Could not restore custom scales!");
7917 } else {
7918 $errorstr = "Could not restore custom scales!";
7919 return false;
7922 if (!defined('RESTORE_SILENTLY')) {
7923 echo '</li>';
7927 //Now create events as needed
7928 if ($status) {
7929 if (!defined('RESTORE_SILENTLY')) {
7930 echo "<li>".get_string("creatingevents");
7932 if (!$status = restore_create_events($restore,$xml_file)) {
7933 if (!defined('RESTORE_SILENTLY')) {
7934 notify("Could not restore course events!");
7935 } else {
7936 $errorstr = "Could not restore course events!";
7937 return false;
7940 if (!defined('RESTORE_SILENTLY')) {
7941 echo '</li>';
7945 //Now create course modules as needed
7946 if ($status) {
7947 if (!defined('RESTORE_SILENTLY')) {
7948 echo "<li>".get_string("creatingcoursemodules");
7950 if (!$status = restore_create_modules($restore,$xml_file)) {
7951 if (!defined('RESTORE_SILENTLY')) {
7952 notify("Could not restore modules!");
7953 } else {
7954 $errorstr = "Could not restore modules!";
7955 return false;
7958 if (!defined('RESTORE_SILENTLY')) {
7959 echo '</li>';
7963 //Bring back the course blocks -- do it AFTER the modules!!!
7964 if($status) {
7965 //If we are deleting and bringing into a course or making a new course, same situation
7966 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7967 if (!defined('RESTORE_SILENTLY')) {
7968 echo '<li>'.get_string('creatingblocks');
7970 $course_header->blockinfo = !empty($course_header->blockinfo) ? $course_header->blockinfo : NULL;
7971 if (!$status = restore_create_blocks($restore, $info->backup_block_format, $course_header->blockinfo, $xml_file)) {
7972 if (!defined('RESTORE_SILENTLY')) {
7973 notify('Error while creating the course blocks');
7974 } else {
7975 $errorstr = "Error while creating the course blocks";
7976 return false;
7979 if (!defined('RESTORE_SILENTLY')) {
7980 echo '</li>';
7985 if($status) {
7986 //If we are deleting and bringing into a course or making a new course, same situation
7987 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7988 if (!defined('RESTORE_SILENTLY')) {
7989 echo '<li>'.get_string('courseformatdata');
7991 if (!$status = restore_set_format_data($restore, $xml_file)) {
7992 $error = "Error while setting the course format data";
7993 if (!defined('RESTORE_SILENTLY')) {
7994 notify($error);
7995 } else {
7996 $errorstr=$error;
7997 return false;
8000 if (!defined('RESTORE_SILENTLY')) {
8001 echo '</li>';
8006 //Now create log entries as needed
8007 if ($status and ($restore->logs)) {
8008 if (!defined('RESTORE_SILENTLY')) {
8009 echo "<li>".get_string("creatinglogentries");
8011 if (!$status = restore_create_logs($restore,$xml_file)) {
8012 if (!defined('RESTORE_SILENTLY')) {
8013 notify("Could not restore logs!");
8014 } else {
8015 $errorstr = "Could not restore logs!";
8016 return false;
8019 if (!defined('RESTORE_SILENTLY')) {
8020 echo '</li>';
8024 //Now, if all is OK, adjust the instance field in course_modules !!
8025 //this also calculates the final modinfo information so, after this,
8026 //code needing it can be used (like role_assignments. MDL-13740)
8027 if ($status) {
8028 if (!defined('RESTORE_SILENTLY')) {
8029 echo "<li>".get_string("checkinginstances");
8031 if (!$status = restore_check_instances($restore)) {
8032 if (!defined('RESTORE_SILENTLY')) {
8033 notify("Could not adjust instances in course_modules!");
8034 } else {
8035 $errorstr = "Could not adjust instances in course_modules!";
8036 return false;
8039 if (!defined('RESTORE_SILENTLY')) {
8040 echo '</li>';
8044 //Now, if all is OK, adjust activity events
8045 if ($status) {
8046 if (!defined('RESTORE_SILENTLY')) {
8047 echo "<li>".get_string("refreshingevents");
8049 if (!$status = restore_refresh_events($restore)) {
8050 if (!defined('RESTORE_SILENTLY')) {
8051 notify("Could not refresh events for activities!");
8052 } else {
8053 $errorstr = "Could not refresh events for activities!";
8054 return false;
8057 if (!defined('RESTORE_SILENTLY')) {
8058 echo '</li>';
8062 //Now, if all is OK, adjust inter-activity links
8063 if ($status) {
8064 if (!defined('RESTORE_SILENTLY')) {
8065 echo "<li>".get_string("decodinginternallinks");
8067 if (!$status = restore_decode_content_links($restore)) {
8068 if (!defined('RESTORE_SILENTLY')) {
8069 notify("Could not decode content links!");
8070 } else {
8071 $errorstr = "Could not decode content links!";
8072 return false;
8075 if (!defined('RESTORE_SILENTLY')) {
8076 echo '</li>';
8080 //Now, with backup files prior to version 2005041100,
8081 //convert all the wiki texts in the course to markdown
8082 if ($status && $restore->backup_version < 2005041100) {
8083 if (!defined('RESTORE_SILENTLY')) {
8084 echo "<li>".get_string("convertingwikitomarkdown");
8086 if (!$status = restore_convert_wiki2markdown($restore)) {
8087 if (!defined('RESTORE_SILENTLY')) {
8088 notify("Could not convert wiki texts to markdown!");
8089 } else {
8090 $errorstr = "Could not convert wiki texts to markdown!";
8091 return false;
8094 if (!defined('RESTORE_SILENTLY')) {
8095 echo '</li>';
8099 //Now create gradebook as needed -- AFTER modules and blocks!!!
8100 if ($status) {
8101 if ($restore->backup_version > 2007090500) {
8102 if (!defined('RESTORE_SILENTLY')) {
8103 echo "<li>".get_string("creatinggradebook");
8105 if (!$status = restore_create_gradebook($restore,$xml_file)) {
8106 if (!defined('RESTORE_SILENTLY')) {
8107 notify("Could not restore gradebook!");
8108 } else {
8109 $errorstr = "Could not restore gradebook!";
8110 return false;
8114 if (!defined('RESTORE_SILENTLY')) {
8115 echo '</li>';
8118 } else {
8119 // for moodle versions before 1.9, those grades need to be converted to use the new gradebook
8120 // this code needs to execute *after* the course_modules are sorted out
8121 if (!defined('RESTORE_SILENTLY')) {
8122 echo "<li>".get_string("migratinggrades");
8125 /// force full refresh of grading data before migration == crete all items first
8126 if (!$status = restore_migrate_old_gradebook($restore,$xml_file)) {
8127 if (!defined('RESTORE_SILENTLY')) {
8128 notify("Could not migrate gradebook!");
8129 } else {
8130 $errorstr = "Could not migrade gradebook!";
8131 return false;
8134 if (!defined('RESTORE_SILENTLY')) {
8135 echo '</li>';
8138 /// force full refresh of grading data after all items are created
8139 grade_force_full_regrading($restore->course_id);
8140 grade_grab_course_grades($restore->course_id);
8143 /*******************************************************************************
8144 ************* Restore of Roles and Capabilities happens here ******************
8145 *******************************************************************************/
8146 // try to restore roles even when restore is going to fail - teachers might have
8147 // at least some role assigned - this is not correct though
8148 $status = restore_create_roles($restore, $xml_file) && $status;
8149 $status = restore_roles_settings($restore, $xml_file) && $status;
8151 //Now if all is OK, update:
8152 // - course modinfo field
8153 // - categories table
8154 // - add user as teacher
8155 if ($status) {
8156 if (!defined('RESTORE_SILENTLY')) {
8157 echo "<li>".get_string("checkingcourse");
8159 //categories table
8160 $course = get_record("course","id",$restore->course_id);
8161 fix_course_sortorder();
8162 // Check if the user has course update capability in the newly restored course
8163 // there is no need to load his capabilities again, because restore_roles_settings
8164 // would have loaded it anyway, if there is any assignments.
8165 // fix for MDL-6831
8166 $newcontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
8167 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
8168 // fix for MDL-9065, use the new config setting if exists
8169 if ($CFG->creatornewroleid) {
8170 role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id);
8171 } else {
8172 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM))) {
8173 if ($legacyteacher = array_shift($legacyteachers)) {
8174 role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id);
8176 } else {
8177 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
8181 if (!defined('RESTORE_SILENTLY')) {
8182 echo '</li>';
8186 //Cleanup temps (files and db)
8187 if ($status) {
8188 if (!defined('RESTORE_SILENTLY')) {
8189 echo "<li>".get_string("cleaningtempdata");
8191 if (!$status = clean_temp_data ($restore)) {
8192 if (!defined('RESTORE_SILENTLY')) {
8193 notify("Could not clean up temporary data from files and database");
8194 } else {
8195 $errorstr = "Could not clean up temporary data from files and database";
8196 return false;
8199 if (!defined('RESTORE_SILENTLY')) {
8200 echo '</li>';
8204 // this is not a critical check - the result can be ignored
8205 if (restore_close_html($restore)){
8206 if (!defined('RESTORE_SILENTLY')) {
8207 echo '<li>Closing the Restorelog.html file.</li>';
8210 else {
8211 if (!defined('RESTORE_SILENTLY')) {
8212 notify("Could not close the restorelog.html file");
8216 if (!defined('RESTORE_SILENTLY')) {
8217 //End the main ul
8218 echo "</ul>";
8220 //End the main table
8221 echo "</td></tr>";
8222 echo "</table>";
8225 return $status;
8227 //Create, open and write header of the html log file
8228 function restore_open_html($restore,$course_header) {
8230 global $CFG;
8232 $status = true;
8234 //Open file for writing
8235 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
8236 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
8237 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
8239 $status = check_dir_exists($dest_dir,true);
8240 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8241 //Add the stylesheet
8242 $stylesheetshtml = '';
8243 foreach ($CFG->stylesheets as $stylesheet) {
8244 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
8246 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
8247 $languagehtml = get_html_lang($dir=true);
8249 //Write the header in the new logging file
8250 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
8251 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
8252 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
8253 fwrite ($restorelog_file,"<head>");
8254 fwrite ($restorelog_file,$stylesheetshtml);
8255 fwrite ($restorelog_file,"<title>".$course_header->course_shortname." Restored </title>");
8256 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
8257 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname." The FullName is now - ".$course_header->course_fullname."<br/><br/>");
8258 $startdate = addslashes($course_header->course_startdate);
8259 $date = usergetdate($startdate);
8260 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
8261 $startdate += $restore->course_startdateoffset;
8262 $date = usergetdate($startdate);
8263 fwrite ($restorelog_file,"&nbsp;&nbsp;&nbsp;This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
8265 if ($status) {
8266 return $restorelog_file;
8267 } else {
8268 return false;
8271 //Create & close footer of the html log file
8272 function restore_close_html($restore) {
8274 global $CFG;
8276 $status = true;
8278 //Open file for writing
8279 //First, check that course_id/backupdata folder exists in CFG->dataroot
8280 $dest_dir = $CFG->dataroot."/".$restore->course_id."/backupdata";
8281 $status = check_dir_exists($dest_dir, true, true);
8282 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8283 //Write the footer to close the logging file
8284 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
8285 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
8287 if ($status) {
8288 return $restorelog_file;
8289 } else {
8290 return false;
8294 /********************** Roles and Capabilities Related Functions *******************************/
8296 /* Yu: Note recovering of role assignments/overrides need to take place after
8297 users have been recovered, i.e. after we get their new_id, and after all
8298 roles have been recreated or mapped. Contexts can be created on the fly.
8299 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
8300 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
8301 once roles and users have been restored.
8305 * This function restores all the needed roles for this course
8306 * i.e. roles with an assignment in any of the mods or blocks,
8307 * roles assigned on any user (e.g. parent role) and roles
8308 * assigned at course levle
8309 * This function should check for duplicate roles first
8310 * It isn't now, just overwriting
8312 function restore_create_roles($restore, $xmlfile) {
8313 if (!defined('RESTORE_SILENTLY')) {
8314 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
8316 $info = restore_read_xml_roles($xmlfile);
8318 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
8320 // the following code creates new roles
8321 // but we could use more intelligent detection, and role mapping
8322 // get role mapping info from $restore
8323 $rolemappings = array();
8325 if (!empty($restore->rolesmapping)) {
8326 $rolemappings = $restore->rolesmapping;
8328 // $info->roles will be empty for backups pre 1.7
8329 if (isset($info->roles) && $info->roles) {
8331 foreach ($info->roles as $oldroleid=>$roledata) {
8333 if (empty($restore->rolesmapping)) {
8334 // if this is empty altogether, we came from import or there's no roles used in course at all
8335 // in this case, write the same oldid as this is the same site
8336 // no need to do mapping
8337 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
8338 $oldroleid); // adding a new id
8339 continue; // do not create additonal roles;
8341 // first we check if the roles are in the mappings
8342 // if so, we just do a mapping i.e. update oldids table
8343 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
8344 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
8345 $rolemappings[$oldroleid]); // adding a new id
8347 } else {
8349 // code to make new role name/short name if same role name or shortname exists
8350 $fullname = $roledata->name;
8351 $shortname = $roledata->shortname;
8352 $currentfullname = "";
8353 $currentshortname = "";
8354 $counter = 0;
8356 do {
8357 if ($counter) {
8358 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
8359 $suffixshort = "_".$counter;
8360 } else {
8361 $suffixfull = "";
8362 $suffixshort = "";
8364 $currentfullname = $fullname.$suffixfull;
8365 // Limit the size of shortname - database column accepts <= 100 chars
8366 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
8367 $coursefull = get_record("role","name",addslashes($currentfullname));
8368 $courseshort = get_record("role","shortname",addslashes($currentshortname));
8369 $counter++;
8370 } while ($coursefull || $courseshort);
8372 $roledata->name = $currentfullname;
8373 $roledata->shortname= $currentshortname;
8375 // done finding a unique name
8377 $newroleid = create_role(addslashes($roledata->name),addslashes($roledata->shortname),'');
8378 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
8379 $newroleid); // adding a new id
8380 foreach ($roledata->capabilities as $capability) {
8382 $roleinfo = new object();
8383 $roleinfo = (object)$capability;
8384 $roleinfo->contextid = $sitecontext->id;
8385 $roleinfo->capability = $capability->name;
8386 $roleinfo->roleid = $newroleid;
8388 insert_record('role_capabilities', $roleinfo);
8391 /// Now, restore role nameincourse (only if the role had nameincourse in backup)
8392 if (!empty($roledata->nameincourse)) {
8393 $newrole = backup_getid($restore->backup_unique_code, 'role', $oldroleid); /// Look for target role
8394 $coursecontext = get_context_instance(CONTEXT_COURSE, $restore->course_id); /// Look for target context
8395 if (!empty($newrole->new_id) && !empty($coursecontext)) {
8396 /// Check the role hasn't any custom name in context
8397 if (!record_exists('role_names', 'roleid', $newrole->new_id, 'contextid', $coursecontext->id)) {
8398 $rolename = new object();
8399 $rolename->roleid = $newrole->new_id;
8400 $rolename->contextid = $coursecontext->id;
8401 $rolename->name = addslashes($roledata->nameincourse);
8403 insert_record('role_names', $rolename);
8409 return true;
8413 * this function restores role assignments and role overrides
8414 * in course/user/block/mod level, it passed through
8415 * the xml file again
8417 function restore_roles_settings($restore, $xmlfile) {
8418 // data pulls from course, mod, user, and blocks
8420 /*******************************************************
8421 * Restoring from course level assignments *
8422 *******************************************************/
8423 if (!defined('RESTORE_SILENTLY')) {
8424 echo "<li>".get_string("creatingcourseroles").'</li>';
8426 $course = restore_read_xml_course_header($xmlfile);
8428 if (!isset($restore->rolesmapping)) {
8429 $isimport = true; // course import from another course, or course with no role assignments
8430 } else {
8431 $isimport = false; // course restore with role assignments
8434 if (!empty($course->roleassignments) && !$isimport) {
8435 $courseassignments = $course->roleassignments;
8437 foreach ($courseassignments as $oldroleid => $courseassignment) {
8438 restore_write_roleassignments($restore, $courseassignment->assignments, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
8441 /*****************************************************
8442 * Restoring from course level overrides *
8443 *****************************************************/
8445 if (!empty($course->roleoverrides) && !$isimport) {
8446 $courseoverrides = $course->roleoverrides;
8447 foreach ($courseoverrides as $oldroleid => $courseoverride) {
8448 // if not importing into exiting course, or creating new role, we are ok
8449 // local course overrides to be respected (i.e. restored course overrides ignored)
8450 if ($restore->restoreto != 1 || empty($restore->rolesmapping[$oldroleid])) {
8451 restore_write_roleoverrides($restore, $courseoverride->overrides, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
8456 /*******************************************************
8457 * Restoring role assignments/overrdies *
8458 * from module level assignments *
8459 *******************************************************/
8461 if (!defined('RESTORE_SILENTLY')) {
8462 echo "<li>".get_string("creatingmodroles").'</li>';
8464 $sections = restore_read_xml_sections($xmlfile);
8465 $secs = $sections->sections;
8467 foreach ($secs as $section) {
8468 if (isset($section->mods)) {
8469 foreach ($section->mods as $modid=>$mod) {
8470 if (isset($mod->roleassignments) && !$isimport) {
8471 foreach ($mod->roleassignments as $oldroleid=>$modassignment) {
8472 restore_write_roleassignments($restore, $modassignment->assignments, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
8475 // role overrides always applies, in import or backup/restore
8476 if (isset($mod->roleoverrides)) {
8477 foreach ($mod->roleoverrides as $oldroleid=>$modoverride) {
8478 restore_write_roleoverrides($restore, $modoverride->overrides, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
8485 /*************************************************
8486 * Restoring assignments from blocks level *
8487 * role assignments/overrides *
8488 *************************************************/
8490 if ($restore->restoreto != 1) { // skip altogether if restoring to exisitng course by adding
8491 if (!defined('RESTORE_SILENTLY')) {
8492 echo "<li>".get_string("creatingblocksroles").'</li>';
8494 $blocks = restore_read_xml_blocks($restore, $xmlfile);
8495 if (isset($blocks->instances)) {
8496 foreach ($blocks->instances as $instance) {
8497 if (isset($instance->roleassignments) && !$isimport) {
8498 foreach ($instance->roleassignments as $oldroleid=>$blockassignment) {
8499 restore_write_roleassignments($restore, $blockassignment->assignments, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
8503 // likewise block overrides should always be restored like mods
8504 if (isset($instance->roleoverrides)) {
8505 foreach ($instance->roleoverrides as $oldroleid=>$blockoverride) {
8506 restore_write_roleoverrides($restore, $blockoverride->overrides, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
8512 /************************************************
8513 * Restoring assignments from userid level *
8514 * role assignments/overrides *
8515 ************************************************/
8516 if (!defined('RESTORE_SILENTLY')) {
8517 echo "<li>".get_string("creatinguserroles").'</li>';
8519 $info = restore_read_xml_users($restore, $xmlfile);
8520 if (!empty($info->users) && !$isimport) { // no need to restore user assignments for imports (same course)
8521 //For each user, take its info from backup_ids
8522 foreach ($info->users as $userid) {
8523 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
8524 if (isset($rec->info->roleassignments)) {
8525 foreach ($rec->info->roleassignments as $oldroleid=>$userassignment) {
8526 restore_write_roleassignments($restore, $userassignment->assignments, "user", CONTEXT_USER, $userid, $oldroleid);
8529 if (isset($rec->info->roleoverrides)) {
8530 foreach ($rec->info->roleoverrides as $oldroleid=>$useroverride) {
8531 restore_write_roleoverrides($restore, $useroverride->overrides, "user", CONTEXT_USER, $userid, $oldroleid);
8537 return true;
8540 // auxillary function to write role assignments read from xml to db
8541 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
8543 $role = backup_getid($restore->backup_unique_code, "role", $oldroleid);
8545 foreach ($assignments as $assignment) {
8547 $olduser = backup_getid($restore->backup_unique_code,"user",$assignment->userid);
8548 //Oh dear, $olduser... can be an object, $obj->string or bool!
8549 if (!$olduser || (is_string($olduser->info) && $olduser->info == "notincourse")) { // it's possible that user is not in the course
8550 continue;
8552 $assignment->userid = $olduser->new_id; // new userid here
8553 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$assignment->modifierid);
8554 $assignment->modifierid = !empty($oldmodifier->new_id) ? $oldmodifier->new_id : 0; // new modifier id here
8555 $assignment->roleid = $role->new_id; // restored new role id
8557 // hack to make the correct contextid for course level imports
8558 if ($contextlevel == CONTEXT_COURSE) {
8559 $oldinstance->new_id = $restore->course_id;
8560 } else {
8561 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
8564 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
8565 $assignment->contextid = $newcontext->id; // new context id
8566 // might already have same assignment
8567 role_assign($assignment->roleid, $assignment->userid, 0, $assignment->contextid, $assignment->timestart, $assignment->timeend, $assignment->hidden, $assignment->enrol, $assignment->timemodified);
8572 // auxillary function to write role assignments read from xml to db
8573 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
8575 // it is possible to have an override not relevant to this course context.
8576 // should be ignored(?)
8577 if (!$role = backup_getid($restore->backup_unique_code, "role", $oldroleid)) {
8578 return null;
8581 foreach ($overrides as $override) {
8582 $override->capability = $override->name;
8583 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$override->modifierid);
8584 $override->modifierid = !empty($oldmodifier->new_id)?$oldmodifier->new_id:0; // new modifier id here
8585 $override->roleid = $role->new_id; // restored new role id
8587 // hack to make the correct contextid for course level imports
8588 if ($contextlevel == CONTEXT_COURSE) {
8589 $oldinstance->new_id = $restore->course_id;
8590 } else {
8591 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
8594 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
8595 $override->contextid = $newcontext->id; // new context id
8596 // use assign capability instead so we can add context to context_rel
8597 assign_capability($override->capability, $override->permission, $override->roleid, $override->contextid);
8600 //write activity date changes to the html log file, and update date values in the the xml array
8601 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
8603 global $CFG;
8604 $openlog = false;
8606 // loop through time fields in $TAGS
8607 foreach ($TAGS as $TAG) {
8609 // check $TAG has a sensible value
8610 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
8612 if ($openlog==false) {
8613 $openlog = true; // only come through here once
8615 // open file for writing
8616 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
8617 check_dir_exists($course_dir, true);
8618 $restorelog = fopen("$course_dir/restorelog.html", "a");
8620 // start output for this record
8621 $msg = new stdClass();
8622 $msg->recordtype = $recordtype;
8623 $msg->recordname = $xml[$NAMETAG][0]['#'];
8624 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
8627 // write old date to $restorelog
8628 $value = $xml[$TAG][0]['#'];
8629 $date = usergetdate($value);
8631 $msg = new stdClass();
8632 $msg->TAG = $TAG;
8633 $msg->weekday = $date['weekday'];
8634 $msg->mday = $date['mday'];
8635 $msg->month = $date['month'];
8636 $msg->year = $date['year'];
8637 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
8639 // write new date to $restorelog
8640 $value += $restore->course_startdateoffset;
8641 $date = usergetdate($value);
8643 $msg = new stdClass();
8644 $msg->TAG = $TAG;
8645 $msg->weekday = $date['weekday'];
8646 $msg->mday = $date['mday'];
8647 $msg->month = $date['month'];
8648 $msg->year = $date['year'];
8649 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
8651 // update $value in $xml tree for calling module
8652 $xml[$TAG][0]['#'] = "$value";
8655 // close the restore log, if it was opened
8656 if ($openlog) {
8657 fclose($restorelog);