Added LinuxChix theme
[moodle-linuxchix.git] / backup / restorelib.php
blob86ac29a077598fa9c6fff2c5d878e91b5ceeb88e
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 if (!empty($CFG->showblocksonmodpages)) {
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 presetn 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;
4409 /// Finally, calculate modinfo cache.
4410 rebuild_course_cache($restore->course_id);
4414 return $status;
4417 //=====================================================================================
4418 //== ==
4419 //== XML Functions (SAX) ==
4420 //== ==
4421 //=====================================================================================
4423 //This is the class used to do all the xml parse
4424 class MoodleParser {
4426 var $level = 0; //Level we are
4427 var $counter = 0; //Counter
4428 var $tree = array(); //Array of levels we are
4429 var $content = ""; //Content under current level
4430 var $todo = ""; //What we hav to do when parsing
4431 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
4432 var $temp = ""; //Temp storage.
4433 var $preferences = ""; //Preferences about what to load !!
4434 var $finished = false; //Flag to say xml_parse to stop
4436 //This function is used to get the current contents property value
4437 //They are trimed (and converted from utf8 if needed)
4438 function getContents() {
4439 return trim($this->content);
4442 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4443 function startElementInfo($parser, $tagName, $attrs) {
4444 //Refresh properties
4445 $this->level++;
4446 $this->tree[$this->level] = $tagName;
4448 //Output something to avoid browser timeouts...
4449 //backup_flush();
4451 //Check if we are into INFO zone
4452 //if ($this->tree[2] == "INFO") //Debug
4453 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4456 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4457 function startElementRoles($parser, $tagName, $attrs) {
4458 //Refresh properties
4459 $this->level++;
4460 $this->tree[$this->level] = $tagName;
4462 //Output something to avoid browser timeouts...
4463 //backup_flush();
4465 //Check if we are into INFO zone
4466 //if ($this->tree[2] == "INFO") //Debug
4467 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4471 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
4472 function startElementCourseHeader($parser, $tagName, $attrs) {
4473 //Refresh properties
4474 $this->level++;
4475 $this->tree[$this->level] = $tagName;
4477 //Output something to avoid browser timeouts...
4478 //backup_flush();
4480 //Check if we are into COURSE_HEADER zone
4481 //if ($this->tree[3] == "HEADER") //Debug
4482 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4485 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
4486 function startElementBlocks($parser, $tagName, $attrs) {
4487 //Refresh properties
4488 $this->level++;
4489 $this->tree[$this->level] = $tagName;
4491 //Output something to avoid browser timeouts...
4492 //backup_flush();
4494 //Check if we are into BLOCKS zone
4495 //if ($this->tree[3] == "BLOCKS") //Debug
4496 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4498 //If we are under a BLOCK tag under a BLOCKS zone, accumule it
4499 if (isset($this->tree[4]) and isset($this->tree[3])) { //
4500 if ($this->tree[4] == "BLOCK" and $this->tree[3] == "BLOCKS") {
4501 if (!isset($this->temp)) {
4502 $this->temp = "";
4504 $this->temp .= "<".$tagName.">";
4509 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
4510 function startElementSections($parser, $tagName, $attrs) {
4511 //Refresh properties
4512 $this->level++;
4513 $this->tree[$this->level] = $tagName;
4515 //Output something to avoid browser timeouts...
4516 //backup_flush();
4518 //Check if we are into SECTIONS zone
4519 //if ($this->tree[3] == "SECTIONS") //Debug
4520 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4523 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4524 function startElementFormatData($parser, $tagName, $attrs) {
4525 //Refresh properties
4526 $this->level++;
4527 $this->tree[$this->level] = $tagName;
4529 //Output something to avoid browser timeouts...
4530 //backup_flush();
4532 //Accumulate all the data inside this tag
4533 if (isset($this->tree[3]) && $this->tree[3] == "FORMATDATA") {
4534 if (!isset($this->temp)) {
4535 $this->temp = '';
4537 $this->temp .= "<".$tagName.">";
4540 //Check if we are into FORMATDATA zone
4541 //if ($this->tree[3] == "FORMATDATA") //Debug
4542 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4545 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4546 function startElementMetacourse($parser, $tagName, $attrs) {
4548 //Refresh properties
4549 $this->level++;
4550 $this->tree[$this->level] = $tagName;
4552 //Output something to avoid browser timeouts...
4553 //backup_flush();
4555 //Check if we are into METACOURSE zone
4556 //if ($this->tree[3] == "METACOURSE") //Debug
4557 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4560 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4561 function startElementGradebook($parser, $tagName, $attrs) {
4563 //Refresh properties
4564 $this->level++;
4565 $this->tree[$this->level] = $tagName;
4567 //Output something to avoid browser timeouts...
4568 //backup_flush();
4570 //Check if we are into GRADEBOOK zone
4571 //if ($this->tree[3] == "GRADEBOOK") //Debug
4572 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4574 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4575 if (isset($this->tree[5]) and isset($this->tree[3])) {
4576 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")) {
4578 if (!isset($this->temp)) {
4579 $this->temp = "";
4581 $this->temp .= "<".$tagName.">";
4586 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4587 function startElementOldGradebook($parser, $tagName, $attrs) {
4589 //Refresh properties
4590 $this->level++;
4591 $this->tree[$this->level] = $tagName;
4593 //Output something to avoid browser timeouts...
4594 //backup_flush();
4596 //Check if we are into GRADEBOOK zone
4597 //if ($this->tree[3] == "GRADEBOOK") //Debug
4598 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4600 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4601 if (isset($this->tree[5]) and isset($this->tree[3])) {
4602 if (($this->tree[5] == "GRADE_PREFERENCE" || $this->tree[5] == "GRADE_LETTER" || $this->tree[5] == "GRADE_CATEGORY" ) && ($this->tree[3] == "GRADEBOOK")) {
4603 if (!isset($this->temp)) {
4604 $this->temp = "";
4606 $this->temp .= "<".$tagName.">";
4612 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
4613 function startElementUsers($parser, $tagName, $attrs) {
4614 //Refresh properties
4615 $this->level++;
4616 $this->tree[$this->level] = $tagName;
4618 //Check if we are into USERS zone
4619 //if ($this->tree[3] == "USERS") //Debug
4620 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4623 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
4624 function startElementMessages($parser, $tagName, $attrs) {
4625 //Refresh properties
4626 $this->level++;
4627 $this->tree[$this->level] = $tagName;
4629 //Output something to avoid browser timeouts...
4630 //backup_flush();
4632 //Check if we are into MESSAGES zone
4633 //if ($this->tree[3] == "MESSAGES") //Debug
4634 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4636 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
4637 if (isset($this->tree[4]) and isset($this->tree[3])) {
4638 if (($this->tree[4] == "MESSAGE" || (isset($this->tree[5]) && $this->tree[5] == "CONTACT" )) and ($this->tree[3] == "MESSAGES")) {
4639 if (!isset($this->temp)) {
4640 $this->temp = "";
4642 $this->temp .= "<".$tagName.">";
4647 //This is the startTag handler we use where we are reading the blogs zone (todo="BLOGS")
4648 function startElementBlogs($parser, $tagName, $attrs) {
4649 //Refresh properties
4650 $this->level++;
4651 $this->tree[$this->level] = $tagName;
4653 //Output something to avoid browser timeouts...
4654 //backup_flush();
4656 //Check if we are into BLOGS zone
4657 //if ($this->tree[3] == "BLOGS") //Debug
4658 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4660 //If we are under a BLOG tag under a BLOGS zone, accumule it
4661 if (isset($this->tree[4]) and isset($this->tree[3])) {
4662 if ($this->tree[4] == "BLOG" and $this->tree[3] == "BLOGS") {
4663 if (!isset($this->temp)) {
4664 $this->temp = "";
4666 $this->temp .= "<".$tagName.">";
4671 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4672 function startElementQuestions($parser, $tagName, $attrs) {
4673 //Refresh properties
4674 $this->level++;
4675 $this->tree[$this->level] = $tagName;
4677 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
4678 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
4679 //} //Debug
4681 //Output something to avoid browser timeouts...
4682 //backup_flush();
4684 //Check if we are into QUESTION_CATEGORIES zone
4685 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
4686 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4688 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
4689 if (isset($this->tree[4]) and isset($this->tree[3])) {
4690 if (($this->tree[4] == "QUESTION_CATEGORY") and ($this->tree[3] == "QUESTION_CATEGORIES")) {
4691 if (!isset($this->temp)) {
4692 $this->temp = "";
4694 $this->temp .= "<".$tagName.">";
4699 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
4700 function startElementScales($parser, $tagName, $attrs) {
4701 //Refresh properties
4702 $this->level++;
4703 $this->tree[$this->level] = $tagName;
4705 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
4706 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
4707 //} //Debug
4709 //Output something to avoid browser timeouts...
4710 //backup_flush();
4712 //Check if we are into SCALES zone
4713 //if ($this->tree[3] == "SCALES") //Debug
4714 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4716 //If we are under a SCALE tag under a SCALES zone, accumule it
4717 if (isset($this->tree[4]) and isset($this->tree[3])) {
4718 if (($this->tree[4] == "SCALE") and ($this->tree[3] == "SCALES")) {
4719 if (!isset($this->temp)) {
4720 $this->temp = "";
4722 $this->temp .= "<".$tagName.">";
4727 function startElementGroups($parser, $tagName, $attrs) {
4728 //Refresh properties
4729 $this->level++;
4730 $this->tree[$this->level] = $tagName;
4732 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
4733 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
4734 //} //Debug
4736 //Output something to avoid browser timeouts...
4737 //backup_flush();
4739 //Check if we are into GROUPS zone
4740 //if ($this->tree[3] == "GROUPS") //Debug
4741 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4743 //If we are under a GROUP tag under a GROUPS zone, accumule it
4744 if (isset($this->tree[4]) and isset($this->tree[3])) {
4745 if (($this->tree[4] == "GROUP") and ($this->tree[3] == "GROUPS")) {
4746 if (!isset($this->temp)) {
4747 $this->temp = "";
4749 $this->temp .= "<".$tagName.">";
4754 function startElementGroupings($parser, $tagName, $attrs) {
4755 //Refresh properties
4756 $this->level++;
4757 $this->tree[$this->level] = $tagName;
4759 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
4760 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
4761 //} //Debug
4763 //Output something to avoid browser timeouts...
4764 //backup_flush();
4766 //Check if we are into GROUPINGS zone
4767 //if ($this->tree[3] == "GROUPINGS") //Debug
4768 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4770 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
4771 if (isset($this->tree[4]) and isset($this->tree[3])) {
4772 if (($this->tree[4] == "GROUPING") and ($this->tree[3] == "GROUPINGS")) {
4773 if (!isset($this->temp)) {
4774 $this->temp = "";
4776 $this->temp .= "<".$tagName.">";
4781 function startElementGroupingsGroups($parser, $tagName, $attrs) {
4782 //Refresh properties
4783 $this->level++;
4784 $this->tree[$this->level] = $tagName;
4786 //if ($tagName == "GROUPINGGROUP" && $this->tree[3] == "GROUPINGSGROUPS") { //Debug
4787 // echo "<P>GROUPINGSGROUP: ".strftime ("%X",time()),"-"; //Debug
4788 //} //Debug
4790 //Output something to avoid browser timeouts...
4791 backup_flush();
4793 //Check if we are into GROUPINGSGROUPS zone
4794 //if ($this->tree[3] == "GROUPINGSGROUPS") //Debug
4795 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4797 //If we are under a GROUPINGGROUP tag under a GROUPINGSGROUPS zone, accumule it
4798 if (isset($this->tree[4]) and isset($this->tree[3])) {
4799 if (($this->tree[4] == "GROUPINGGROUP") and ($this->tree[3] == "GROUPINGSGROUPS")) {
4800 if (!isset($this->temp)) {
4801 $this->temp = "";
4803 $this->temp .= "<".$tagName.">";
4808 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
4809 function startElementEvents($parser, $tagName, $attrs) {
4810 //Refresh properties
4811 $this->level++;
4812 $this->tree[$this->level] = $tagName;
4814 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
4815 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
4816 //} //Debug
4818 //Output something to avoid browser timeouts...
4819 //backup_flush();
4821 //Check if we are into EVENTS zone
4822 //if ($this->tree[3] == "EVENTS") //Debug
4823 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4825 //If we are under a EVENT tag under a EVENTS zone, accumule it
4826 if (isset($this->tree[4]) and isset($this->tree[3])) {
4827 if (($this->tree[4] == "EVENT") and ($this->tree[3] == "EVENTS")) {
4828 if (!isset($this->temp)) {
4829 $this->temp = "";
4831 $this->temp .= "<".$tagName.">";
4836 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
4837 function startElementModules($parser, $tagName, $attrs) {
4838 //Refresh properties
4839 $this->level++;
4840 $this->tree[$this->level] = $tagName;
4842 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
4843 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
4844 //} //Debug
4846 //Output something to avoid browser timeouts...
4847 //backup_flush();
4849 //Check if we are into MODULES zone
4850 //if ($this->tree[3] == "MODULES") //Debug
4851 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4853 //If we are under a MOD tag under a MODULES zone, accumule it
4854 if (isset($this->tree[4]) and isset($this->tree[3])) {
4855 if (($this->tree[4] == "MOD") and ($this->tree[3] == "MODULES")) {
4856 if (!isset($this->temp)) {
4857 $this->temp = "";
4859 $this->temp .= "<".$tagName.">";
4864 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
4865 function startElementLogs($parser, $tagName, $attrs) {
4866 //Refresh properties
4867 $this->level++;
4868 $this->tree[$this->level] = $tagName;
4870 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
4871 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
4872 //} //Debug
4874 //Output something to avoid browser timeouts...
4875 //backup_flush();
4877 //Check if we are into LOGS zone
4878 //if ($this->tree[3] == "LOGS") //Debug
4879 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4881 //If we are under a LOG tag under a LOGS zone, accumule it
4882 if (isset($this->tree[4]) and isset($this->tree[3])) {
4883 if (($this->tree[4] == "LOG") and ($this->tree[3] == "LOGS")) {
4884 if (!isset($this->temp)) {
4885 $this->temp = "";
4887 $this->temp .= "<".$tagName.">";
4892 //This is the startTag default handler we use when todo is undefined
4893 function startElement($parser, $tagName, $attrs) {
4894 $this->level++;
4895 $this->tree[$this->level] = $tagName;
4897 //Output something to avoid browser timeouts...
4898 //backup_flush();
4900 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4903 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
4904 function endElementInfo($parser, $tagName) {
4905 //Check if we are into INFO zone
4906 if ($this->tree[2] == "INFO") {
4907 //if (trim($this->content)) //Debug
4908 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4909 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4910 //Dependig of different combinations, do different things
4911 if ($this->level == 3) {
4912 switch ($tagName) {
4913 case "NAME":
4914 $this->info->backup_name = $this->getContents();
4915 break;
4916 case "MOODLE_VERSION":
4917 $this->info->backup_moodle_version = $this->getContents();
4918 break;
4919 case "MOODLE_RELEASE":
4920 $this->info->backup_moodle_release = $this->getContents();
4921 break;
4922 case "BACKUP_VERSION":
4923 $this->info->backup_backup_version = $this->getContents();
4924 break;
4925 case "BACKUP_RELEASE":
4926 $this->info->backup_backup_release = $this->getContents();
4927 break;
4928 case "DATE":
4929 $this->info->backup_date = $this->getContents();
4930 break;
4931 case "ORIGINAL_WWWROOT":
4932 $this->info->original_wwwroot = $this->getContents();
4933 break;
4934 case "MNET_EXTERNALUSERS":
4935 $this->info->mnet_externalusers = $this->getContents();
4936 break;
4939 if ($this->tree[3] == "DETAILS") {
4940 if ($this->level == 4) {
4941 switch ($tagName) {
4942 case "METACOURSE":
4943 $this->info->backup_metacourse = $this->getContents();
4944 break;
4945 case "USERS":
4946 $this->info->backup_users = $this->getContents();
4947 break;
4948 case "LOGS":
4949 $this->info->backup_logs = $this->getContents();
4950 break;
4951 case "USERFILES":
4952 $this->info->backup_user_files = $this->getContents();
4953 break;
4954 case "COURSEFILES":
4955 $this->info->backup_course_files = $this->getContents();
4956 break;
4957 case "SITEFILES":
4958 $this->info->backup_site_files = $this->getContents();
4959 break;
4960 case "GRADEBOOKHISTORIES":
4961 $this->info->gradebook_histories = $this->getContents();
4962 break;
4963 case "MESSAGES":
4964 $this->info->backup_messages = $this->getContents();
4965 break;
4966 case "BLOGS":
4967 $this->info->backup_blogs = $this->getContents();
4968 break;
4969 case 'BLOCKFORMAT':
4970 $this->info->backup_block_format = $this->getContents();
4971 break;
4974 if ($this->level == 5) {
4975 switch ($tagName) {
4976 case "NAME":
4977 $this->info->tempName = $this->getContents();
4978 break;
4979 case "INCLUDED":
4980 $this->info->mods[$this->info->tempName]->backup = $this->getContents();
4981 break;
4982 case "USERINFO":
4983 $this->info->mods[$this->info->tempName]->userinfo = $this->getContents();
4984 break;
4987 if ($this->level == 7) {
4988 switch ($tagName) {
4989 case "ID":
4990 $this->info->tempId = $this->getContents();
4991 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->id = $this->info->tempId;
4992 break;
4993 case "NAME":
4994 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->name = $this->getContents();
4995 break;
4996 case "INCLUDED":
4997 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->backup = $this->getContents();
4998 break;
4999 case "USERINFO":
5000 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->userinfo = $this->getContents();
5001 break;
5007 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
5008 //Speed up a lot (avoid parse all)
5009 if ($tagName == "INFO") {
5010 $this->finished = true;
5013 //Clear things
5014 $this->tree[$this->level] = "";
5015 $this->level--;
5016 $this->content = "";
5020 function endElementRoles($parser, $tagName) {
5021 //Check if we are into INFO zone
5022 if ($this->tree[2] == "ROLES") {
5024 if ($this->tree[3] == "ROLE") {
5025 if ($this->level == 4) {
5026 switch ($tagName) {
5027 case "ID": // this is the old id
5028 $this->info->tempid = $this->getContents();
5029 $this->info->roles[$this->info->tempid]->id = $this->info->tempid;
5030 break;
5031 case "NAME":
5032 $this->info->roles[$this->info->tempid]->name = $this->getContents();;
5033 break;
5034 case "SHORTNAME":
5035 $this->info->roles[$this->info->tempid]->shortname = $this->getContents();;
5036 break;
5037 case "NAMEINCOURSE": // custom name of the role in course
5038 $this->info->roles[$this->info->tempid]->nameincourse = $this->getContents();;
5039 break;
5042 if ($this->level == 6) {
5043 switch ($tagName) {
5044 case "NAME":
5045 $this->info->tempcapname = $this->getContents();
5046 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->name = $this->getContents();
5047 break;
5048 case "PERMISSION":
5049 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->permission = $this->getContents();
5050 break;
5051 case "TIMEMODIFIED":
5052 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->timemodified = $this->getContents();
5053 break;
5054 case "MODIFIERID":
5055 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->modifierid = $this->getContents();
5056 break;
5062 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
5063 //Speed up a lot (avoid parse all)
5064 if ($tagName == "ROLES") {
5065 $this->finished = true;
5068 //Clear things
5069 $this->tree[$this->level] = "";
5070 $this->level--;
5071 $this->content = "";
5075 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
5076 function endElementCourseHeader($parser, $tagName) {
5077 //Check if we are into COURSE_HEADER zone
5078 if ($this->tree[3] == "HEADER") {
5079 //if (trim($this->content)) //Debug
5080 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5081 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5082 //Dependig of different combinations, do different things
5083 if ($this->level == 4) {
5084 switch ($tagName) {
5085 case "ID":
5086 $this->info->course_id = $this->getContents();
5087 break;
5088 case "PASSWORD":
5089 $this->info->course_password = $this->getContents();
5090 break;
5091 case "FULLNAME":
5092 $this->info->course_fullname = $this->getContents();
5093 break;
5094 case "SHORTNAME":
5095 $this->info->course_shortname = $this->getContents();
5096 break;
5097 case "IDNUMBER":
5098 $this->info->course_idnumber = $this->getContents();
5099 break;
5100 case "SUMMARY":
5101 $this->info->course_summary = $this->getContents();
5102 break;
5103 case "FORMAT":
5104 $this->info->course_format = $this->getContents();
5105 break;
5106 case "SHOWGRADES":
5107 $this->info->course_showgrades = $this->getContents();
5108 break;
5109 case "BLOCKINFO":
5110 $this->info->blockinfo = $this->getContents();
5111 break;
5112 case "NEWSITEMS":
5113 $this->info->course_newsitems = $this->getContents();
5114 break;
5115 case "TEACHER":
5116 $this->info->course_teacher = $this->getContents();
5117 break;
5118 case "TEACHERS":
5119 $this->info->course_teachers = $this->getContents();
5120 break;
5121 case "STUDENT":
5122 $this->info->course_student = $this->getContents();
5123 break;
5124 case "STUDENTS":
5125 $this->info->course_students = $this->getContents();
5126 break;
5127 case "GUEST":
5128 $this->info->course_guest = $this->getContents();
5129 break;
5130 case "STARTDATE":
5131 $this->info->course_startdate = $this->getContents();
5132 break;
5133 case "NUMSECTIONS":
5134 $this->info->course_numsections = $this->getContents();
5135 break;
5136 //case "SHOWRECENT": INFO: This is out in 1.3
5137 // $this->info->course_showrecent = $this->getContents();
5138 // break;
5139 case "MAXBYTES":
5140 $this->info->course_maxbytes = $this->getContents();
5141 break;
5142 case "SHOWREPORTS":
5143 $this->info->course_showreports = $this->getContents();
5144 break;
5145 case "GROUPMODE":
5146 $this->info->course_groupmode = $this->getContents();
5147 break;
5148 case "GROUPMODEFORCE":
5149 $this->info->course_groupmodeforce = $this->getContents();
5150 break;
5151 case "DEFAULTGROUPINGID":
5152 $this->info->course_defaultgroupingid = $this->getContents();
5153 break;
5154 case "LANG":
5155 $this->info->course_lang = $this->getContents();
5156 break;
5157 case "THEME":
5158 $this->info->course_theme = $this->getContents();
5159 break;
5160 case "COST":
5161 $this->info->course_cost = $this->getContents();
5162 break;
5163 case "CURRENCY":
5164 $this->info->course_currency = $this->getContents();
5165 break;
5166 case "MARKER":
5167 $this->info->course_marker = $this->getContents();
5168 break;
5169 case "VISIBLE":
5170 $this->info->course_visible = $this->getContents();
5171 break;
5172 case "HIDDENSECTIONS":
5173 $this->info->course_hiddensections = $this->getContents();
5174 break;
5175 case "TIMECREATED":
5176 $this->info->course_timecreated = $this->getContents();
5177 break;
5178 case "TIMEMODIFIED":
5179 $this->info->course_timemodified = $this->getContents();
5180 break;
5181 case "METACOURSE":
5182 $this->info->course_metacourse = $this->getContents();
5183 break;
5184 case "EXPIRENOTIFY":
5185 $this->info->course_expirynotify = $this->getContents();
5186 break;
5187 case "NOTIFYSTUDENTS":
5188 $this->info->course_notifystudents = $this->getContents();
5189 break;
5190 case "EXPIRYTHRESHOLD":
5191 $this->info->course_expirythreshold = $this->getContents();
5192 break;
5193 case "ENROLLABLE":
5194 $this->info->course_enrollable = $this->getContents();
5195 break;
5196 case "ENROLSTARTDATE":
5197 $this->info->course_enrolstartdate = $this->getContents();
5198 break;
5199 case "ENROLENDDATE":
5200 $this->info->course_enrolenddate = $this->getContents();
5201 break;
5202 case "ENROLPERIOD":
5203 $this->info->course_enrolperiod = $this->getContents();
5204 break;
5207 if ($this->tree[4] == "CATEGORY") {
5208 if ($this->level == 5) {
5209 switch ($tagName) {
5210 case "ID":
5211 $this->info->category->id = $this->getContents();
5212 break;
5213 case "NAME":
5214 $this->info->category->name = $this->getContents();
5215 break;
5220 if ($this->tree[4] == "ROLES_ASSIGNMENTS") {
5221 if ($this->level == 6) {
5222 switch ($tagName) {
5223 case "NAME":
5224 $this->info->tempname = $this->getContents();
5225 break;
5226 case "SHORTNAME":
5227 $this->info->tempshortname = $this->getContents();
5228 break;
5229 case "ID":
5230 $this->info->tempid = $this->getContents();
5231 break;
5235 if ($this->level == 8) {
5236 switch ($tagName) {
5237 case "USERID":
5238 $this->info->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5239 $this->info->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5240 $this->info->tempuser = $this->getContents();
5241 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5242 break;
5243 case "HIDDEN":
5244 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5245 break;
5246 case "TIMESTART":
5247 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5248 break;
5249 case "TIMEEND":
5250 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5251 break;
5252 case "TIMEMODIFIED":
5253 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5254 break;
5255 case "MODIFIERID":
5256 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5257 break;
5258 case "ENROL":
5259 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5260 break;
5261 case "SORTORDER":
5262 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5263 break;
5267 } /// ends role_assignments
5269 if ($this->tree[4] == "ROLES_OVERRIDES") {
5270 if ($this->level == 6) {
5271 switch ($tagName) {
5272 case "NAME":
5273 $this->info->tempname = $this->getContents();
5274 break;
5275 case "SHORTNAME":
5276 $this->info->tempshortname = $this->getContents();
5277 break;
5278 case "ID":
5279 $this->info->tempid = $this->getContents();
5280 break;
5284 if ($this->level == 8) {
5285 switch ($tagName) {
5286 case "NAME":
5287 $this->info->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5288 $this->info->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5289 $this->info->tempname = $this->getContents(); // change to name of capability
5290 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5291 break;
5292 case "PERMISSION":
5293 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5294 break;
5295 case "TIMEMODIFIED":
5296 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5297 break;
5298 case "MODIFIERID":
5299 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5300 break;
5303 } /// ends role_overrides
5306 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
5307 //Speed up a lot (avoid parse all)
5308 if ($tagName == "HEADER") {
5309 $this->finished = true;
5312 //Clear things
5313 $this->tree[$this->level] = "";
5314 $this->level--;
5315 $this->content = "";
5319 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
5320 function endElementBlocks($parser, $tagName) {
5321 //Check if we are into BLOCKS zone
5322 if ($this->tree[3] == 'BLOCKS') {
5323 //if (trim($this->content)) //Debug
5324 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5325 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5327 // Collect everything into $this->temp
5328 if (!isset($this->temp)) {
5329 $this->temp = "";
5331 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5333 //Dependig of different combinations, do different things
5334 if ($this->level == 4) {
5335 switch ($tagName) {
5336 case 'BLOCK':
5337 //We've finalized a block, get it
5338 $this->info->instances[] = $this->info->tempinstance;
5339 unset($this->info->tempinstance);
5341 //Also, xmlize INSTANCEDATA and save to db
5342 //Prepend XML standard header to info gathered
5343 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5344 //Call to xmlize for this portion of xml data (one BLOCK)
5345 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5346 $data = xmlize($xml_data,0);
5347 //echo strftime ("%X",time())."<p>"; //Debug
5348 //traverse_xmlize($data); //Debug
5349 //print_object ($GLOBALS['traverse_array']); //Debug
5350 //$GLOBALS['traverse_array']=""; //Debug
5351 //Check for instancedata, is exists, then save to DB
5352 if (isset($data['BLOCK']['#']['INSTANCEDATA']['0']['#'])) {
5353 //Get old id
5354 $oldid = $data['BLOCK']['#']['ID']['0']['#'];
5355 //Get instancedata
5357 if ($data = $data['BLOCK']['#']['INSTANCEDATA']['0']['#']) {
5358 //Restore code calls this multiple times - so might already have the newid
5359 if ($newid = backup_getid($this->preferences->backup_unique_code,'block_instance',$oldid)) {
5360 $newid = $newid->new_id;
5361 } else {
5362 $newid = null;
5364 //Save to DB, we will use it later
5365 $status = backup_putid($this->preferences->backup_unique_code,'block_instance',$oldid,$newid,$data);
5368 //Reset temp
5369 unset($this->temp);
5371 break;
5372 default:
5373 die($tagName);
5376 if ($this->level == 5) {
5377 switch ($tagName) {
5378 case 'ID':
5379 $this->info->tempinstance->id = $this->getContents();
5380 case 'NAME':
5381 $this->info->tempinstance->name = $this->getContents();
5382 break;
5383 case 'PAGEID':
5384 $this->info->tempinstance->pageid = $this->getContents();
5385 break;
5386 case 'PAGETYPE':
5387 $this->info->tempinstance->pagetype = $this->getContents();
5388 break;
5389 case 'POSITION':
5390 $this->info->tempinstance->position = $this->getContents();
5391 break;
5392 case 'WEIGHT':
5393 $this->info->tempinstance->weight = $this->getContents();
5394 break;
5395 case 'VISIBLE':
5396 $this->info->tempinstance->visible = $this->getContents();
5397 break;
5398 case 'CONFIGDATA':
5399 $this->info->tempinstance->configdata = $this->getContents();
5400 break;
5401 default:
5402 break;
5406 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
5407 if ($this->level == 7) {
5408 switch ($tagName) {
5409 case "NAME":
5410 $this->info->tempname = $this->getContents();
5411 break;
5412 case "SHORTNAME":
5413 $this->info->tempshortname = $this->getContents();
5414 break;
5415 case "ID":
5416 $this->info->tempid = $this->getContents(); // temp roleid
5417 break;
5421 if ($this->level == 9) {
5423 switch ($tagName) {
5424 case "USERID":
5425 $this->info->tempinstance->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5427 $this->info->tempinstance->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5429 $this->info->tempuser = $this->getContents();
5431 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5432 break;
5433 case "HIDDEN":
5434 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5435 break;
5436 case "TIMESTART":
5437 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5438 break;
5439 case "TIMEEND":
5440 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5441 break;
5442 case "TIMEMODIFIED":
5443 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5444 break;
5445 case "MODIFIERID":
5446 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5447 break;
5448 case "ENROL":
5449 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5450 break;
5451 case "SORTORDER":
5452 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5453 break;
5457 } /// ends role_assignments
5459 if ($this->tree[5] == "ROLES_OVERRIDES") {
5460 if ($this->level == 7) {
5461 switch ($tagName) {
5462 case "NAME":
5463 $this->info->tempname = $this->getContents();
5464 break;
5465 case "SHORTNAME":
5466 $this->info->tempshortname = $this->getContents();
5467 break;
5468 case "ID":
5469 $this->info->tempid = $this->getContents(); // temp roleid
5470 break;
5474 if ($this->level == 9) {
5475 switch ($tagName) {
5476 case "NAME":
5478 $this->info->tempinstance->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5479 $this->info->tempinstance->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5480 $this->info->tempname = $this->getContents(); // change to name of capability
5481 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5482 break;
5483 case "PERMISSION":
5484 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5485 break;
5486 case "TIMEMODIFIED":
5487 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5488 break;
5489 case "MODIFIERID":
5490 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5491 break;
5494 } /// ends role_overrides
5497 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
5498 //Speed up a lot (avoid parse all)
5499 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
5500 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
5501 if ($this->tree[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
5502 $this->finished = true;
5505 //Clear things
5506 $this->tree[$this->level] = '';
5507 $this->level--;
5508 $this->content = "";
5511 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
5512 function endElementSections($parser, $tagName) {
5513 //Check if we are into SECTIONS zone
5514 if ($this->tree[3] == "SECTIONS") {
5515 //if (trim($this->content)) //Debug
5516 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5517 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5518 //Dependig of different combinations, do different things
5519 if ($this->level == 4) {
5520 switch ($tagName) {
5521 case "SECTION":
5522 //We've finalized a section, get it
5523 $this->info->sections[$this->info->tempsection->id] = $this->info->tempsection;
5524 unset($this->info->tempsection);
5527 if ($this->level == 5) {
5528 switch ($tagName) {
5529 case "ID":
5530 $this->info->tempsection->id = $this->getContents();
5531 break;
5532 case "NUMBER":
5533 $this->info->tempsection->number = $this->getContents();
5534 break;
5535 case "SUMMARY":
5536 $this->info->tempsection->summary = $this->getContents();
5537 break;
5538 case "VISIBLE":
5539 $this->info->tempsection->visible = $this->getContents();
5540 break;
5543 if ($this->level == 6) {
5544 switch ($tagName) {
5545 case "MOD":
5546 if (!isset($this->info->tempmod->groupmode)) {
5547 $this->info->tempmod->groupmode = 0;
5549 if (!isset($this->info->tempmod->groupingid)) {
5550 $this->info->tempmod->groupingid = 0;
5552 if (!isset($this->info->tempmod->groupmembersonly)) {
5553 $this->info->tempmod->groupmembersonly = 0;
5555 if (!isset($this->info->tempmod->idnumber)) {
5556 $this->info->tempmod->idnumber = null;
5559 //We've finalized a mod, get it
5560 $this->info->tempsection->mods[$this->info->tempmod->id]->type =
5561 $this->info->tempmod->type;
5562 $this->info->tempsection->mods[$this->info->tempmod->id]->instance =
5563 $this->info->tempmod->instance;
5564 $this->info->tempsection->mods[$this->info->tempmod->id]->added =
5565 $this->info->tempmod->added;
5566 $this->info->tempsection->mods[$this->info->tempmod->id]->score =
5567 $this->info->tempmod->score;
5568 $this->info->tempsection->mods[$this->info->tempmod->id]->indent =
5569 $this->info->tempmod->indent;
5570 $this->info->tempsection->mods[$this->info->tempmod->id]->visible =
5571 $this->info->tempmod->visible;
5572 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmode =
5573 $this->info->tempmod->groupmode;
5574 $this->info->tempsection->mods[$this->info->tempmod->id]->groupingid =
5575 $this->info->tempmod->groupingid;
5576 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmembersonly =
5577 $this->info->tempmod->groupmembersonly;
5578 $this->info->tempsection->mods[$this->info->tempmod->id]->idnumber =
5579 $this->info->tempmod->idnumber;
5581 unset($this->info->tempmod);
5584 if ($this->level == 7) {
5585 switch ($tagName) {
5586 case "ID":
5587 $this->info->tempmod->id = $this->getContents();
5588 break;
5589 case "TYPE":
5590 $this->info->tempmod->type = $this->getContents();
5591 break;
5592 case "INSTANCE":
5593 $this->info->tempmod->instance = $this->getContents();
5594 break;
5595 case "ADDED":
5596 $this->info->tempmod->added = $this->getContents();
5597 break;
5598 case "SCORE":
5599 $this->info->tempmod->score = $this->getContents();
5600 break;
5601 case "INDENT":
5602 $this->info->tempmod->indent = $this->getContents();
5603 break;
5604 case "VISIBLE":
5605 $this->info->tempmod->visible = $this->getContents();
5606 break;
5607 case "GROUPMODE":
5608 $this->info->tempmod->groupmode = $this->getContents();
5609 break;
5610 case "GROUPINGID":
5611 $this->info->tempmod->groupingid = $this->getContents();
5612 break;
5613 case "GROUPMEMBERSONLY":
5614 $this->info->tempmod->groupmembersonly = $this->getContents();
5615 case "IDNUMBER":
5616 $this->info->tempmod->idnumber = $this->getContents();
5617 break;
5618 default:
5619 break;
5623 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_ASSIGNMENTS") {
5625 if ($this->level == 9) {
5626 switch ($tagName) {
5627 case "NAME":
5628 $this->info->tempname = $this->getContents();
5629 break;
5630 case "SHORTNAME":
5631 $this->info->tempshortname = $this->getContents();
5632 break;
5633 case "ID":
5634 $this->info->tempid = $this->getContents(); // temp roleid
5635 break;
5639 if ($this->level == 11) {
5640 switch ($tagName) {
5641 case "USERID":
5642 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5644 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5646 $this->info->tempuser = $this->getContents();
5648 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5649 break;
5650 case "HIDDEN":
5651 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5652 break;
5653 case "TIMESTART":
5654 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5655 break;
5656 case "TIMEEND":
5657 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5658 break;
5659 case "TIMEMODIFIED":
5660 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5661 break;
5662 case "MODIFIERID":
5663 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5664 break;
5665 case "ENROL":
5666 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5667 break;
5668 case "SORTORDER":
5669 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5670 break;
5674 } /// ends role_assignments
5676 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_OVERRIDES") {
5677 if ($this->level == 9) {
5678 switch ($tagName) {
5679 case "NAME":
5680 $this->info->tempname = $this->getContents();
5681 break;
5682 case "SHORTNAME":
5683 $this->info->tempshortname = $this->getContents();
5684 break;
5685 case "ID":
5686 $this->info->tempid = $this->getContents(); // temp roleid
5687 break;
5691 if ($this->level == 11) {
5692 switch ($tagName) {
5693 case "NAME":
5695 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5696 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5697 $this->info->tempname = $this->getContents(); // change to name of capability
5698 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5699 break;
5700 case "PERMISSION":
5701 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5702 break;
5703 case "TIMEMODIFIED":
5704 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5705 break;
5706 case "MODIFIERID":
5707 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5708 break;
5711 } /// ends role_overrides
5715 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
5716 //Speed up a lot (avoid parse all)
5717 if ($tagName == "SECTIONS") {
5718 $this->finished = true;
5721 //Clear things
5722 $this->tree[$this->level] = "";
5723 $this->level--;
5724 $this->content = "";
5728 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
5729 function endElementFormatData($parser, $tagName) {
5730 //Check if we are into FORMATDATA zone
5731 if ($this->tree[3] == 'FORMATDATA') {
5732 if (!isset($this->temp)) {
5733 $this->temp = '';
5735 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5738 if($tagName=='FORMATDATA') {
5739 //Did we have any data? If not don't bother
5740 if($this->temp!='<FORMATDATA></FORMATDATA>') {
5741 //Prepend XML standard header to info gathered
5742 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5743 $this->temp='';
5745 //Call to xmlize for this portion of xml data (the FORMATDATA block)
5746 $this->info->format_data = xmlize($xml_data,0);
5748 //Stop parsing at end of FORMATDATA
5749 $this->finished=true;
5752 //Clear things
5753 $this->tree[$this->level] = "";
5754 $this->level--;
5755 $this->content = "";
5758 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
5759 function endElementMetacourse($parser, $tagName) {
5760 //Check if we are into METACOURSE zone
5761 if ($this->tree[3] == 'METACOURSE') {
5762 //if (trim($this->content)) //Debug
5763 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5764 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5765 //Dependig of different combinations, do different things
5766 if ($this->level == 5) {
5767 switch ($tagName) {
5768 case 'CHILD':
5769 //We've finalized a child, get it
5770 $this->info->childs[] = $this->info->tempmeta;
5771 unset($this->info->tempmeta);
5772 break;
5773 case 'PARENT':
5774 //We've finalized a parent, get it
5775 $this->info->parents[] = $this->info->tempmeta;
5776 unset($this->info->tempmeta);
5777 break;
5778 default:
5779 die($tagName);
5782 if ($this->level == 6) {
5783 switch ($tagName) {
5784 case 'ID':
5785 $this->info->tempmeta->id = $this->getContents();
5786 break;
5787 case 'IDNUMBER':
5788 $this->info->tempmeta->idnumber = $this->getContents();
5789 break;
5790 case 'SHORTNAME':
5791 $this->info->tempmeta->shortname = $this->getContents();
5792 break;
5797 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
5798 //Speed up a lot (avoid parse all)
5799 if ($this->tree[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
5800 $this->finished = true;
5803 //Clear things
5804 $this->tree[$this->level] = '';
5805 $this->level--;
5806 $this->content = "";
5809 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5810 function endElementGradebook($parser, $tagName) {
5811 //Check if we are into GRADEBOOK zone
5812 if ($this->tree[3] == "GRADEBOOK") {
5813 //if (trim($this->content)) //Debug
5814 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5815 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
5816 //Acumulate data to info (content + close tag)
5817 //Reconvert: strip htmlchars again and trim to generate xml data
5818 if (!isset($this->temp)) {
5819 $this->temp = "";
5821 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5822 // We have finished outcome, grade_category or grade_item, reset accumulated
5823 // data because they are close tags
5824 if ($this->level == 4) {
5825 $this->temp = "";
5827 //If we've finished a grade item, xmlize it an save to db
5828 if (($this->level == 5) and ($tagName == "GRADE_ITEM")) {
5829 //Prepend XML standard header to info gathered
5830 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5831 //Call to xmlize for this portion of xml data (one PREFERENCE)
5832 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5833 $data = xmlize($xml_data,0);
5834 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
5835 $this->counter++;
5836 //Save to db
5838 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items', $item_id,
5839 null,$data);
5840 //Create returning info
5841 $this->info = $this->counter;
5842 //Reset temp
5844 unset($this->temp);
5847 //If we've finished a grade_category, xmlize it an save to db
5848 if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
5849 //Prepend XML standard header to info gathered
5850 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5851 //Call to xmlize for this portion of xml data (one CATECORY)
5852 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5853 $data = xmlize($xml_data,0);
5854 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5855 $this->counter++;
5856 //Save to db
5857 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories' ,$category_id,
5858 null,$data);
5859 //Create returning info
5860 $this->info = $this->counter;
5861 //Reset temp
5862 unset($this->temp);
5865 if (($this->level == 5) and ($tagName == "GRADE_LETTER")) {
5866 //Prepend XML standard header to info gathered
5867 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5868 //Call to xmlize for this portion of xml data (one CATECORY)
5869 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5870 $data = xmlize($xml_data,0);
5871 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
5872 $this->counter++;
5873 //Save to db
5874 $status = backup_putid($this->preferences->backup_unique_code, 'grade_letters' ,$letter_id,
5875 null,$data);
5876 //Create returning info
5877 $this->info = $this->counter;
5878 //Reset temp
5879 unset($this->temp);
5882 //If we've finished a grade_outcome, xmlize it an save to db
5883 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME")) {
5884 //Prepend XML standard header to info gathered
5885 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5886 //Call to xmlize for this portion of xml data (one CATECORY)
5887 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5888 $data = xmlize($xml_data,0);
5889 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
5890 $this->counter++;
5891 //Save to db
5892 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes' ,$outcome_id,
5893 null,$data);
5894 //Create returning info
5895 $this->info = $this->counter;
5896 //Reset temp
5897 unset($this->temp);
5900 //If we've finished a grade_outcomes_course, xmlize it an save to db
5901 if (($this->level == 5) and ($tagName == "GRADE_OUTCOMES_COURSE")) {
5902 //Prepend XML standard header to info gathered
5903 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5904 //Call to xmlize for this portion of xml data (one CATECORY)
5905 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5906 $data = xmlize($xml_data,0);
5907 $outcomes_course_id = $data["GRADE_OUTCOMES_COURSE"]["#"]["ID"]["0"]["#"];
5908 $this->counter++;
5909 //Save to db
5910 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_courses' ,$outcomes_course_id,
5911 null,$data);
5912 //Create returning info
5913 $this->info = $this->counter;
5914 //Reset temp
5915 unset($this->temp);
5918 if (($this->level == 5) and ($tagName == "GRADE_CATEGORIES_HISTORY")) {
5919 //Prepend XML standard header to info gathered
5920 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5921 //Call to xmlize for this portion of xml data (one PREFERENCE)
5922 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5923 $data = xmlize($xml_data,0);
5924 $id = $data["GRADE_CATEGORIES_HISTORY"]["#"]["ID"]["0"]["#"];
5925 $this->counter++;
5926 //Save to db
5928 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories_history', $id,
5929 null,$data);
5930 //Create returning info
5931 $this->info = $this->counter;
5932 //Reset temp
5934 unset($this->temp);
5937 if (($this->level == 5) and ($tagName == "GRADE_GRADES_HISTORY")) {
5938 //Prepend XML standard header to info gathered
5939 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5940 //Call to xmlize for this portion of xml data (one PREFERENCE)
5941 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5942 $data = xmlize($xml_data,0);
5943 $id = $data["GRADE_GRADES_HISTORY"]["#"]["ID"]["0"]["#"];
5944 $this->counter++;
5945 //Save to db
5947 $status = backup_putid($this->preferences->backup_unique_code, 'grade_grades_history', $id,
5948 null,$data);
5949 //Create returning info
5950 $this->info = $this->counter;
5951 //Reset temp
5953 unset($this->temp);
5956 if (($this->level == 5) and ($tagName == "GRADE_ITEM_HISTORY")) {
5957 //Prepend XML standard header to info gathered
5958 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5959 //Call to xmlize for this portion of xml data (one PREFERENCE)
5960 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5961 $data = xmlize($xml_data,0);
5962 $id = $data["GRADE_ITEM_HISTORY"]["#"]["ID"]["0"]["#"];
5963 $this->counter++;
5964 //Save to db
5966 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items_history', $id,
5967 null,$data);
5968 //Create returning info
5969 $this->info = $this->counter;
5970 //Reset temp
5972 unset($this->temp);
5975 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME_HISTORY")) {
5976 //Prepend XML standard header to info gathered
5977 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5978 //Call to xmlize for this portion of xml data (one PREFERENCE)
5979 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5980 $data = xmlize($xml_data,0);
5981 $id = $data["GRADE_OUTCOME_HISTORY"]["#"]["ID"]["0"]["#"];
5982 $this->counter++;
5983 //Save to db
5985 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_history', $id,
5986 null,$data);
5987 //Create returning info
5988 $this->info = $this->counter;
5989 //Reset temp
5991 unset($this->temp);
5995 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
5996 //Speed up a lot (avoid parse all)
5997 if ($tagName == "GRADEBOOK" and $this->level == 3) {
5998 $this->finished = true;
5999 $this->counter = 0;
6002 //Clear things
6003 $this->tree[$this->level] = "";
6004 $this->level--;
6005 $this->content = "";
6009 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
6010 function endElementOldGradebook($parser, $tagName) {
6011 //Check if we are into GRADEBOOK zone
6012 if ($this->tree[3] == "GRADEBOOK") {
6013 //if (trim($this->content)) //Debug
6014 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6015 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
6016 //Acumulate data to info (content + close tag)
6017 //Reconvert: strip htmlchars again and trim to generate xml data
6018 if (!isset($this->temp)) {
6019 $this->temp = "";
6021 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6022 //We have finished preferences, letters or categories, reset accumulated
6023 //data because they are close tags
6024 if ($this->level == 4) {
6025 $this->temp = "";
6027 //If we've finished a message, xmlize it an save to db
6028 if (($this->level == 5) and ($tagName == "GRADE_PREFERENCE")) {
6029 //Prepend XML standard header to info gathered
6030 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6031 //Call to xmlize for this portion of xml data (one PREFERENCE)
6032 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6033 $data = xmlize($xml_data,0);
6034 //echo strftime ("%X",time())."<p>"; //Debug
6035 //traverse_xmlize($data); //Debug
6036 //print_object ($GLOBALS['traverse_array']); //Debug
6037 //$GLOBALS['traverse_array']=""; //Debug
6038 //Now, save data to db. We'll use it later
6039 //Get id and status from data
6040 $preference_id = $data["GRADE_PREFERENCE"]["#"]["ID"]["0"]["#"];
6041 $this->counter++;
6042 //Save to db
6043 $status = backup_putid($this->preferences->backup_unique_code, 'grade_preferences', $preference_id,
6044 null,$data);
6045 //Create returning info
6046 $this->info = $this->counter;
6047 //Reset temp
6048 unset($this->temp);
6050 //If we've finished a grade_letter, xmlize it an save to db
6051 if (($this->level == 5) and ($tagName == "GRADE_LETTER")) {
6052 //Prepend XML standard header to info gathered
6053 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6054 //Call to xmlize for this portion of xml data (one LETTER)
6055 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6056 $data = xmlize($xml_data,0);
6057 //echo strftime ("%X",time())."<p>"; //Debug
6058 //traverse_xmlize($data); //Debug
6059 //print_object ($GLOBALS['traverse_array']); //Debug
6060 //$GLOBALS['traverse_array']=""; //Debug
6061 //Now, save data to db. We'll use it later
6062 //Get id and status from data
6063 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
6064 $this->counter++;
6065 //Save to db
6066 $status = backup_putid($this->preferences->backup_unique_code, 'grade_letter' ,$letter_id,
6067 null,$data);
6068 //Create returning info
6069 $this->info = $this->counter;
6070 //Reset temp
6071 unset($this->temp);
6074 //If we've finished a grade_category, xmlize it an save to db
6075 if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
6076 //Prepend XML standard header to info gathered
6077 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6078 //Call to xmlize for this portion of xml data (one CATECORY)
6079 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6080 $data = xmlize($xml_data,0);
6081 //echo strftime ("%X",time())."<p>"; //Debug
6082 //traverse_xmlize($data); //Debug
6083 //print_object ($GLOBALS['traverse_array']); //Debug
6084 //$GLOBALS['traverse_array']=""; //Debug
6085 //Now, save data to db. We'll use it later
6086 //Get id and status from data
6087 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
6088 $this->counter++;
6089 //Save to db
6090 $status = backup_putid($this->preferences->backup_unique_code, 'grade_category' ,$category_id,
6091 null,$data);
6092 //Create returning info
6093 $this->info = $this->counter;
6094 //Reset temp
6095 unset($this->temp);
6099 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
6100 //Speed up a lot (avoid parse all)
6101 if ($tagName == "GRADEBOOK" and $this->level == 3) {
6102 $this->finished = true;
6103 $this->counter = 0;
6106 //Clear things
6107 $this->tree[$this->level] = "";
6108 $this->level--;
6109 $this->content = "";
6113 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
6114 function endElementUsers($parser, $tagName) {
6115 global $CFG;
6116 //Check if we are into USERS zone
6117 if ($this->tree[3] == "USERS") {
6118 //if (trim($this->content)) //Debug
6119 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6120 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6121 //Dependig of different combinations, do different things
6122 if ($this->level == 4) {
6123 switch ($tagName) {
6124 case "USER":
6125 //Increment counter
6126 $this->counter++;
6127 //Save to db, only save if record not already exist
6128 // if there already is an new_id for this entry, just use that new_id?
6129 $newuser = backup_getid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id);
6130 if (isset($newuser->new_id)) {
6131 $newid = $newuser->new_id;
6132 } else {
6133 $newid = null;
6136 backup_putid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id,
6137 $newid,$this->info->tempuser);
6139 //Do some output
6140 if ($this->counter % 10 == 0) {
6141 if (!defined('RESTORE_SILENTLY')) {
6142 echo ".";
6143 if ($this->counter % 200 == 0) {
6144 echo "<br />";
6147 backup_flush(300);
6150 //Delete temp obejct
6151 unset($this->info->tempuser);
6152 break;
6156 if ($this->level == 5) {
6157 switch ($tagName) {
6158 case "ID":
6159 $this->info->users[$this->getContents()] = $this->getContents();
6160 $this->info->tempuser->id = $this->getContents();
6161 break;
6162 case "AUTH":
6163 $this->info->tempuser->auth = $this->getContents();
6164 break;
6165 case "CONFIRMED":
6166 $this->info->tempuser->confirmed = $this->getContents();
6167 break;
6168 case "POLICYAGREED":
6169 $this->info->tempuser->policyagreed = $this->getContents();
6170 break;
6171 case "DELETED":
6172 $this->info->tempuser->deleted = $this->getContents();
6173 break;
6174 case "USERNAME":
6175 $this->info->tempuser->username = $this->getContents();
6176 break;
6177 case "PASSWORD":
6178 $this->info->tempuser->password = $this->getContents();
6179 break;
6180 case "IDNUMBER":
6181 $this->info->tempuser->idnumber = $this->getContents();
6182 break;
6183 case "FIRSTNAME":
6184 $this->info->tempuser->firstname = $this->getContents();
6185 break;
6186 case "LASTNAME":
6187 $this->info->tempuser->lastname = $this->getContents();
6188 break;
6189 case "EMAIL":
6190 $this->info->tempuser->email = $this->getContents();
6191 break;
6192 case "EMAILSTOP":
6193 $this->info->tempuser->emailstop = $this->getContents();
6194 break;
6195 case "ICQ":
6196 $this->info->tempuser->icq = $this->getContents();
6197 break;
6198 case "SKYPE":
6199 $this->info->tempuser->skype = $this->getContents();
6200 break;
6201 case "AIM":
6202 $this->info->tempuser->aim = $this->getContents();
6203 break;
6204 case "YAHOO":
6205 $this->info->tempuser->yahoo = $this->getContents();
6206 break;
6207 case "MSN":
6208 $this->info->tempuser->msn = $this->getContents();
6209 break;
6210 case "PHONE1":
6211 $this->info->tempuser->phone1 = $this->getContents();
6212 break;
6213 case "PHONE2":
6214 $this->info->tempuser->phone2 = $this->getContents();
6215 break;
6216 case "INSTITUTION":
6217 $this->info->tempuser->institution = $this->getContents();
6218 break;
6219 case "DEPARTMENT":
6220 $this->info->tempuser->department = $this->getContents();
6221 break;
6222 case "ADDRESS":
6223 $this->info->tempuser->address = $this->getContents();
6224 break;
6225 case "CITY":
6226 $this->info->tempuser->city = $this->getContents();
6227 break;
6228 case "COUNTRY":
6229 $this->info->tempuser->country = $this->getContents();
6230 break;
6231 case "LANG":
6232 $this->info->tempuser->lang = $this->getContents();
6233 break;
6234 case "THEME":
6235 $this->info->tempuser->theme = $this->getContents();
6236 break;
6237 case "TIMEZONE":
6238 $this->info->tempuser->timezone = $this->getContents();
6239 break;
6240 case "FIRSTACCESS":
6241 $this->info->tempuser->firstaccess = $this->getContents();
6242 break;
6243 case "LASTACCESS":
6244 $this->info->tempuser->lastaccess = $this->getContents();
6245 break;
6246 case "LASTLOGIN":
6247 $this->info->tempuser->lastlogin = $this->getContents();
6248 break;
6249 case "CURRENTLOGIN":
6250 $this->info->tempuser->currentlogin = $this->getContents();
6251 break;
6252 case "LASTIP":
6253 $this->info->tempuser->lastip = $this->getContents();
6254 break;
6255 case "SECRET":
6256 $this->info->tempuser->secret = $this->getContents();
6257 break;
6258 case "PICTURE":
6259 $this->info->tempuser->picture = $this->getContents();
6260 break;
6261 case "URL":
6262 $this->info->tempuser->url = $this->getContents();
6263 break;
6264 case "DESCRIPTION":
6265 $this->info->tempuser->description = $this->getContents();
6266 break;
6267 case "MAILFORMAT":
6268 $this->info->tempuser->mailformat = $this->getContents();
6269 break;
6270 case "MAILDIGEST":
6271 $this->info->tempuser->maildigest = $this->getContents();
6272 break;
6273 case "MAILDISPLAY":
6274 $this->info->tempuser->maildisplay = $this->getContents();
6275 break;
6276 case "HTMLEDITOR":
6277 $this->info->tempuser->htmleditor = $this->getContents();
6278 break;
6279 case "AJAX":
6280 $this->info->tempuser->ajax = $this->getContents();
6281 break;
6282 case "AUTOSUBSCRIBE":
6283 $this->info->tempuser->autosubscribe = $this->getContents();
6284 break;
6285 case "TRACKFORUMS":
6286 $this->info->tempuser->trackforums = $this->getContents();
6287 break;
6288 case "MNETHOSTURL":
6289 $this->info->tempuser->mnethosturl = $this->getContents();
6290 break;
6291 case "TIMEMODIFIED":
6292 $this->info->tempuser->timemodified = $this->getContents();
6293 break;
6294 default:
6295 break;
6299 if ($this->level == 6 && $this->tree[5]!="ROLES_ASSIGNMENTS" && $this->tree[5]!="ROLES_OVERRIDES") {
6300 switch ($tagName) {
6301 case "ROLE":
6302 //We've finalized a role, get it
6303 $this->info->tempuser->roles[$this->info->temprole->type] = $this->info->temprole;
6304 unset($this->info->temprole);
6305 break;
6306 case "USER_PREFERENCE":
6307 //We've finalized a user_preference, get it
6308 $this->info->tempuser->user_preferences[$this->info->tempuserpreference->name] = $this->info->tempuserpreference;
6309 unset($this->info->tempuserpreference);
6310 break;
6311 case "USER_CUSTOM_PROFILE_FIELD":
6312 //We've finalized a user_custom_profile_field, get it
6313 $this->info->tempuser->user_custom_profile_fields[] = $this->info->tempusercustomprofilefield;
6314 unset($this->info->tempusercustomprofilefield);
6315 break;
6316 case "USER_TAG":
6317 //We've finalized a user_tag, get it
6318 $this->info->tempuser->user_tags[] = $this->info->tempusertag;
6319 unset($this->info->tempusertag);
6320 break;
6321 default:
6322 break;
6326 if ($this->level == 7 && $this->tree[5]!="ROLES_ASSIGNMENTS" && $this->tree[5]!="ROLES_OVERRIDES") {
6327 /// If we are reading roles
6328 if($this->tree[6] == 'ROLE') {
6329 switch ($tagName) {
6330 case "TYPE":
6331 $this->info->temprole->type = $this->getContents();
6332 break;
6333 case "AUTHORITY":
6334 $this->info->temprole->authority = $this->getContents();
6335 break;
6336 case "TEA_ROLE":
6337 $this->info->temprole->tea_role = $this->getContents();
6338 break;
6339 case "EDITALL":
6340 $this->info->temprole->editall = $this->getContents();
6341 break;
6342 case "TIMESTART":
6343 $this->info->temprole->timestart = $this->getContents();
6344 break;
6345 case "TIMEEND":
6346 $this->info->temprole->timeend = $this->getContents();
6347 break;
6348 case "TIMEMODIFIED":
6349 $this->info->temprole->timemodified = $this->getContents();
6350 break;
6351 case "TIMESTART":
6352 $this->info->temprole->timestart = $this->getContents();
6353 break;
6354 case "TIMEEND":
6355 $this->info->temprole->timeend = $this->getContents();
6356 break;
6357 case "TIME":
6358 $this->info->temprole->time = $this->getContents();
6359 break;
6360 case "TIMEACCESS":
6361 $this->info->temprole->timeaccess = $this->getContents();
6362 break;
6363 case "ENROL":
6364 $this->info->temprole->enrol = $this->getContents();
6365 break;
6366 default:
6367 break;
6369 /// If we are reading user_preferences
6370 } else if ($this->tree[6] == 'USER_PREFERENCE') {
6371 switch ($tagName) {
6372 case "NAME":
6373 $this->info->tempuserpreference->name = $this->getContents();
6374 break;
6375 case "VALUE":
6376 $this->info->tempuserpreference->value = $this->getContents();
6377 break;
6378 default:
6379 break;
6381 /// If we are reading user_custom_profile_fields
6382 } else if ($this->tree[6] == 'USER_CUSTOM_PROFILE_FIELD') {
6383 switch ($tagName) {
6384 case "FIELD_NAME":
6385 $this->info->tempusercustomprofilefield->field_name = $this->getContents();
6386 break;
6387 case "FIELD_TYPE":
6388 $this->info->tempusercustomprofilefield->field_type = $this->getContents();
6389 break;
6390 case "FIELD_DATA":
6391 $this->info->tempusercustomprofilefield->field_data = $this->getContents();
6392 break;
6393 default:
6394 break;
6396 /// If we are reading user_tags
6397 } else if ($this->tree[6] == 'USER_TAG') {
6398 switch ($tagName) {
6399 case "NAME":
6400 $this->info->tempusertag->name = $this->getContents();
6401 break;
6402 case "RAWNAME":
6403 $this->info->tempusertag->rawname = $this->getContents();
6404 break;
6405 default:
6406 break;
6411 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
6413 if ($this->level == 7) {
6414 switch ($tagName) {
6415 case "NAME":
6416 $this->info->tempname = $this->getContents();
6417 break;
6418 case "SHORTNAME":
6419 $this->info->tempshortname = $this->getContents();
6420 break;
6421 case "ID":
6422 $this->info->tempid = $this->getContents(); // temp roleid
6423 break;
6427 if ($this->level == 9) {
6429 switch ($tagName) {
6430 case "USERID":
6431 $this->info->tempuser->roleassignments[$this->info->tempid]->name = $this->info->tempname;
6433 $this->info->tempuser->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
6435 $this->info->tempuserid = $this->getContents();
6437 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->userid = $this->getContents();
6438 break;
6439 case "HIDDEN":
6440 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->hidden = $this->getContents();
6441 break;
6442 case "TIMESTART":
6443 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timestart = $this->getContents();
6444 break;
6445 case "TIMEEND":
6446 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timeend = $this->getContents();
6447 break;
6448 case "TIMEMODIFIED":
6449 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timemodified = $this->getContents();
6450 break;
6451 case "MODIFIERID":
6452 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->modifierid = $this->getContents();
6453 break;
6454 case "ENROL":
6455 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->enrol = $this->getContents();
6456 break;
6457 case "SORTORDER":
6458 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->sortorder = $this->getContents();
6459 break;
6463 } /// ends role_assignments
6465 if ($this->tree[5] == "ROLES_OVERRIDES") {
6466 if ($this->level == 7) {
6467 switch ($tagName) {
6468 case "NAME":
6469 $this->info->tempname = $this->getContents();
6470 break;
6471 case "SHORTNAME":
6472 $this->info->tempshortname = $this->getContents();
6473 break;
6474 case "ID":
6475 $this->info->tempid = $this->getContents(); // temp roleid
6476 break;
6480 if ($this->level == 9) {
6481 switch ($tagName) {
6482 case "NAME":
6484 $this->info->tempuser->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
6485 $this->info->tempuser->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
6486 $this->info->tempname = $this->getContents(); // change to name of capability
6487 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
6488 break;
6489 case "PERMISSION":
6490 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
6491 break;
6492 case "TIMEMODIFIED":
6493 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
6494 break;
6495 case "MODIFIERID":
6496 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
6497 break;
6500 } /// ends role_overrides
6502 } // closes if this->tree[3]=="users"
6504 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
6505 //Speed up a lot (avoid parse all)
6506 if ($tagName == "USERS" and $this->level == 3) {
6507 $this->finished = true;
6508 $this->counter = 0;
6511 //Clear things
6512 $this->tree[$this->level] = "";
6513 $this->level--;
6514 $this->content = "";
6518 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
6519 function endElementMessages($parser, $tagName) {
6520 //Check if we are into MESSAGES zone
6521 if ($this->tree[3] == "MESSAGES") {
6522 //if (trim($this->content)) //Debug
6523 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6524 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
6525 //Acumulate data to info (content + close tag)
6526 //Reconvert: strip htmlchars again and trim to generate xml data
6527 if (!isset($this->temp)) {
6528 $this->temp = "";
6530 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6531 //If we've finished a message, xmlize it an save to db
6532 if (($this->level == 4) and ($tagName == "MESSAGE")) {
6533 //Prepend XML standard header to info gathered
6534 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6535 //Call to xmlize for this portion of xml data (one MESSAGE)
6536 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6537 $data = xmlize($xml_data,0);
6538 //echo strftime ("%X",time())."<p>"; //Debug
6539 //traverse_xmlize($data); //Debug
6540 //print_object ($GLOBALS['traverse_array']); //Debug
6541 //$GLOBALS['traverse_array']=""; //Debug
6542 //Now, save data to db. We'll use it later
6543 //Get id and status from data
6544 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
6545 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
6546 if ($message_status == "READ") {
6547 $table = "message_read";
6548 } else {
6549 $table = "message";
6551 $this->counter++;
6552 //Save to db
6553 $status = backup_putid($this->preferences->backup_unique_code, $table,$message_id,
6554 null,$data);
6555 //Create returning info
6556 $this->info = $this->counter;
6557 //Reset temp
6558 unset($this->temp);
6560 //If we've finished a contact, xmlize it an save to db
6561 if (($this->level == 5) and ($tagName == "CONTACT")) {
6562 //Prepend XML standard header to info gathered
6563 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6564 //Call to xmlize for this portion of xml data (one MESSAGE)
6565 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6566 $data = xmlize($xml_data,0);
6567 //echo strftime ("%X",time())."<p>"; //Debug
6568 //traverse_xmlize($data); //Debug
6569 //print_object ($GLOBALS['traverse_array']); //Debug
6570 //$GLOBALS['traverse_array']=""; //Debug
6571 //Now, save data to db. We'll use it later
6572 //Get id and status from data
6573 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
6574 $this->counter++;
6575 //Save to db
6576 $status = backup_putid($this->preferences->backup_unique_code, 'message_contacts' ,$contact_id,
6577 null,$data);
6578 //Create returning info
6579 $this->info = $this->counter;
6580 //Reset temp
6581 unset($this->temp);
6585 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
6586 //Speed up a lot (avoid parse all)
6587 if ($tagName == "MESSAGES" and $this->level == 3) {
6588 $this->finished = true;
6589 $this->counter = 0;
6592 //Clear things
6593 $this->tree[$this->level] = "";
6594 $this->level--;
6595 $this->content = "";
6599 //This is the endTag handler we use where we are reading the blogs zone (todo="BLOGS")
6600 function endElementBlogs($parser, $tagName) {
6601 //Check if we are into BLOGS zone
6602 if ($this->tree[3] == "BLOGS") {
6603 //if (trim($this->content)) //Debug
6604 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6605 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
6606 //Acumulate data to info (content + close tag)
6607 //Reconvert: strip htmlchars again and trim to generate xml data
6608 if (!isset($this->temp)) {
6609 $this->temp = "";
6611 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6612 //If we've finished a blog, xmlize it an save to db
6613 if (($this->level == 4) and ($tagName == "BLOG")) {
6614 //Prepend XML standard header to info gathered
6615 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6616 //Call to xmlize for this portion of xml data (one BLOG)
6617 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6618 $data = xmlize($xml_data,0);
6619 //echo strftime ("%X",time())."<p>"; //Debug
6620 //traverse_xmlize($data); //Debug
6621 //print_object ($GLOBALS['traverse_array']); //Debug
6622 //$GLOBALS['traverse_array']=""; //Debug
6623 //Now, save data to db. We'll use it later
6624 //Get id from data
6625 $blog_id = $data["BLOG"]["#"]["ID"]["0"]["#"];
6626 $this->counter++;
6627 //Save to db
6628 $status = backup_putid($this->preferences->backup_unique_code, 'blog', $blog_id,
6629 null,$data);
6630 //Create returning info
6631 $this->info = $this->counter;
6632 //Reset temp
6633 unset($this->temp);
6637 //Stop parsing if todo = BLOGS and tagName = BLOGS (end of the tag, of course)
6638 //Speed up a lot (avoid parse all)
6639 if ($tagName == "BLOGS" and $this->level == 3) {
6640 $this->finished = true;
6641 $this->counter = 0;
6644 //Clear things
6645 $this->tree[$this->level] = "";
6646 $this->level--;
6647 $this->content = "";
6651 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
6652 function endElementQuestions($parser, $tagName) {
6653 //Check if we are into QUESTION_CATEGORIES zone
6654 if ($this->tree[3] == "QUESTION_CATEGORIES") {
6655 //if (trim($this->content)) //Debug
6656 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6657 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6658 //Acumulate data to info (content + close tag)
6659 //Reconvert: strip htmlchars again and trim to generate xml data
6660 if (!isset($this->temp)) {
6661 $this->temp = "";
6663 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6664 //If we've finished a mod, xmlize it an save to db
6665 if (($this->level == 4) and ($tagName == "QUESTION_CATEGORY")) {
6666 //Prepend XML standard header to info gathered
6667 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6668 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
6669 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6670 $data = xmlize($xml_data,0);
6671 //echo strftime ("%X",time())."<p>"; //Debug
6672 //traverse_xmlize($data); //Debug
6673 //print_object ($GLOBALS['traverse_array']); //Debug
6674 //$GLOBALS['traverse_array']=""; //Debug
6675 //Now, save data to db. We'll use it later
6676 //Get id from data
6677 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
6678 //Save to db
6679 $status = backup_putid($this->preferences->backup_unique_code,"question_categories",$category_id,
6680 null,$data);
6681 //Create returning info
6682 $ret_info = new object();
6683 $ret_info->id = $category_id;
6684 $this->info[] = $ret_info;
6685 //Reset temp
6686 unset($this->temp);
6690 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
6691 //Speed up a lot (avoid parse all)
6692 if ($tagName == "QUESTION_CATEGORIES" and $this->level == 3) {
6693 $this->finished = true;
6696 //Clear things
6697 $this->tree[$this->level] = "";
6698 $this->level--;
6699 $this->content = "";
6703 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
6704 function endElementScales($parser, $tagName) {
6705 //Check if we are into SCALES zone
6706 if ($this->tree[3] == "SCALES") {
6707 //if (trim($this->content)) //Debug
6708 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6709 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6710 //Acumulate data to info (content + close tag)
6711 //Reconvert: strip htmlchars again and trim to generate xml data
6712 if (!isset($this->temp)) {
6713 $this->temp = "";
6715 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6716 //If we've finished a scale, xmlize it an save to db
6717 if (($this->level == 4) and ($tagName == "SCALE")) {
6718 //Prepend XML standard header to info gathered
6719 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6720 //Call to xmlize for this portion of xml data (one SCALE)
6721 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6722 $data = xmlize($xml_data,0);
6723 //echo strftime ("%X",time())."<p>"; //Debug
6724 //traverse_xmlize($data); //Debug
6725 //print_object ($GLOBALS['traverse_array']); //Debug
6726 //$GLOBALS['traverse_array']=""; //Debug
6727 //Now, save data to db. We'll use it later
6728 //Get id and from data
6729 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
6730 //Save to db
6731 $status = backup_putid($this->preferences->backup_unique_code,"scale",$scale_id,
6732 null,$data);
6733 //Create returning info
6734 $ret_info = new object();
6735 $ret_info->id = $scale_id;
6736 $this->info[] = $ret_info;
6737 //Reset temp
6738 unset($this->temp);
6742 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
6743 //Speed up a lot (avoid parse all)
6744 if ($tagName == "SCALES" and $this->level == 3) {
6745 $this->finished = true;
6748 //Clear things
6749 $this->tree[$this->level] = "";
6750 $this->level--;
6751 $this->content = "";
6755 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
6756 function endElementGroups($parser, $tagName) {
6757 //Check if we are into GROUPS zone
6758 if ($this->tree[3] == "GROUPS") {
6759 //if (trim($this->content)) //Debug
6760 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6761 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6762 //Acumulate data to info (content + close tag)
6763 //Reconvert: strip htmlchars again and trim to generate xml data
6764 if (!isset($this->temp)) {
6765 $this->temp = "";
6767 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6768 //If we've finished a group, xmlize it an save to db
6769 if (($this->level == 4) and ($tagName == "GROUP")) {
6770 //Prepend XML standard header to info gathered
6771 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6772 //Call to xmlize for this portion of xml data (one GROUP)
6773 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6774 $data = xmlize($xml_data,0);
6775 //echo strftime ("%X",time())."<p>"; //Debug
6776 //traverse_xmlize($data); //Debug
6777 //print_object ($GLOBALS['traverse_array']); //Debug
6778 //$GLOBALS['traverse_array']=""; //Debug
6779 //Now, save data to db. We'll use it later
6780 //Get id and from data
6781 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
6782 //Save to db
6783 $status = backup_putid($this->preferences->backup_unique_code,"groups",$group_id,
6784 null,$data);
6785 //Create returning info
6786 $ret_info = new Object();
6787 $ret_info->id = $group_id;
6788 $this->info[] = $ret_info;
6789 //Reset temp
6790 unset($this->temp);
6794 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
6795 //Speed up a lot (avoid parse all)
6796 if ($tagName == "GROUPS" and $this->level == 3) {
6797 $this->finished = true;
6800 //Clear things
6801 $this->tree[$this->level] = "";
6802 $this->level--;
6803 $this->content = "";
6807 //This is the endTag handler we use where we are reading the groupings zone (todo="GROUPINGS")
6808 function endElementGroupings($parser, $tagName) {
6809 //Check if we are into GROUPINGS zone
6810 if ($this->tree[3] == "GROUPINGS") {
6811 //Acumulate data to info (content + close tag)
6812 //Reconvert: strip htmlchars again and trim to generate xml data
6813 if (!isset($this->temp)) {
6814 $this->temp = "";
6816 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6817 //If we've finished a group, xmlize it an save to db
6818 if (($this->level == 4) and ($tagName == "GROUPING")) {
6819 //Prepend XML standard header to info gathered
6820 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6821 //Call to xmlize for this portion of xml data (one GROUPING)
6822 $data = xmlize($xml_data,0);
6823 //Now, save data to db. We'll use it later
6824 //Get id and from data
6825 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
6826 //Save to db
6827 $status = backup_putid($this->preferences->backup_unique_code,"groupings",$grouping_id,
6828 null,$data);
6829 //Create returning info
6830 $ret_info = new Object();
6831 $ret_info->id = $grouping_id;
6832 $this->info[] = $ret_info;
6833 //Reset temp
6834 unset($this->temp);
6838 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6839 //Speed up a lot (avoid parse all)
6840 if ($tagName == "GROUPINGS" and $this->level == 3) {
6841 $this->finished = true;
6844 //Clear things
6845 $this->tree[$this->level] = "";
6846 $this->level--;
6847 $this->content = "";
6851 //This is the endTag handler we use where we are reading the groupingsgroups zone (todo="GROUPINGGROUPS")
6852 function endElementGroupingsGroups($parser, $tagName) {
6853 //Check if we are into GROUPINGSGROUPS zone
6854 if ($this->tree[3] == "GROUPINGSGROUPS") {
6855 //Acumulate data to info (content + close tag)
6856 //Reconvert: strip htmlchars again and trim to generate xml data
6857 if (!isset($this->temp)) {
6858 $this->temp = "";
6860 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6861 //If we've finished a group, xmlize it an save to db
6862 if (($this->level == 4) and ($tagName == "GROUPINGGROUP")) {
6863 //Prepend XML standard header to info gathered
6864 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6865 //Call to xmlize for this portion of xml data (one GROUPING)
6866 $data = xmlize($xml_data,0);
6867 //Now, save data to db. We'll use it later
6868 //Get id and from data
6869 $groupinggroup_id = $data["GROUPINGGROUP"]["#"]["ID"]["0"]["#"];
6870 //Save to db
6871 $status = backup_putid($this->preferences->backup_unique_code,"groupingsgroups",$groupinggroup_id,
6872 null,$data);
6873 //Create returning info
6874 $ret_info = new Object();
6875 $ret_info->id = $groupinggroup_id;
6876 $this->info[] = $ret_info;
6877 //Reset temp
6878 unset($this->temp);
6882 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6883 //Speed up a lot (avoid parse all)
6884 if ($tagName == "GROUPINGSGROUPS" and $this->level == 3) {
6885 $this->finished = true;
6888 //Clear things
6889 $this->tree[$this->level] = "";
6890 $this->level--;
6891 $this->content = "";
6895 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
6896 function endElementEvents($parser, $tagName) {
6897 //Check if we are into EVENTS zone
6898 if ($this->tree[3] == "EVENTS") {
6899 //if (trim($this->content)) //Debug
6900 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6901 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6902 //Acumulate data to info (content + close tag)
6903 //Reconvert: strip htmlchars again and trim to generate xml data
6904 if (!isset($this->temp)) {
6905 $this->temp = "";
6907 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6908 //If we've finished a event, xmlize it an save to db
6909 if (($this->level == 4) and ($tagName == "EVENT")) {
6910 //Prepend XML standard header to info gathered
6911 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6912 //Call to xmlize for this portion of xml data (one EVENT)
6913 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6914 $data = xmlize($xml_data,0);
6915 //echo strftime ("%X",time())."<p>"; //Debug
6916 //traverse_xmlize($data); //Debug
6917 //print_object ($GLOBALS['traverse_array']); //Debug
6918 //$GLOBALS['traverse_array']=""; //Debug
6919 //Now, save data to db. We'll use it later
6920 //Get id and from data
6921 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
6922 //Save to db
6923 $status = backup_putid($this->preferences->backup_unique_code,"event",$event_id,
6924 null,$data);
6925 //Create returning info
6926 $ret_info = new object();
6927 $ret_info->id = $event_id;
6928 $this->info[] = $ret_info;
6929 //Reset temp
6930 unset($this->temp);
6934 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
6935 //Speed up a lot (avoid parse all)
6936 if ($tagName == "EVENTS" and $this->level == 3) {
6937 $this->finished = true;
6940 //Clear things
6941 $this->tree[$this->level] = "";
6942 $this->level--;
6943 $this->content = "";
6947 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
6948 function endElementModules($parser, $tagName) {
6949 //Check if we are into MODULES zone
6950 if ($this->tree[3] == "MODULES") {
6951 //if (trim($this->content)) //Debug
6952 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6953 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6954 //Acumulate data to info (content + close tag)
6955 //Reconvert: strip htmlchars again and trim to generate xml data
6956 if (!isset($this->temp)) {
6957 $this->temp = "";
6959 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6960 //If we've finished a mod, xmlize it an save to db
6961 if (($this->level == 4) and ($tagName == "MOD")) {
6962 //Prepend XML standard header to info gathered
6963 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6964 //Call to xmlize for this portion of xml data (one MOD)
6965 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6966 $data = xmlize($xml_data,0);
6967 //echo strftime ("%X",time())."<p>"; //Debug
6968 //traverse_xmlize($data); //Debug
6969 //print_object ($GLOBALS['traverse_array']); //Debug
6970 //$GLOBALS['traverse_array']=""; //Debug
6971 //Now, save data to db. We'll use it later
6972 //Get id and modtype from data
6973 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
6974 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
6975 //Only if we've selected to restore it
6976 if (!empty($this->preferences->mods[$mod_type]->restore)) {
6977 //Save to db
6978 $status = backup_putid($this->preferences->backup_unique_code,$mod_type,$mod_id,
6979 null,$data);
6980 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6981 //Create returning info
6982 $ret_info = new object();
6983 $ret_info->id = $mod_id;
6984 $ret_info->modtype = $mod_type;
6985 $this->info[] = $ret_info;
6987 //Reset temp
6988 unset($this->temp);
6994 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
6995 //Speed up a lot (avoid parse all)
6996 if ($tagName == "MODULES" and $this->level == 3) {
6997 $this->finished = true;
7000 //Clear things
7001 $this->tree[$this->level] = "";
7002 $this->level--;
7003 $this->content = "";
7007 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
7008 function endElementLogs($parser, $tagName) {
7009 //Check if we are into LOGS zone
7010 if ($this->tree[3] == "LOGS") {
7011 //if (trim($this->content)) //Debug
7012 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
7013 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
7014 //Acumulate data to info (content + close tag)
7015 //Reconvert: strip htmlchars again and trim to generate xml data
7016 if (!isset($this->temp)) {
7017 $this->temp = "";
7019 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
7020 //If we've finished a log, xmlize it an save to db
7021 if (($this->level == 4) and ($tagName == "LOG")) {
7022 //Prepend XML standard header to info gathered
7023 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
7024 //Call to xmlize for this portion of xml data (one LOG)
7025 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
7026 $data = xmlize($xml_data,0);
7027 //echo strftime ("%X",time())."<p>"; //Debug
7028 //traverse_xmlize($data); //Debug
7029 //print_object ($GLOBALS['traverse_array']); //Debug
7030 //$GLOBALS['traverse_array']=""; //Debug
7031 //Now, save data to db. We'll use it later
7032 //Get id and modtype from data
7033 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
7034 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
7035 //We only save log entries from backup file if they are:
7036 // - Course logs
7037 // - User logs
7038 // - Module logs about one restored module
7039 if ($log_module == "course" or
7040 $log_module == "user" or
7041 $this->preferences->mods[$log_module]->restore) {
7042 //Increment counter
7043 $this->counter++;
7044 //Save to db
7045 $status = backup_putid($this->preferences->backup_unique_code,"log",$log_id,
7046 null,$data);
7047 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
7048 //Create returning info
7049 $this->info = $this->counter;
7051 //Reset temp
7052 unset($this->temp);
7056 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
7057 //Speed up a lot (avoid parse all)
7058 if ($tagName == "LOGS" and $this->level == 3) {
7059 $this->finished = true;
7060 $this->counter = 0;
7063 //Clear things
7064 $this->tree[$this->level] = "";
7065 $this->level--;
7066 $this->content = "";
7070 //This is the endTag default handler we use when todo is undefined
7071 function endElement($parser, $tagName) {
7072 if (trim($this->content)) //Debug
7073 echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
7074 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
7076 //Clear things
7077 $this->tree[$this->level] = "";
7078 $this->level--;
7079 $this->content = "";
7082 //This is the handler to read data contents (simple accumule it)
7083 function characterData($parser, $data) {
7084 $this->content .= $data;
7088 //This function executes the MoodleParser
7089 function restore_read_xml ($xml_file,$todo,$preferences) {
7091 $status = true;
7093 $xml_parser = xml_parser_create('UTF-8');
7094 $moodle_parser = new MoodleParser();
7095 $moodle_parser->todo = $todo;
7096 $moodle_parser->preferences = $preferences;
7097 xml_set_object($xml_parser,$moodle_parser);
7098 //Depending of the todo we use some element_handler or another
7099 if ($todo == "INFO") {
7100 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
7101 } else if ($todo == "ROLES") {
7102 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
7103 } else if ($todo == "COURSE_HEADER") {
7104 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
7105 } else if ($todo == 'BLOCKS') {
7106 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
7107 } else if ($todo == "SECTIONS") {
7108 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
7109 } else if ($todo == 'FORMATDATA') {
7110 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
7111 } else if ($todo == "METACOURSE") {
7112 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
7113 } else if ($todo == "GRADEBOOK") {
7114 if ($preferences->backup_version > 2007090500) {
7115 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
7116 } else {
7117 xml_set_element_handler($xml_parser, "startElementOldGradebook", "endElementOldGradebook");
7119 } else if ($todo == "USERS") {
7120 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
7121 } else if ($todo == "MESSAGES") {
7122 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
7123 } else if ($todo == "BLOGS") {
7124 xml_set_element_handler($xml_parser, "startElementBlogs", "endElementBlogs");
7125 } else if ($todo == "QUESTIONS") {
7126 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
7127 } else if ($todo == "SCALES") {
7128 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
7129 } else if ($todo == "GROUPS") {
7130 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
7131 } else if ($todo == "GROUPINGS") {
7132 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
7133 } else if ($todo == "GROUPINGSGROUPS") {
7134 xml_set_element_handler($xml_parser, "startElementGroupingsGroups", "endElementGroupingsGroups");
7135 } else if ($todo == "EVENTS") {
7136 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
7137 } else if ($todo == "MODULES") {
7138 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
7139 } else if ($todo == "LOGS") {
7140 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
7141 } else {
7142 //Define default handlers (must no be invoked when everything become finished)
7143 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
7145 xml_set_character_data_handler($xml_parser, "characterData");
7146 $fp = fopen($xml_file,"r")
7147 or $status = false;
7148 if ($status) {
7149 // MDL-9290 performance improvement on reading large xml
7150 $lasttime = time(); // crmas
7151 while ($data = fread($fp, 4096) and !$moodle_parser->finished) {
7153 if ((time() - $lasttime) > 5) {
7154 $lasttime = time();
7155 backup_flush(1);
7158 xml_parse($xml_parser, $data, feof($fp))
7159 or die(sprintf("XML error: %s at line %d",
7160 xml_error_string(xml_get_error_code($xml_parser)),
7161 xml_get_current_line_number($xml_parser)));
7163 fclose($fp);
7165 //Get info from parser
7166 $info = $moodle_parser->info;
7168 //Clear parser mem
7169 xml_parser_free($xml_parser);
7171 if ($status && !empty($info)) {
7172 return $info;
7173 } else {
7174 return $status;
7179 * @param string $errorstr passed by reference, if silent is true,
7180 * errorstr will be populated and this function will return false rather than calling error() or notify()
7181 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
7182 * redirect to the next step in the restore process, instead will return $backup_unique_code
7184 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
7186 global $CFG, $SESSION;
7188 //Prepend dataroot to variable to have the absolute path
7189 $file = $CFG->dataroot."/".$file;
7191 if (!defined('RESTORE_SILENTLY')) {
7192 //Start the main table
7193 echo "<table cellpadding=\"5\">";
7194 echo "<tr><td>";
7196 //Start the mail ul
7197 echo "<ul>";
7200 //Check the file exists
7201 if (!is_file($file)) {
7202 if (!defined('RESTORE_SILENTLY')) {
7203 error ("File not exists ($file)");
7204 } else {
7205 $errorstr = "File not exists ($file)";
7206 return false;
7210 //Check the file name ends with .zip
7211 if (!substr($file,-4) == ".zip") {
7212 if (!defined('RESTORE_SILENTLY')) {
7213 error ("File has an incorrect extension");
7214 } else {
7215 $errorstr = 'File has an incorrect extension';
7216 return false;
7220 //Now calculate the unique_code for this restore
7221 $backup_unique_code = time();
7223 //Now check and create the backup dir (if it doesn't exist)
7224 if (!defined('RESTORE_SILENTLY')) {
7225 echo "<li>".get_string("creatingtemporarystructures").'</li>';
7227 $status = check_and_create_backup_dir($backup_unique_code);
7228 //Empty dir
7229 if ($status) {
7230 $status = clear_backup_dir($backup_unique_code);
7233 //Now delete old data and directories under dataroot/temp/backup
7234 if ($status) {
7235 if (!defined('RESTORE_SILENTLY')) {
7236 echo "<li>".get_string("deletingolddata").'</li>';
7238 $status = backup_delete_old_data();
7241 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
7242 if ($status) {
7243 if (!defined('RESTORE_SILENTLY')) {
7244 echo "<li>".get_string("copyingzipfile").'</li>';
7246 if (! $status = backup_copy_file($file,$CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
7247 if (!defined('RESTORE_SILENTLY')) {
7248 notify("Error copying backup file. Invalid name or bad perms.");
7249 } else {
7250 $errorstr = "Error copying backup file. Invalid name or bad perms";
7251 return false;
7256 //Now unzip the file
7257 if ($status) {
7258 if (!defined('RESTORE_SILENTLY')) {
7259 echo "<li>".get_string("unzippingbackup").'</li>';
7261 if (! $status = restore_unzip ($CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
7262 if (!defined('RESTORE_SILENTLY')) {
7263 notify("Error unzipping backup file. Invalid zip file.");
7264 } else {
7265 $errorstr = "Error unzipping backup file. Invalid zip file.";
7266 return false;
7271 //Check for Blackboard backups and convert
7272 if ($status){
7273 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
7274 if (!defined('RESTORE_SILENTLY')) {
7275 echo "<li>".get_string("checkingforbbexport").'</li>';
7277 $status = blackboard_convert($CFG->dataroot."/temp/backup/".$backup_unique_code);
7280 //Now check for the moodle.xml file
7281 if ($status) {
7282 $xml_file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
7283 if (!defined('RESTORE_SILENTLY')) {
7284 echo "<li>".get_string("checkingbackup").'</li>';
7286 if (! $status = restore_check_moodle_file ($xml_file)) {
7287 if (!is_file($xml_file)) {
7288 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
7289 } else {
7290 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
7292 if (!defined('RESTORE_SILENTLY')) {
7293 notify($errorstr);
7294 } else {
7295 return false;
7300 $info = "";
7301 $course_header = "";
7303 //Now read the info tag (all)
7304 if ($status) {
7305 if (!defined('RESTORE_SILENTLY')) {
7306 echo "<li>".get_string("readinginfofrombackup").'</li>';
7308 //Reading info from file
7309 $info = restore_read_xml_info ($xml_file);
7310 //Reading course_header from file
7311 $course_header = restore_read_xml_course_header ($xml_file);
7313 if(!is_object($course_header)){
7314 // ensure we fail if there is no course header
7315 $course_header = false;
7319 if (!defined('RESTORE_SILENTLY')) {
7320 //End the main ul
7321 echo "</ul>\n";
7323 //End the main table
7324 echo "</td></tr>";
7325 echo "</table>";
7328 //We compare Moodle's versions
7329 if ($CFG->version < $info->backup_moodle_version && $status) {
7330 $message = new message();
7331 $message->serverversion = $CFG->version;
7332 $message->serverrelease = $CFG->release;
7333 $message->backupversion = $info->backup_moodle_version;
7334 $message->backuprelease = $info->backup_moodle_release;
7335 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
7339 //Now we print in other table, the backup and the course it contains info
7340 if ($info and $course_header and $status) {
7341 //First, the course info
7342 if (!defined('RESTORE_SILENTLY')) {
7343 $status = restore_print_course_header($course_header);
7345 //Now, the backup info
7346 if ($status) {
7347 if (!defined('RESTORE_SILENTLY')) {
7348 $status = restore_print_info($info);
7353 //Save course header and info into php session
7354 if ($status) {
7355 $SESSION->info = $info;
7356 $SESSION->course_header = $course_header;
7359 //Finally, a little form to continue
7360 //with some hidden fields
7361 if ($status) {
7362 if (!defined('RESTORE_SILENTLY')) {
7363 echo "<br /><div style='text-align:center'>";
7364 $hidden["backup_unique_code"] = $backup_unique_code;
7365 $hidden["launch"] = "form";
7366 $hidden["file"] = $file;
7367 $hidden["id"] = $id;
7368 print_single_button("restore.php", $hidden, get_string("continue"),"post");
7369 echo "</div>";
7371 else {
7372 if (empty($noredirect)) {
7373 redirect($CFG->wwwroot.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
7374 } else {
7375 return $backup_unique_code;
7380 if (!$status) {
7381 if (!defined('RESTORE_SILENTLY')) {
7382 error ("An error has ocurred");
7383 } else {
7384 $errorstr = "An error has occured"; // helpful! :P
7385 return false;
7388 return true;
7391 function restore_setup_for_check(&$restore,$backup_unique_code) {
7392 global $SESSION;
7393 $restore->backup_unique_code=$backup_unique_code;
7394 $restore->users = 2; // yuk
7395 $restore->course_files = $SESSION->restore->restore_course_files;
7396 $restore->site_files = $SESSION->restore->restore_site_files;
7397 if ($allmods = get_records("modules")) {
7398 foreach ($allmods as $mod) {
7399 $modname = $mod->name;
7400 $var = "restore_".$modname;
7401 //Now check that we have that module info in the backup file
7402 if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
7403 $restore->$var = 1;
7407 return true;
7410 function backup_to_restore_array($backup,$k=0) {
7411 if (is_array($backup) ) {
7412 foreach ($backup as $key => $value) {
7413 $newkey = str_replace('backup','restore',$key);
7414 $restore[$newkey] = backup_to_restore_array($value,$key);
7417 else if (is_object($backup)) {
7418 $tmp = get_object_vars($backup);
7419 foreach ($tmp as $key => $value) {
7420 $newkey = str_replace('backup','restore',$key);
7421 $restore->$newkey = backup_to_restore_array($value,$key);
7424 else {
7425 $newkey = str_replace('backup','restore',$k);
7426 $restore = $backup;
7428 return $restore;
7432 * compatibility function
7433 * checks for per-instance backups AND
7434 * older per-module backups
7435 * and returns whether userdata has been selected.
7437 function restore_userdata_selected($restore,$modname,$modid) {
7438 // check first for per instance array
7439 if (!empty($restore->mods[$modname]->granular)) { // supports per instance
7440 return array_key_exists($modid,$restore->mods[$modname]->instances)
7441 && !empty($restore->mods[$modname]->instances[$modid]->userinfo);
7444 //print_object($restore->mods[$modname]);
7445 return !empty($restore->mods[$modname]->userinfo);
7448 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
7450 global $CFG, $USER;
7451 $status = true;
7453 //Checks for the required files/functions to restore every module
7454 //and include them
7455 if ($allmods = get_records("modules") ) {
7456 foreach ($allmods as $mod) {
7457 $modname = $mod->name;
7458 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
7459 //If file exists and we have selected to restore that type of module
7460 if ((file_exists($modfile)) and !empty($restore->mods[$modname]) and ($restore->mods[$modname]->restore)) {
7461 include_once($modfile);
7466 if (!defined('RESTORE_SILENTLY')) {
7467 //Start the main table
7468 echo "<table cellpadding=\"5\">";
7469 echo "<tr><td>";
7471 //Start the main ul
7472 echo "<ul>";
7475 //Localtion of the xml file
7476 $xml_file = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/moodle.xml";
7478 //If we've selected to restore into new course
7479 //create it (course)
7480 //Saving conversion id variables into backup_tables
7481 if ($restore->restoreto == 2) {
7482 if (!defined('RESTORE_SILENTLY')) {
7483 echo '<li>'.get_string('creatingnewcourse') . '</li>';
7485 $oldidnumber = $course_header->course_idnumber;
7486 if (!$status = restore_create_new_course($restore,$course_header)) {
7487 if (!defined('RESTORE_SILENTLY')) {
7488 notify("Error while creating the new empty course.");
7489 } else {
7490 $errorstr = "Error while creating the new empty course.";
7491 return false;
7495 //Print course fullname and shortname and category
7496 if ($status) {
7497 if (!defined('RESTORE_SILENTLY')) {
7498 echo "<ul>";
7499 echo "<li>".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
7500 echo "<li>".get_string("category").": ".$course_header->category->name.'</li>';
7501 if (!empty($oldidnumber)) {
7502 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
7504 echo "</ul>";
7505 //Put the destination course_id
7507 $restore->course_id = $course_header->course_id;
7510 if ($status = restore_open_html($restore,$course_header)){
7511 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
7514 } else {
7515 $course = get_record("course","id",$restore->course_id);
7516 if ($course) {
7517 if (!defined('RESTORE_SILENTLY')) {
7518 echo "<li>".get_string("usingexistingcourse");
7519 echo "<ul>";
7520 echo "<li>".get_string("from").": ".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
7521 echo "<li>".get_string("to").": ". format_string($course->fullname) ." (".format_string($course->shortname).")".'</li>';
7522 if (($restore->deleting)) {
7523 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
7524 } else {
7525 echo "<li>".get_string("addingdatatoexisting").'</li>';
7527 echo "</ul></li>";
7529 //If we have selected to restore deleting, we do it now.
7530 if ($restore->deleting) {
7531 if (!defined('RESTORE_SILENTLY')) {
7532 echo "<li>".get_string("deletingolddata").'</li>';
7534 $status = remove_course_contents($restore->course_id,false) and
7535 delete_dir_contents($CFG->dataroot."/".$restore->course_id,"backupdata");
7536 if ($status) {
7537 //Now , this situation is equivalent to the "restore to new course" one (we
7538 //have a course record and nothing more), so define it as "to new course"
7539 $restore->restoreto = 2;
7540 } else {
7541 if (!defined('RESTORE_SILENTLY')) {
7542 notify("An error occurred while deleting some of the course contents.");
7543 } else {
7544 $errrostr = "An error occurred while deleting some of the course contents.";
7545 return false;
7549 } else {
7550 if (!defined('RESTORE_SILENTLY')) {
7551 notify("Error opening existing course.");
7552 $status = false;
7553 } else {
7554 $errorstr = "Error opening existing course.";
7555 return false;
7560 //Now create users as needed
7561 if ($status and ($restore->users == 0 or $restore->users == 1)) {
7562 if (!defined('RESTORE_SILENTLY')) {
7563 echo "<li>".get_string("creatingusers")."<br />";
7565 if (!$status = restore_create_users($restore,$xml_file)) {
7566 if (!defined('RESTORE_SILENTLY')) {
7567 notify("Could not restore users.");
7568 } else {
7569 $errorstr = "Could not restore users.";
7570 return false;
7574 //Now print info about the work done
7575 if ($status) {
7576 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
7577 where backup_code = '$restore->backup_unique_code' and
7578 table_name = 'user'");
7579 //We've records
7580 if ($recs) {
7581 $new_count = 0;
7582 $exists_count = 0;
7583 $student_count = 0;
7584 $teacher_count = 0;
7585 $counter = 0;
7586 //Iterate, filling counters
7587 foreach ($recs as $rec) {
7588 //Get full record, using backup_getids
7589 $record = backup_getid($restore->backup_unique_code,"user",$rec->old_id);
7590 if (strpos($record->info,"new") !== false) {
7591 $new_count++;
7593 if (strpos($record->info,"exists") !== false) {
7594 $exists_count++;
7596 if (strpos($record->info,"student") !== false) {
7597 $student_count++;
7598 } else if (strpos($record->info,"teacher") !== false) {
7599 $teacher_count++;
7601 //Do some output
7602 $counter++;
7603 if ($counter % 10 == 0) {
7604 if (!defined('RESTORE_SILENTLY')) {
7605 echo ".";
7606 if ($counter % 200 == 0) {
7607 echo "<br />";
7610 backup_flush(300);
7613 if (!defined('RESTORE_SILENTLY')) {
7614 //Now print information gathered
7615 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
7616 echo "<ul>";
7617 echo "<li>".get_string("students").": ".$student_count.'</li>';
7618 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
7619 echo "</ul>";
7621 } else {
7622 if (!defined('RESTORE_SILENTLY')) {
7623 notify("No users were found!");
7624 } // no need to return false here, it's recoverable.
7628 if (!defined('RESTORE_SILENTLY')) {
7629 echo "</li>";
7634 //Now create groups as needed
7635 if ($status and ($restore->groups == RESTORE_GROUPS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) {
7636 if (!defined('RESTORE_SILENTLY')) {
7637 echo "<li>".get_string("creatinggroups");
7639 if (!$status = restore_create_groups($restore,$xml_file)) {
7640 if (!defined('RESTORE_SILENTLY')) {
7641 notify("Could not restore groups!");
7642 } else {
7643 $errorstr = "Could not restore groups!";
7644 return false;
7647 if (!defined('RESTORE_SILENTLY')) {
7648 echo '</li>';
7652 //Now create groupings as needed
7653 if ($status and ($restore->groups == RESTORE_GROUPINGS_ONLY or $restore->groups == RESTORE_GROUPS_GROUPINGS)) {
7654 if (!defined('RESTORE_SILENTLY')) {
7655 echo "<li>".get_string("creatinggroupings");
7657 if (!$status = restore_create_groupings($restore,$xml_file)) {
7658 if (!defined('RESTORE_SILENTLY')) {
7659 notify("Could not restore groupings!");
7660 } else {
7661 $errorstr = "Could not restore groupings!";
7662 return false;
7665 if (!defined('RESTORE_SILENTLY')) {
7666 echo '</li>';
7670 //Now create groupingsgroups as needed
7671 if ($status and $restore->groups == RESTORE_GROUPS_GROUPINGS) {
7672 if (!defined('RESTORE_SILENTLY')) {
7673 echo "<li>".get_string("creatinggroupingsgroups");
7675 if (!$status = restore_create_groupings_groups($restore,$xml_file)) {
7676 if (!defined('RESTORE_SILENTLY')) {
7677 notify("Could not restore groups in groupings!");
7678 } else {
7679 $errorstr = "Could not restore groups in groupings!";
7680 return false;
7683 if (!defined('RESTORE_SILENTLY')) {
7684 echo '</li>';
7689 //Now create the course_sections and their associated course_modules
7690 //we have to do this after groups and groupings are restored, because we need the new groupings id
7691 if ($status) {
7692 //Into new course
7693 if ($restore->restoreto == 2) {
7694 if (!defined('RESTORE_SILENTLY')) {
7695 echo "<li>".get_string("creatingsections");
7697 if (!$status = restore_create_sections($restore,$xml_file)) {
7698 if (!defined('RESTORE_SILENTLY')) {
7699 notify("Error creating sections in the existing course.");
7700 } else {
7701 $errorstr = "Error creating sections in the existing course.";
7702 return false;
7705 if (!defined('RESTORE_SILENTLY')) {
7706 echo '</li>';
7708 //Into existing course
7709 } else if ($restore->restoreto == 0 or $restore->restoreto == 1) {
7710 if (!defined('RESTORE_SILENTLY')) {
7711 echo "<li>".get_string("checkingsections");
7713 if (!$status = restore_create_sections($restore,$xml_file)) {
7714 if (!defined('RESTORE_SILENTLY')) {
7715 notify("Error creating sections in the existing course.");
7716 } else {
7717 $errorstr = "Error creating sections in the existing course.";
7718 return false;
7721 if (!defined('RESTORE_SILENTLY')) {
7722 echo '</li>';
7724 //Error
7725 } else {
7726 if (!defined('RESTORE_SILENTLY')) {
7727 notify("Neither a new course or an existing one was specified.");
7728 $status = false;
7729 } else {
7730 $errorstr = "Neither a new course or an existing one was specified.";
7731 return false;
7736 //Now create metacourse info
7737 if ($status and $restore->metacourse) {
7738 //Only to new courses!
7739 if ($restore->restoreto == 2) {
7740 if (!defined('RESTORE_SILENTLY')) {
7741 echo "<li>".get_string("creatingmetacoursedata");
7743 if (!$status = restore_create_metacourse($restore,$xml_file)) {
7744 if (!defined('RESTORE_SILENTLY')) {
7745 notify("Error creating metacourse in the course.");
7746 } else {
7747 $errorstr = "Error creating metacourse in the course.";
7748 return false;
7751 if (!defined('RESTORE_SILENTLY')) {
7752 echo '</li>';
7758 //Now create categories and questions as needed
7759 if ($status) {
7760 include_once("$CFG->dirroot/question/restorelib.php");
7761 if (!defined('RESTORE_SILENTLY')) {
7762 echo "<li>".get_string("creatingcategoriesandquestions");
7763 echo "<ul>";
7765 if (!$status = restore_create_questions($restore,$xml_file)) {
7766 if (!defined('RESTORE_SILENTLY')) {
7767 notify("Could not restore categories and questions!");
7768 } else {
7769 $errorstr = "Could not restore categories and questions!";
7770 return false;
7773 if (!defined('RESTORE_SILENTLY')) {
7774 echo "</ul></li>";
7778 //Now create user_files as needed
7779 if ($status and ($restore->user_files)) {
7780 if (!defined('RESTORE_SILENTLY')) {
7781 echo "<li>".get_string("copyinguserfiles");
7783 if (!$status = restore_user_files($restore)) {
7784 if (!defined('RESTORE_SILENTLY')) {
7785 notify("Could not restore user files!");
7786 } else {
7787 $errorstr = "Could not restore user files!";
7788 return false;
7791 //If all is ok (and we have a counter)
7792 if ($status and ($status !== true)) {
7793 //Inform about user dirs created from backup
7794 if (!defined('RESTORE_SILENTLY')) {
7795 echo "<ul>";
7796 echo "<li>".get_string("userzones").": ".$status;
7797 echo "</li></ul>";
7800 if (!defined('RESTORE_SILENTLY')) {
7801 echo '</li>';
7805 //Now create course files as needed
7806 if ($status and ($restore->course_files)) {
7807 if (!defined('RESTORE_SILENTLY')) {
7808 echo "<li>".get_string("copyingcoursefiles");
7810 if (!$status = restore_course_files($restore)) {
7811 if (empty($status)) {
7812 notify("Could not restore course files!");
7813 } else {
7814 $errorstr = "Could not restore course files!";
7815 return false;
7818 //If all is ok (and we have a counter)
7819 if ($status and ($status !== true)) {
7820 //Inform about user dirs created from backup
7821 if (!defined('RESTORE_SILENTLY')) {
7822 echo "<ul>";
7823 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7824 echo "</ul>";
7827 if (!defined('RESTORE_SILENTLY')) {
7828 echo "</li>";
7833 //Now create site files as needed
7834 if ($status and ($restore->site_files)) {
7835 if (!defined('RESTORE_SILENTLY')) {
7836 echo "<li>".get_string('copyingsitefiles');
7838 if (!$status = restore_site_files($restore)) {
7839 if (empty($status)) {
7840 notify("Could not restore site files!");
7841 } else {
7842 $errorstr = "Could not restore site files!";
7843 return false;
7846 //If all is ok (and we have a counter)
7847 if ($status and ($status !== true)) {
7848 //Inform about user dirs created from backup
7849 if (!defined('RESTORE_SILENTLY')) {
7850 echo "<ul>";
7851 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7852 echo "</ul>";
7855 if (!defined('RESTORE_SILENTLY')) {
7856 echo "</li>";
7860 //Now create messages as needed
7861 if ($status and ($restore->messages)) {
7862 if (!defined('RESTORE_SILENTLY')) {
7863 echo "<li>".get_string("creatingmessagesinfo");
7865 if (!$status = restore_create_messages($restore,$xml_file)) {
7866 if (!defined('RESTORE_SILENTLY')) {
7867 notify("Could not restore messages!");
7868 } else {
7869 $errorstr = "Could not restore messages!";
7870 return false;
7873 if (!defined('RESTORE_SILENTLY')) {
7874 echo "</li>";
7878 //Now create blogs as needed
7879 if ($status and ($restore->blogs)) {
7880 if (!defined('RESTORE_SILENTLY')) {
7881 echo "<li>".get_string("creatingblogsinfo");
7883 if (!$status = restore_create_blogs($restore,$xml_file)) {
7884 if (!defined('RESTORE_SILENTLY')) {
7885 notify("Could not restore blogs!");
7886 } else {
7887 $errorstr = "Could not restore blogs!";
7888 return false;
7891 if (!defined('RESTORE_SILENTLY')) {
7892 echo "</li>";
7896 //Now create scales as needed
7897 if ($status) {
7898 if (!defined('RESTORE_SILENTLY')) {
7899 echo "<li>".get_string("creatingscales");
7901 if (!$status = restore_create_scales($restore,$xml_file)) {
7902 if (!defined('RESTORE_SILENTLY')) {
7903 notify("Could not restore custom scales!");
7904 } else {
7905 $errorstr = "Could not restore custom scales!";
7906 return false;
7909 if (!defined('RESTORE_SILENTLY')) {
7910 echo '</li>';
7914 //Now create events as needed
7915 if ($status) {
7916 if (!defined('RESTORE_SILENTLY')) {
7917 echo "<li>".get_string("creatingevents");
7919 if (!$status = restore_create_events($restore,$xml_file)) {
7920 if (!defined('RESTORE_SILENTLY')) {
7921 notify("Could not restore course events!");
7922 } else {
7923 $errorstr = "Could not restore course events!";
7924 return false;
7927 if (!defined('RESTORE_SILENTLY')) {
7928 echo '</li>';
7932 //Now create course modules as needed
7933 if ($status) {
7934 if (!defined('RESTORE_SILENTLY')) {
7935 echo "<li>".get_string("creatingcoursemodules");
7937 if (!$status = restore_create_modules($restore,$xml_file)) {
7938 if (!defined('RESTORE_SILENTLY')) {
7939 notify("Could not restore modules!");
7940 } else {
7941 $errorstr = "Could not restore modules!";
7942 return false;
7945 if (!defined('RESTORE_SILENTLY')) {
7946 echo '</li>';
7950 //Bring back the course blocks -- do it AFTER the modules!!!
7951 if($status) {
7952 //If we are deleting and bringing into a course or making a new course, same situation
7953 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7954 if (!defined('RESTORE_SILENTLY')) {
7955 echo '<li>'.get_string('creatingblocks');
7957 $course_header->blockinfo = !empty($course_header->blockinfo) ? $course_header->blockinfo : NULL;
7958 if (!$status = restore_create_blocks($restore, $info->backup_block_format, $course_header->blockinfo, $xml_file)) {
7959 if (!defined('RESTORE_SILENTLY')) {
7960 notify('Error while creating the course blocks');
7961 } else {
7962 $errorstr = "Error while creating the course blocks";
7963 return false;
7966 if (!defined('RESTORE_SILENTLY')) {
7967 echo '</li>';
7972 if($status) {
7973 //If we are deleting and bringing into a course or making a new course, same situation
7974 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7975 if (!defined('RESTORE_SILENTLY')) {
7976 echo '<li>'.get_string('courseformatdata');
7978 if (!$status = restore_set_format_data($restore, $xml_file)) {
7979 $error = "Error while setting the course format data";
7980 if (!defined('RESTORE_SILENTLY')) {
7981 notify($error);
7982 } else {
7983 $errorstr=$error;
7984 return false;
7987 if (!defined('RESTORE_SILENTLY')) {
7988 echo '</li>';
7993 //Now create log entries as needed
7994 if ($status and ($restore->logs)) {
7995 if (!defined('RESTORE_SILENTLY')) {
7996 echo "<li>".get_string("creatinglogentries");
7998 if (!$status = restore_create_logs($restore,$xml_file)) {
7999 if (!defined('RESTORE_SILENTLY')) {
8000 notify("Could not restore logs!");
8001 } else {
8002 $errorstr = "Could not restore logs!";
8003 return false;
8006 if (!defined('RESTORE_SILENTLY')) {
8007 echo '</li>';
8011 //Now, if all is OK, adjust the instance field in course_modules !!
8012 //this also calculates the final modinfo information so, after this,
8013 //code needing it can be used (like role_assignments. MDL-13740)
8014 if ($status) {
8015 if (!defined('RESTORE_SILENTLY')) {
8016 echo "<li>".get_string("checkinginstances");
8018 if (!$status = restore_check_instances($restore)) {
8019 if (!defined('RESTORE_SILENTLY')) {
8020 notify("Could not adjust instances in course_modules!");
8021 } else {
8022 $errorstr = "Could not adjust instances in course_modules!";
8023 return false;
8026 if (!defined('RESTORE_SILENTLY')) {
8027 echo '</li>';
8031 //Now, if all is OK, adjust activity events
8032 if ($status) {
8033 if (!defined('RESTORE_SILENTLY')) {
8034 echo "<li>".get_string("refreshingevents");
8036 if (!$status = restore_refresh_events($restore)) {
8037 if (!defined('RESTORE_SILENTLY')) {
8038 notify("Could not refresh events for activities!");
8039 } else {
8040 $errorstr = "Could not refresh events for activities!";
8041 return false;
8044 if (!defined('RESTORE_SILENTLY')) {
8045 echo '</li>';
8049 //Now, if all is OK, adjust inter-activity links
8050 if ($status) {
8051 if (!defined('RESTORE_SILENTLY')) {
8052 echo "<li>".get_string("decodinginternallinks");
8054 if (!$status = restore_decode_content_links($restore)) {
8055 if (!defined('RESTORE_SILENTLY')) {
8056 notify("Could not decode content links!");
8057 } else {
8058 $errorstr = "Could not decode content links!";
8059 return false;
8062 if (!defined('RESTORE_SILENTLY')) {
8063 echo '</li>';
8067 //Now, with backup files prior to version 2005041100,
8068 //convert all the wiki texts in the course to markdown
8069 if ($status && $restore->backup_version < 2005041100) {
8070 if (!defined('RESTORE_SILENTLY')) {
8071 echo "<li>".get_string("convertingwikitomarkdown");
8073 if (!$status = restore_convert_wiki2markdown($restore)) {
8074 if (!defined('RESTORE_SILENTLY')) {
8075 notify("Could not convert wiki texts to markdown!");
8076 } else {
8077 $errorstr = "Could not convert wiki texts to markdown!";
8078 return false;
8081 if (!defined('RESTORE_SILENTLY')) {
8082 echo '</li>';
8086 //Now create gradebook as needed -- AFTER modules and blocks!!!
8087 if ($status) {
8088 if ($restore->backup_version > 2007090500) {
8089 if (!defined('RESTORE_SILENTLY')) {
8090 echo "<li>".get_string("creatinggradebook");
8092 if (!$status = restore_create_gradebook($restore,$xml_file)) {
8093 if (!defined('RESTORE_SILENTLY')) {
8094 notify("Could not restore gradebook!");
8095 } else {
8096 $errorstr = "Could not restore gradebook!";
8097 return false;
8101 if (!defined('RESTORE_SILENTLY')) {
8102 echo '</li>';
8105 } else {
8106 // for moodle versions before 1.9, those grades need to be converted to use the new gradebook
8107 // this code needs to execute *after* the course_modules are sorted out
8108 if (!defined('RESTORE_SILENTLY')) {
8109 echo "<li>".get_string("migratinggrades");
8112 /// force full refresh of grading data before migration == crete all items first
8113 if (!$status = restore_migrate_old_gradebook($restore,$xml_file)) {
8114 if (!defined('RESTORE_SILENTLY')) {
8115 notify("Could not migrate gradebook!");
8116 } else {
8117 $errorstr = "Could not migrade gradebook!";
8118 return false;
8121 if (!defined('RESTORE_SILENTLY')) {
8122 echo '</li>';
8125 /// force full refresh of grading data after all items are created
8126 grade_force_full_regrading($restore->course_id);
8127 grade_grab_course_grades($restore->course_id);
8130 /*******************************************************************************
8131 ************* Restore of Roles and Capabilities happens here ******************
8132 *******************************************************************************/
8133 // try to restore roles even when restore is going to fail - teachers might have
8134 // at least some role assigned - this is not correct though
8135 $status = restore_create_roles($restore, $xml_file) && $status;
8136 $status = restore_roles_settings($restore, $xml_file) && $status;
8138 //Now if all is OK, update:
8139 // - course modinfo field
8140 // - categories table
8141 // - add user as teacher
8142 if ($status) {
8143 if (!defined('RESTORE_SILENTLY')) {
8144 echo "<li>".get_string("checkingcourse");
8146 //categories table
8147 $course = get_record("course","id",$restore->course_id);
8148 fix_course_sortorder();
8149 // Check if the user has course update capability in the newly restored course
8150 // there is no need to load his capabilities again, because restore_roles_settings
8151 // would have loaded it anyway, if there is any assignments.
8152 // fix for MDL-6831
8153 $newcontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
8154 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
8155 // fix for MDL-9065, use the new config setting if exists
8156 if ($CFG->creatornewroleid) {
8157 role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id);
8158 } else {
8159 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM))) {
8160 if ($legacyteacher = array_shift($legacyteachers)) {
8161 role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id);
8163 } else {
8164 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
8168 if (!defined('RESTORE_SILENTLY')) {
8169 echo '</li>';
8173 //Cleanup temps (files and db)
8174 if ($status) {
8175 if (!defined('RESTORE_SILENTLY')) {
8176 echo "<li>".get_string("cleaningtempdata");
8178 if (!$status = clean_temp_data ($restore)) {
8179 if (!defined('RESTORE_SILENTLY')) {
8180 notify("Could not clean up temporary data from files and database");
8181 } else {
8182 $errorstr = "Could not clean up temporary data from files and database";
8183 return false;
8186 if (!defined('RESTORE_SILENTLY')) {
8187 echo '</li>';
8191 // this is not a critical check - the result can be ignored
8192 if (restore_close_html($restore)){
8193 if (!defined('RESTORE_SILENTLY')) {
8194 echo '<li>Closing the Restorelog.html file.</li>';
8197 else {
8198 if (!defined('RESTORE_SILENTLY')) {
8199 notify("Could not close the restorelog.html file");
8203 if (!defined('RESTORE_SILENTLY')) {
8204 //End the main ul
8205 echo "</ul>";
8207 //End the main table
8208 echo "</td></tr>";
8209 echo "</table>";
8212 return $status;
8214 //Create, open and write header of the html log file
8215 function restore_open_html($restore,$course_header) {
8217 global $CFG;
8219 $status = true;
8221 //Open file for writing
8222 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
8223 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
8224 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
8226 $status = check_dir_exists($dest_dir,true);
8227 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8228 //Add the stylesheet
8229 $stylesheetshtml = '';
8230 foreach ($CFG->stylesheets as $stylesheet) {
8231 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
8233 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
8234 $languagehtml = get_html_lang($dir=true);
8236 //Write the header in the new logging file
8237 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
8238 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
8239 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
8240 fwrite ($restorelog_file,"<head>");
8241 fwrite ($restorelog_file,$stylesheetshtml);
8242 fwrite ($restorelog_file,"<title>".$course_header->course_shortname." Restored </title>");
8243 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
8244 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname." The FullName is now - ".$course_header->course_fullname."<br/><br/>");
8245 $startdate = addslashes($course_header->course_startdate);
8246 $date = usergetdate($startdate);
8247 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
8248 $startdate += $restore->course_startdateoffset;
8249 $date = usergetdate($startdate);
8250 fwrite ($restorelog_file,"&nbsp;&nbsp;&nbsp;This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
8252 if ($status) {
8253 return $restorelog_file;
8254 } else {
8255 return false;
8258 //Create & close footer of the html log file
8259 function restore_close_html($restore) {
8261 global $CFG;
8263 $status = true;
8265 //Open file for writing
8266 //First, check that course_id/backupdata folder exists in CFG->dataroot
8267 $dest_dir = $CFG->dataroot."/".$restore->course_id."/backupdata";
8268 $status = check_dir_exists($dest_dir, true, true);
8269 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8270 //Write the footer to close the logging file
8271 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
8272 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
8274 if ($status) {
8275 return $restorelog_file;
8276 } else {
8277 return false;
8281 /********************** Roles and Capabilities Related Functions *******************************/
8283 /* Yu: Note recovering of role assignments/overrides need to take place after
8284 users have been recovered, i.e. after we get their new_id, and after all
8285 roles have been recreated or mapped. Contexts can be created on the fly.
8286 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
8287 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
8288 once roles and users have been restored.
8292 * This function restores all the needed roles for this course
8293 * i.e. roles with an assignment in any of the mods or blocks,
8294 * roles assigned on any user (e.g. parent role) and roles
8295 * assigned at course levle
8296 * This function should check for duplicate roles first
8297 * It isn't now, just overwriting
8299 function restore_create_roles($restore, $xmlfile) {
8300 if (!defined('RESTORE_SILENTLY')) {
8301 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
8303 $info = restore_read_xml_roles($xmlfile);
8305 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
8307 // the following code creates new roles
8308 // but we could use more intelligent detection, and role mapping
8309 // get role mapping info from $restore
8310 $rolemappings = array();
8312 if (!empty($restore->rolesmapping)) {
8313 $rolemappings = $restore->rolesmapping;
8315 // $info->roles will be empty for backups pre 1.7
8316 if (isset($info->roles) && $info->roles) {
8318 foreach ($info->roles as $oldroleid=>$roledata) {
8320 if (empty($restore->rolesmapping)) {
8321 // if this is empty altogether, we came from import or there's no roles used in course at all
8322 // in this case, write the same oldid as this is the same site
8323 // no need to do mapping
8324 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
8325 $oldroleid); // adding a new id
8326 continue; // do not create additonal roles;
8328 // first we check if the roles are in the mappings
8329 // if so, we just do a mapping i.e. update oldids table
8330 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
8331 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
8332 $rolemappings[$oldroleid]); // adding a new id
8334 } else {
8336 // code to make new role name/short name if same role name or shortname exists
8337 $fullname = $roledata->name;
8338 $shortname = $roledata->shortname;
8339 $currentfullname = "";
8340 $currentshortname = "";
8341 $counter = 0;
8343 do {
8344 if ($counter) {
8345 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
8346 $suffixshort = "_".$counter;
8347 } else {
8348 $suffixfull = "";
8349 $suffixshort = "";
8351 $currentfullname = $fullname.$suffixfull;
8352 // Limit the size of shortname - database column accepts <= 100 chars
8353 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
8354 $coursefull = get_record("role","name",addslashes($currentfullname));
8355 $courseshort = get_record("role","shortname",addslashes($currentshortname));
8356 $counter++;
8357 } while ($coursefull || $courseshort);
8359 $roledata->name = $currentfullname;
8360 $roledata->shortname= $currentshortname;
8362 // done finding a unique name
8364 $newroleid = create_role(addslashes($roledata->name),addslashes($roledata->shortname),'');
8365 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
8366 $newroleid); // adding a new id
8367 foreach ($roledata->capabilities as $capability) {
8369 $roleinfo = new object();
8370 $roleinfo = (object)$capability;
8371 $roleinfo->contextid = $sitecontext->id;
8372 $roleinfo->capability = $capability->name;
8373 $roleinfo->roleid = $newroleid;
8375 insert_record('role_capabilities', $roleinfo);
8378 /// Now, restore role nameincourse (only if the role had nameincourse in backup)
8379 if (!empty($roledata->nameincourse)) {
8380 $newrole = backup_getid($restore->backup_unique_code, 'role', $oldroleid); /// Look for target role
8381 $coursecontext = get_context_instance(CONTEXT_COURSE, $restore->course_id); /// Look for target context
8382 if (!empty($newrole->new_id) && !empty($coursecontext)) {
8383 /// Check the role hasn't any custom name in context
8384 if (!record_exists('role_names', 'roleid', $newrole->new_id, 'contextid', $coursecontext->id)) {
8385 $rolename = new object();
8386 $rolename->roleid = $newrole->new_id;
8387 $rolename->contextid = $coursecontext->id;
8388 $rolename->name = addslashes($roledata->nameincourse);
8390 insert_record('role_names', $rolename);
8396 return true;
8400 * this function restores role assignments and role overrides
8401 * in course/user/block/mod level, it passed through
8402 * the xml file again
8404 function restore_roles_settings($restore, $xmlfile) {
8405 // data pulls from course, mod, user, and blocks
8407 /*******************************************************
8408 * Restoring from course level assignments *
8409 *******************************************************/
8410 if (!defined('RESTORE_SILENTLY')) {
8411 echo "<li>".get_string("creatingcourseroles").'</li>';
8413 $course = restore_read_xml_course_header($xmlfile);
8415 if (!isset($restore->rolesmapping)) {
8416 $isimport = true; // course import from another course, or course with no role assignments
8417 } else {
8418 $isimport = false; // course restore with role assignments
8421 if (!empty($course->roleassignments) && !$isimport) {
8422 $courseassignments = $course->roleassignments;
8424 foreach ($courseassignments as $oldroleid => $courseassignment) {
8425 restore_write_roleassignments($restore, $courseassignment->assignments, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
8428 /*****************************************************
8429 * Restoring from course level overrides *
8430 *****************************************************/
8432 if (!empty($course->roleoverrides) && !$isimport) {
8433 $courseoverrides = $course->roleoverrides;
8434 foreach ($courseoverrides as $oldroleid => $courseoverride) {
8435 // if not importing into exiting course, or creating new role, we are ok
8436 // local course overrides to be respected (i.e. restored course overrides ignored)
8437 if ($restore->restoreto != 1 || empty($restore->rolesmapping[$oldroleid])) {
8438 restore_write_roleoverrides($restore, $courseoverride->overrides, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
8443 /*******************************************************
8444 * Restoring role assignments/overrdies *
8445 * from module level assignments *
8446 *******************************************************/
8448 if (!defined('RESTORE_SILENTLY')) {
8449 echo "<li>".get_string("creatingmodroles").'</li>';
8451 $sections = restore_read_xml_sections($xmlfile);
8452 $secs = $sections->sections;
8454 foreach ($secs as $section) {
8455 if (isset($section->mods)) {
8456 foreach ($section->mods as $modid=>$mod) {
8457 if (isset($mod->roleassignments) && !$isimport) {
8458 foreach ($mod->roleassignments as $oldroleid=>$modassignment) {
8459 restore_write_roleassignments($restore, $modassignment->assignments, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
8462 // role overrides always applies, in import or backup/restore
8463 if (isset($mod->roleoverrides)) {
8464 foreach ($mod->roleoverrides as $oldroleid=>$modoverride) {
8465 restore_write_roleoverrides($restore, $modoverride->overrides, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
8472 /*************************************************
8473 * Restoring assignments from blocks level *
8474 * role assignments/overrides *
8475 *************************************************/
8477 if ($restore->restoreto != 1) { // skip altogether if restoring to exisitng course by adding
8478 if (!defined('RESTORE_SILENTLY')) {
8479 echo "<li>".get_string("creatingblocksroles").'</li>';
8481 $blocks = restore_read_xml_blocks($restore, $xmlfile);
8482 if (isset($blocks->instances)) {
8483 foreach ($blocks->instances as $instance) {
8484 if (isset($instance->roleassignments) && !$isimport) {
8485 foreach ($instance->roleassignments as $oldroleid=>$blockassignment) {
8486 restore_write_roleassignments($restore, $blockassignment->assignments, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
8490 // likewise block overrides should always be restored like mods
8491 if (isset($instance->roleoverrides)) {
8492 foreach ($instance->roleoverrides as $oldroleid=>$blockoverride) {
8493 restore_write_roleoverrides($restore, $blockoverride->overrides, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
8499 /************************************************
8500 * Restoring assignments from userid level *
8501 * role assignments/overrides *
8502 ************************************************/
8503 if (!defined('RESTORE_SILENTLY')) {
8504 echo "<li>".get_string("creatinguserroles").'</li>';
8506 $info = restore_read_xml_users($restore, $xmlfile);
8507 if (!empty($info->users) && !$isimport) { // no need to restore user assignments for imports (same course)
8508 //For each user, take its info from backup_ids
8509 foreach ($info->users as $userid) {
8510 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
8511 if (isset($rec->info->roleassignments)) {
8512 foreach ($rec->info->roleassignments as $oldroleid=>$userassignment) {
8513 restore_write_roleassignments($restore, $userassignment->assignments, "user", CONTEXT_USER, $userid, $oldroleid);
8516 if (isset($rec->info->roleoverrides)) {
8517 foreach ($rec->info->roleoverrides as $oldroleid=>$useroverride) {
8518 restore_write_roleoverrides($restore, $useroverride->overrides, "user", CONTEXT_USER, $userid, $oldroleid);
8524 return true;
8527 // auxillary function to write role assignments read from xml to db
8528 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
8530 $role = backup_getid($restore->backup_unique_code, "role", $oldroleid);
8532 foreach ($assignments as $assignment) {
8534 $olduser = backup_getid($restore->backup_unique_code,"user",$assignment->userid);
8535 //Oh dear, $olduser... can be an object, $obj->string or bool!
8536 if (!$olduser || (is_string($olduser->info) && $olduser->info == "notincourse")) { // it's possible that user is not in the course
8537 continue;
8539 $assignment->userid = $olduser->new_id; // new userid here
8540 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$assignment->modifierid);
8541 $assignment->modifierid = !empty($oldmodifier->new_id) ? $oldmodifier->new_id : 0; // new modifier id here
8542 $assignment->roleid = $role->new_id; // restored new role id
8544 // hack to make the correct contextid for course level imports
8545 if ($contextlevel == CONTEXT_COURSE) {
8546 $oldinstance->new_id = $restore->course_id;
8547 } else {
8548 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
8551 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
8552 $assignment->contextid = $newcontext->id; // new context id
8553 // might already have same assignment
8554 role_assign($assignment->roleid, $assignment->userid, 0, $assignment->contextid, $assignment->timestart, $assignment->timeend, $assignment->hidden, $assignment->enrol, $assignment->timemodified);
8559 // auxillary function to write role assignments read from xml to db
8560 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
8562 // it is possible to have an override not relevant to this course context.
8563 // should be ignored(?)
8564 if (!$role = backup_getid($restore->backup_unique_code, "role", $oldroleid)) {
8565 return null;
8568 foreach ($overrides as $override) {
8569 $override->capability = $override->name;
8570 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$override->modifierid);
8571 $override->modifierid = !empty($oldmodifier->new_id)?$oldmodifier->new_id:0; // new modifier id here
8572 $override->roleid = $role->new_id; // restored new role id
8574 // hack to make the correct contextid for course level imports
8575 if ($contextlevel == CONTEXT_COURSE) {
8576 $oldinstance->new_id = $restore->course_id;
8577 } else {
8578 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
8581 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
8582 $override->contextid = $newcontext->id; // new context id
8583 // use assign capability instead so we can add context to context_rel
8584 assign_capability($override->capability, $override->permission, $override->roleid, $override->contextid);
8587 //write activity date changes to the html log file, and update date values in the the xml array
8588 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
8590 global $CFG;
8591 $openlog = false;
8593 // loop through time fields in $TAGS
8594 foreach ($TAGS as $TAG) {
8596 // check $TAG has a sensible value
8597 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
8599 if ($openlog==false) {
8600 $openlog = true; // only come through here once
8602 // open file for writing
8603 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
8604 check_dir_exists($course_dir, true);
8605 $restorelog = fopen("$course_dir/restorelog.html", "a");
8607 // start output for this record
8608 $msg = new stdClass();
8609 $msg->recordtype = $recordtype;
8610 $msg->recordname = $xml[$NAMETAG][0]['#'];
8611 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
8614 // write old date to $restorelog
8615 $value = $xml[$TAG][0]['#'];
8616 $date = usergetdate($value);
8618 $msg = new stdClass();
8619 $msg->TAG = $TAG;
8620 $msg->weekday = $date['weekday'];
8621 $msg->mday = $date['mday'];
8622 $msg->month = $date['month'];
8623 $msg->year = $date['year'];
8624 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
8626 // write new date to $restorelog
8627 $value += $restore->course_startdateoffset;
8628 $date = usergetdate($value);
8630 $msg = new stdClass();
8631 $msg->TAG = $TAG;
8632 $msg->weekday = $date['weekday'];
8633 $msg->mday = $date['mday'];
8634 $msg->month = $date['month'];
8635 $msg->year = $date['year'];
8636 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
8638 // update $value in $xml tree for calling module
8639 $xml[$TAG][0]['#'] = "$value";
8642 // close the restore log, if it was opened
8643 if ($openlog) {
8644 fclose($restorelog);