2 //Functions used in restore
4 require_once($CFG->libdir
.'/gradelib.php');
7 * Group backup/restore constants, 0.
9 define('RESTORE_GROUPS_NONE', 0);
12 * Group backup/restore constants, 1.
14 define('RESTORE_GROUPS_ONLY', 1);
17 * Group backup/restore constants, 2.
19 define('RESTORE_GROUPINGS_ONLY', 2);
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) {
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
48 $status = strpos($first_chars,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
49 if ($status !== false) {
50 $status = strpos($first_chars,"<MOODLE_BACKUP>");
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) {
65 //Take all modules in backup
66 $modules = $restore->mods
;
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
);
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) {
92 if (!defined('RESTORE_SILENTLY')) {
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)) {
108 if (!defined('RESTORE_SILENTLY')) {
112 // Recode links in section summaries.
113 $sections = get_records('course_sections', 'course', $restore->course_id
, 'id', 'id,summary');
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)) {
127 if (!defined('RESTORE_SILENTLY')) {
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')) {
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')) {
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')) {
178 if (!defined('RESTORE_SILENTLY')) {
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
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);
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) {
223 if (!defined('RESTORE_SILENTLY')) {
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);
240 if (!defined('RESTORE_SILENTLY')) {
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) {
255 $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
257 preg_match_all($searchstring,$content,$foundset);
258 //If found, then we are going to look for its new id (in backup tables)
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
270 $result= preg_replace($searchstring,' $1:'.$rec->new_id
.'($2)',$result);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
435 //This function read the xml file and store its data from the modules in
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);
445 //This function read the xml file and store its data from the logs in
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);
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);
462 //This function prints the contents from the info parammeter passed
463 function restore_print_info ($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");
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
;
481 $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
482 $tab[1][1] = $info->backup_moodle_release
." (".$info->backup_moodle_version
.")";
484 $tab[2][0] = "<b>".get_string("backupversion").":</b>";
485 $tab[2][1] = $info->backup_backup_release
." (".$info->backup_backup_version
.")";
487 $tab[3][0] = "<b>".get_string("backupdate").":</b>";
488 $tab[3][1] = userdate($info->backup_date
);
490 print_heading(get_string("backup").":");
492 //Print backup general info
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
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");
509 if ($mod->userinfo
== "true") {
510 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
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
) {
518 $tab[$elem][0] = $instance->name
;
519 if ($instance->userinfo
== 'true') {
520 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
522 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
531 $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
532 if ($info->backup_metacourse
== "true") {
533 $tab[$elem][1] = get_string("yes");
535 $tab[$elem][1] = get_string("no");
539 $tab[$elem][0] = "<b>".get_string("users").":</b>";
540 $tab[$elem][1] = get_string($info->backup_users
);
543 $tab[$elem][0] = "<b>".get_string("logs").":</b>";
544 if ($info->backup_logs
== "true") {
545 $tab[$elem][1] = get_string("yes");
547 $tab[$elem][1] = get_string("no");
551 $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
552 if ($info->backup_user_files
== "true") {
553 $tab[$elem][1] = get_string("yes");
555 $tab[$elem][1] = get_string("no");
559 $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
560 if ($info->backup_course_files
== "true") {
561 $tab[$elem][1] = get_string("yes");
563 $tab[$elem][1] = get_string("no");
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");
571 $tab[$elem][1] = get_string("no");
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");
579 $tab[$elem][1] = get_string("no");
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');
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');
601 print_heading(get_string("backupdetails").":");
602 //Print backup general info
611 //This function prints the contents from the course_header parammeter passed
612 function restore_print_course_header ($course_header) {
615 if ($course_header) {
616 $table = new object();
617 //This is tha align to every ingo table
618 $table->align
= array ("right","left");
620 $table->width
= "70%";
621 //Put interesting course header in table
623 $tab[0][0] = "<b>".get_string("name").":</b>";
624 $tab[0][1] = $course_header->course_fullname
." (".$course_header->course_shortname
.")";
626 $tab[1][0] = "<b>".get_string("summary").":</b>";
627 $tab[1][1] = $course_header->course_summary
;
630 print_heading(get_string("course").":");
631 //Print backup course header info
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) {
647 $fullname = $course_header->course_fullname
;
648 $shortname = $course_header->course_shortname
;
649 $currentfullname = "";
650 $currentshortname = "";
652 //Iteratere while the name exists
655 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
656 $suffixshort = "_".$counter;
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));
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
687 $category = get_record("course_categories","name",addslashes($course_header->category
->name
));
690 //If no exists, get category id 1
692 $category = get_record("course_categories","id","1");
695 //If category 1 doesn'exists, lets create the course category (get it from backup file)
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
710 $course_header->category
->id
= $category->id
;
711 $course_header->category
->name
= $category->name
;
712 //Error, cannot locate category
714 $course_header->category
->id
= 0;
715 $course_header->category
->name
= get_string("unknowncategory");
719 //Create the course_object
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;
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)) {
803 //Now insert the record
804 $newid = insert_record("course",$course);
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;
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) {
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);
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) {
842 foreach($blocks as $blockname) {
843 if(!isset($blockrecords[$blockname])) {
844 // We don't know anything about this block!
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;
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)) {
867 } else if($backup_block_format == 'instances') {
868 $status = restore_create_block_instances($restore,$xml_file);
875 //This function creates all the block_instances from xml when restoring in a
877 function restore_create_block_instances($restore,$xml_file) {
882 if (!file_exists($xml_file)) {
887 $info = restore_read_xml_blocks($restore,$xml_file);
890 if(empty($info->instances
)) {
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
) {
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
918 $instance->pageid
= $getid->new_id
;
921 // Not invented here ;-)
926 // do not restore activity blocks if disabled
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...
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
])) {
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
];
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
;
986 if ($instance->id
= insert_record('block_instance', $instance)) {
987 // Create block instance
988 if (!$blockobj = block_instance($instance->name
, $instance)) {
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)) {
1002 // Save oldid after block restore process because info will be over-written with blank string
1004 backup_putid ($restore->backup_unique_code
,"block_instance",$oldid,$instance->id
);
1012 //Get an object for the block and tell it it's been restored so it can update dates
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;
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) {
1040 if (!file_exists($xml_file)) {
1045 $info = restore_read_xml_sections($xml_file);
1047 //Put the info in the DB, recoding ids and saving the in backup tables
1052 //For each, section, save it to db
1053 foreach ($info->sections
as $key => $sect) {
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
1063 if ($restore->restoreto
== 2) {
1064 //Save it to db (only if restoring to new course)
1065 $newid = insert_record("course_sections",$section);
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
1073 $rec = get_record("course_sections","course",$restore->course_id
,
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.
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);
1087 $rec->sequence
= "";
1090 $sequence = $rec->sequence
;
1093 //save old and new section id
1094 backup_putid ($restore->backup_unique_code
,"course_sections",$key,$newid);
1098 //If all is OK, go with associated mods
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;
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
);
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
;
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
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));
1159 //save old and new module id
1160 //In the info field, we save the original instance of the module
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;
1169 //Now, calculate the sequence field
1172 $sequence .= ",".$newidmod;
1174 $sequence = $newidmod;
1185 //If all is OK, update sequence field in course_sections
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);
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) {
1207 if (!file_exists($xml_file)) {
1210 //Load data from XML to info
1211 if(!($info = restore_read_xml_formatdata($xml_file))) {
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
)) {
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)) {
1225 require_once($file);
1226 $function=$format.'_restore_format_data';
1227 if(!function_exists($function)) {
1230 return $function($restore,$info->format_data
);
1233 // If we got here then there's no data, but that's cool
1237 //This function creates all the metacourse data from xml, notifying
1238 //about each incidence
1239 function restore_create_metacourse($restore,$xml_file) {
1245 if (!file_exists($xml_file)) {
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) {
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
);
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
1275 $dbmetacourse->child_course
= $dbcourse->id
;
1276 $dbmetacourse->parent_course
= $restore->course_id
;
1277 $status = insert_record ('course_meta',$dbmetacourse);
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) {
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
);
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
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
);
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>';
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>';
1333 * This function migrades all the pre 1.9 gradebook data from xml
1335 function restore_migrate_old_gradebook($restore,$xml_file) {
1340 if (!file_exists($xml_file)) {
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
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 ;-)
1365 $restoreall = false;
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
);
1384 if (!defined('RESTORE_SILENTLY')) {
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",
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
);
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",
1422 $cat_count = count($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
);
1428 //Now get completed xmlized object
1429 $info = $data->info
;
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;
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
1452 $grade_category = null;
1455 /// now, restore grade_items
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
);
1480 or ($grade_item->itemtype
== 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule
, $olditeminstance))) {
1481 // module instance not selected when restored using granular
1486 //Now process grade excludes
1487 if (empty($ite_info['#']['GRADE_EXCEPTIONS'])) {
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');
1499 $grade_grade->insert('restore');
1509 if (!defined('RESTORE_SILENTLY')) {
1518 * This function creates all the gradebook data from xml
1520 function restore_create_gradebook($restore,$xml_file) {
1525 if (!file_exists($xml_file)) {
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
1538 if (empty($CFG->disablegradehistory
) and isset($info->gradebook_histories
) and $info->gradebook_histories
== "true") {
1539 $restore_histories = true;
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
);
1556 $restoreall = false;
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);
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
)) {
1584 } else if (!empty($restore->mods
[$itemmodule]->instances
[$olditeminstance]->restore
)) {
1587 // at least one activity should not be restored - do not restore categories and manual items at all
1588 $restoreall = false;
1598 if (!defined('RESTORE_SILENTLY')) {
1602 // array of restored categories - speedup ;-)
1603 $cached_categories = array();
1604 $outcomes = array();
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",
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
);
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'",
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
);
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;
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)) {
1667 $dbrec->courseid
= null;
1670 $dbrec->courseid
= $restore->course_id
;
1673 // no permission to add site outcomes
1674 $dbrec->courseid
= $restore->course_id
;
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
1705 if (!defined('RESTORE_SILENTLY')) {
1706 echo '<li>'.get_string('gradeitems','grades').'</li>';
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
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
);
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) {
1729 $oldcat = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
1730 if (!$cdata = backup_getid($restore->backup_unique_code
,'grade_categories',$oldcat)) {
1733 $cinfo = $cdata->info
;
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();
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
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;
1812 if ($itemtype != 'mod' and (!$restoreall or $importing)) {
1813 // not extra gradebook stuff if restoring individual activities or something already there
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
1832 // keep in sync with activity idnumber
1833 $dbrec->idnumber
= $cm->idnumber
;
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])) {
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');
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
1896 or ($grade_item->itemtype
== 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule
, $olditeminstance))) {
1897 // module instance not selected when restored using granular
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
);
1947 if ($counter %
20 == 0) {
1948 if (!defined('RESTORE_SILENTLY')) {
1950 if ($counter %
400 == 0) {
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>';
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'",
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
);
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
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
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)) {
2043 foreach ($paths as $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);
2067 //Increment counters
2070 if ($counter %
1 == 0) {
2071 if (!defined('RESTORE_SILENTLY')) {
2073 if ($counter %
20 == 0) {
2084 // process histories
2085 if ($gghcount && $status) {
2086 if (!defined('RESTORE_SILENTLY')) {
2087 echo '<li>'.get_string('gradegradeshistory','grades').'</li>';
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'",
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
);
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
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
)) {
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);
2158 //Increment counters
2161 if ($counter %
1 == 0) {
2162 if (!defined('RESTORE_SILENTLY')) {
2164 if ($counter %
20 == 0) {
2175 // process histories
2177 if ($gihcount && $status) {
2178 if (!defined('RESTORE_SILENTLY')) {
2179 echo '<li>'.get_string('gradeitemshistory','grades').'</li>';
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'",
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
);
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
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
)) {
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
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
2248 $category = backup_getid($restore->backup_unique_code
,'grade_categories', $iteminstance);
2249 $dbrec->iteminstance
= $category->new_id
;
2251 // otherwise we can safely ignore this grade item and subsequent
2252 // grade_raws, grade_finals etc
2255 } elseif ($dbrec->itemtype
== 'course') { // We don't restore course type to avoid duplicate course items
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
;
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);
2301 //Increment counters
2304 if ($counter %
1 == 0) {
2305 if (!defined('RESTORE_SILENTLY')) {
2307 if ($counter %
20 == 0) {
2318 // process histories
2319 if ($gohcount && $status) {
2320 if (!defined('RESTORE_SILENTLY')) {
2321 echo '<li>'.get_string('gradeoutcomeshistory','grades').'</li>';
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'",
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
);
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
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);
2366 //Increment counters
2369 if ($counter %
1 == 0) {
2370 if (!defined('RESTORE_SILENTLY')) {
2372 if ($counter %
20 == 0) {
2384 if (!defined('RESTORE_SILENTLY')) {
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) {
2396 require_once ($CFG->dirroot
.'/tag/lib.php');
2400 if (!file_exists($xml_file)) {
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
2424 foreach ($info->users
as $userid) {
2425 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
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)) {
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(
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
;
2478 // fast url-to-id lookups
2479 if (isset($mnethosts[$user->mnethosturl
])) {
2480 $user->mnethostid
= $mnethosts[$user->mnethosturl
]->id
;
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
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
);
2496 $user_exists = false;
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
2530 //Unset the id because it's going to be inserted with a new one
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
)) {
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
2544 if (empty($user->auth
)) {
2545 if ($CFG->registerauth
== 'email') {
2546 $user->auth
= 'email';
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;
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)) {
2568 //We are going to create the user
2569 //The structure is exactly as we need
2571 $newid = insert_record ("user", addslashes_recursive($user));
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
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);
2602 //Only put status in backup_ids
2603 $currinfo = $currinfo."needed,";
2604 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
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
;
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'],
2634 $user->roles
['teacher']->timestart
,
2635 $user->roles
['teacher']->timeend
,
2637 $user->roles
['teacher']->enrol
);
2641 // non editting teacher
2642 role_assign($rolesmapping['defaultteacher'],
2646 $user->roles
['teacher']->timestart
,
2647 $user->roles
['teacher']->timeend
,
2649 $user->roles
['teacher']->enrol
);
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
;
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'],
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
2716 /// if tags are enabled and there are user tags
2717 if (!empty($CFG->usetags
) && isset($user->user_tags
)) {
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);
2742 if ($counter %
10 == 0) {
2743 if (!defined('RESTORE_SILENTLY')) {
2745 if ($counter %
200 == 0) {
2751 } /// End of loop over all the users loaded from xml
2757 //This function creates all the structures messages and contacts
2758 function restore_create_messages($restore,$xml_file) {
2764 if (!file_exists($xml_file)) {
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
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) {
2782 if (!defined('RESTORE_SILENTLY')) {
2785 //Number of records to get in every chunk
2786 $recordset_size = 4;
2790 if (!defined('RESTORE_SILENTLY')) {
2791 echo '<li>'.get_string('unreadmessages','message').'</li>';
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);
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
);
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
);
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
);
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
);
2833 $status = insert_record('message',$dbrec);
2835 //Duplicate. Do nothing
2840 if ($counter %
10 == 0) {
2841 if (!defined('RESTORE_SILENTLY')) {
2843 if ($counter %
200 == 0) {
2856 if (!defined('RESTORE_SILENTLY')) {
2857 echo '<li>'.get_string('readmessages','message').'</li>';
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);
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
);
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
);
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
);
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
);
2900 $status = insert_record('message_read',$dbrec);
2902 //Duplicate. Do nothing
2907 if ($counter %
10 == 0) {
2908 if (!defined('RESTORE_SILENTLY')) {
2910 if ($counter %
200 == 0) {
2922 if ($contactcount) {
2923 if (!defined('RESTORE_SILENTLY')) {
2924 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
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);
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
);
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
);
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
);
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
);
2961 $status = insert_record('message_contacts',$dbrec);
2963 //Duplicate. Do nothing
2968 if ($counter %
10 == 0) {
2969 if (!defined('RESTORE_SILENTLY')) {
2971 if ($counter %
200 == 0) {
2981 if (!defined('RESTORE_SILENTLY')) {
2992 //This function creates all the structures for blogs and blog tags
2993 function restore_create_blogs($restore,$xml_file) {
2999 if (!file_exists($xml_file)) {
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
3010 //Count how many we have
3011 $blogcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'blog');
3013 //Number of records to get in every chunk
3014 $recordset_size = 4;
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);
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
);
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
);
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
);
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'];
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
3093 if ($counter %
10 == 0) {
3094 if (!defined('RESTORE_SILENTLY')) {
3096 if ($counter %
200 == 0) {
3113 //This function creates all the categories and questions
3115 function restore_create_questions($restore,$xml_file) {
3121 if (!file_exists($xml_file)) {
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
3133 if ($info !== true) {
3134 $status = $status && restore_question_categories($info, $restore);
3142 //This function creates all the scales
3143 function restore_create_scales($restore,$xml_file) {
3149 if (!file_exists($xml_file)) {
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
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
);
3170 $create_scale = false;
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;
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
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
);
3215 $sca->userid
= $user->new_id
;
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);
3223 //get current scale id
3224 $newid = $sca_db->id
;
3227 //We have the newid, update backup_ids
3228 backup_putid($restore->backup_unique_code
,"scale",
3229 $scale->id
, $newid);
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
) {
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;
3268 //This function creates all the groups
3269 function restore_create_groups($restore,$xml_file) {
3274 if (!file_exists($xml_file)) {
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)
3283 } else if ($groups === 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
);
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']['#']);
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);
3333 //get current group id
3334 $newid = $gro_db->id
;
3338 //We have the newid, update backup_ids
3339 backup_putid($restore->backup_unique_code
,"groups", $group->id
, $newid);
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)) {
3356 //Now, restore group_files
3358 $status = restore_group_files($restore);
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.
3371 //Get the members array
3372 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
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']['#']);
3391 //We have to recode the userid field
3392 if (!$user = backup_getid($restore->backup_unique_code
,"user",$group_member->userid
)) {
3393 debugging("group membership can not be restored, user id $group_member->userid not present in backup");
3394 // do not not block the restore
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)) {
3407 if (($i+
1) %
50 == 0) {
3408 if (!defined('RESTORE_SILENTLY')) {
3410 if (($i+
1) %
1000 == 0) {
3421 //This function creates all the groupings
3422 function restore_create_groupings($restore,$xml_file) {
3425 if (!file_exists($xml_file)) {
3429 if (!$groupings = restore_read_xml_groupings($restore,$xml_file)) {
3432 } else if ($groupings === 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
;
3458 //The structure is equal to the db, so insert the grouping
3459 if (!$newid = insert_record('groupings', $gro)) {
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
);
3478 set_field('course', 'defaultgroupingid', 0, 'id', $course->id
);
3485 //This function creates all the groupingsgroups
3486 function restore_create_groupings_groups($restore,$xml_file) {
3489 if (!file_exists($xml_file)) {
3493 if (!$groupingsgroups = restore_read_xml_groupings_groups($restore,$xml_file)) {
3496 } else if ($groupingsgroups === 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
)) {
3518 if (!$group = backup_getid($restore->backup_unique_code
,"groups",$gro_member->groupid
)) {
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)) {
3536 //This function creates all the course events
3537 function restore_create_events($restore,$xml_file) {
3543 if (!file_exists($xml_file)) {
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
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
);
3566 $create_event = false;
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']['#']);
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
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
);
3613 $eve->userid
= $user->new_id
;
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
);
3622 $eve->groupid
= $group->new_id
;
3624 //Assign it to group 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
);
3643 // update the record to contain the correct repeatid
3644 update_record('event',$eve);
3647 //get current event id
3648 $newid = $eve_db->id
;
3651 //We have the newid, update backup_ids
3652 backup_putid($restore->backup_unique_code
,"event",
3653 $event->id
, $newid);
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) {
3681 } else if ($content === '') {
3683 } else if (is_numeric($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
3701 //This function restores the userfiles from the temp (user_files) directory to the
3702 //dataroot/users directory
3703 function restore_user_files($restore) {
3711 // 'users' is the old users folder, 'user' is the new one, with a new hierarchy. Detect which one is here and treat accordingly
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))) {
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";
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);
3750 if ($counter %
2 == 0) {
3751 if (!defined('RESTORE_SILENTLY')) {
3753 if ($counter %
40 == 0) {
3763 //If status is ok and whe have dirs created, returns counter to inform
3764 if ($status and $counter) {
3771 //This function restores the groupfiles from the temp (group_files) directory to the
3772 //dataroot/groups directory
3773 function restore_group_files($restore) {
3781 //First, we check to "groups" exists and create is as necessary
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);
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",
3800 //If that group exists in backup_ids
3802 if (!file_exists($dest_dir."/".$data->new_id
)) {
3803 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id
,true);
3807 if ($counter %
2 == 0) {
3808 if (!defined('RESTORE_SILENTLY')) {
3810 if ($counter %
40 == 0) {
3820 //If status is ok and whe have dirs created, returns counter to inform
3821 if ($status and $counter) {
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) {
3838 //First, we check to "course_id" exists and create is as necessary
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);
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);
3861 if ($counter %
2 == 0) {
3862 if (!defined('RESTORE_SILENTLY')) {
3864 if ($counter %
40 == 0) {
3873 //If status is ok and whe have dirs created, returns counter to inform
3874 if ($status and $counter) {
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) {
3891 //First, we check to "course_id" exists and create is as necessary
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);
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);
3914 if ($counter %
2 == 0) {
3915 if (!defined('RESTORE_SILENTLY')) {
3917 if ($counter %
40 == 0) {
3926 //If status is ok and whe have dirs created, returns counter to inform
3927 if ($status and $counter) {
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) {
3942 if (!file_exists($xml_file)) {
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)
3954 if ($info !== true) {
3955 if (!defined('RESTORE_SILENTLY')) {
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);
3969 //Something was wrong. Function should exist.
3974 if (!defined('RESTORE_SILENTLY')) {
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) {
3990 //Number of records to get in every chunk
3991 $recordset_size = 4;
3992 //Counter, points to current record
3994 //To count all the recods to restore
3999 if (!file_exists($xml_file)) {
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);
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
);
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
);
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
);
4053 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
4054 $dblog->cmid
= $cm->new_id
;
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") {
4066 $stat = restore_log_user($restore,$dblog);
4068 //It's a module log,
4069 $stat = restore_log_module($restore,$dblog);
4075 if ($counter %
10 == 0) {
4076 if (!defined('RESTORE_SILENTLY')) {
4078 if ($counter %
200 == 0) {
4086 //We never should arrive here
4087 $counter = $count_logs;
4096 //This function inserts a course log record, calculating the URL field as necessary
4097 function restore_log_course($restore,$log) {
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
) {
4107 $log->url
= "view.php?id=".$log->course
;
4108 $log->info
= $log->course
;
4112 $log->url
= "view.php?id=".$log->course
;
4116 //recode the info field (it's the user id)
4117 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
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;
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);
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);
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;
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);
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);
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;
4169 $log->url
= "view.php?id=".$log->course
;
4173 $log->url
= "edit.php?id=".$log->course
;
4178 //recode the info field (it's the user id)
4179 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4181 $log->info
= $user->new_id
;
4182 $log->url
= "view.php?id=".$log->course
;
4187 //recode the info field (it's the user id)
4188 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4190 $log->info
= $user->new_id
;
4191 $log->url
= "view.php?id=".$log->course
;
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);
4201 $secid = $sec->new_id
;
4202 //Now I have everything so reconstruct url and info
4203 $log->url
= "editsection.php?id=".$secid;
4208 $log->url
= "view.php?id=".$log->course
;
4213 $log->url
= "recent.php?id=".$log->course
;
4218 $log->url
= "report/log/index.php?id=".$log->course
;
4219 $log->info
= $log->course
;
4223 $log->url
= "report/log/live.php?id=".$log->course
;
4224 $log->info
= $log->course
;
4227 case "report outline":
4228 $log->url
= "report/outline/index.php?id=".$log->course
;
4229 $log->info
= $log->course
;
4232 case "report participation":
4233 $log->url
= "report/participation/index.php?id=".$log->course
;
4234 $log->info
= $log->course
;
4237 case "report stats":
4238 $log->url
= "report/stats/index.php?id=".$log->course
;
4239 $log->info
= $log->course
;
4243 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
4247 //echo "After transformations<br />"; //Debug
4248 //print_object($log); //Debug
4250 //Now if $toinsert is set, insert the record
4252 //echo "Inserting record<br />"; //Debug
4253 $status = insert_record("log",$log);
4258 //This function inserts a user log record, calculating the URL field as necessary
4259 function restore_log_user($restore,$log) {
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
) {
4269 //recode the info field (it's the user id)
4270 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4272 $log->info
= $user->new_id
;
4273 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
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
);
4281 $log->info
= $user->new_id
;
4282 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4287 //recode the info field (it's the user id)
4288 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4290 $log->info
= $user->new_id
;
4291 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4296 //recode the info field (it's the user id)
4297 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4299 $log->info
= $user->new_id
;
4300 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4305 $log->url
= "view.php?id=".$log->course
;
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);
4314 $user = backup_getid($restore->backup_unique_code
,"user",$userid);
4317 $log->url
= "view.php?id=".$user->new_id
."&course=".$log->course
;
4322 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
4326 //echo "After transformations<br />"; //Debug
4327 //print_object($log); //Debug
4329 //Now if $toinsert is set, insert the record
4331 //echo "Inserting record<br />"; //Debug
4332 $status = insert_record("log",$log);
4337 //This function inserts a module log record, calculating the URL field as necessary
4338 function restore_log_module($restore,$log) {
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)) {
4350 $log = $function($restore,$log);
4351 //If everything is ok, mark the insert flag
4357 //echo "After transformations<br />"; //Debug
4358 //print_object($log); //Debug
4360 //Now if $toinsert is set, insert the record
4362 //echo "Inserting record<br />"; //Debug
4363 $status = insert_record("log",$log);
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) {
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
);
4388 //We know the module type id. Get the name from modules
4389 $type = get_record("modules","id",$module->module
);
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
);
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);
4408 // MDL-14326 remove empty course modules instance's (credit goes to John T. Macklin from Remote Learner)
4409 $course_modules_inst_zero = get_records_sql("SELECT id, course, instance
4410 FROM {$CFG->prefix}course_modules
4411 WHERE id = '$cm_module->new_id' AND
4414 if($course_modules_inst_zero){ // Clean up the invalid instances
4415 foreach($course_modules_inst_zero as $course_modules_inst){
4416 delete_records('course_modules', 'id',$course_modules_inst->id
);
4421 /// Finally, calculate modinfo cache.
4422 rebuild_course_cache($restore->course_id
);
4429 //=====================================================================================
4431 //== XML Functions (SAX) ==
4433 //=====================================================================================
4435 //This is the class used to do all the xml parse
4436 class MoodleParser
{
4438 var $level = 0; //Level we are
4439 var $counter = 0; //Counter
4440 var $tree = array(); //Array of levels we are
4441 var $content = ""; //Content under current level
4442 var $todo = ""; //What we hav to do when parsing
4443 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
4444 var $temp = ""; //Temp storage.
4445 var $preferences = ""; //Preferences about what to load !!
4446 var $finished = false; //Flag to say xml_parse to stop
4448 //This function is used to get the current contents property value
4449 //They are trimed (and converted from utf8 if needed)
4450 function getContents() {
4451 return trim($this->content
);
4454 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4455 function startElementInfo($parser, $tagName, $attrs) {
4456 //Refresh properties
4458 $this->tree
[$this->level
] = $tagName;
4460 //Output something to avoid browser timeouts...
4463 //Check if we are into INFO zone
4464 //if ($this->tree[2] == "INFO") //Debug
4465 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4468 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4469 function startElementRoles($parser, $tagName, $attrs) {
4470 //Refresh properties
4472 $this->tree
[$this->level
] = $tagName;
4474 //Output something to avoid browser timeouts...
4477 //Check if we are into INFO zone
4478 //if ($this->tree[2] == "INFO") //Debug
4479 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4483 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
4484 function startElementCourseHeader($parser, $tagName, $attrs) {
4485 //Refresh properties
4487 $this->tree
[$this->level
] = $tagName;
4489 //Output something to avoid browser timeouts...
4492 //Check if we are into COURSE_HEADER zone
4493 //if ($this->tree[3] == "HEADER") //Debug
4494 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4497 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
4498 function startElementBlocks($parser, $tagName, $attrs) {
4499 //Refresh properties
4501 $this->tree
[$this->level
] = $tagName;
4503 //Output something to avoid browser timeouts...
4506 //Check if we are into BLOCKS zone
4507 //if ($this->tree[3] == "BLOCKS") //Debug
4508 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4510 //If we are under a BLOCK tag under a BLOCKS zone, accumule it
4511 if (isset($this->tree
[4]) and isset($this->tree
[3])) { //
4512 if ($this->tree
[4] == "BLOCK" and $this->tree
[3] == "BLOCKS") {
4513 if (!isset($this->temp
)) {
4516 $this->temp
.= "<".$tagName.">";
4521 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
4522 function startElementSections($parser, $tagName, $attrs) {
4523 //Refresh properties
4525 $this->tree
[$this->level
] = $tagName;
4527 //Output something to avoid browser timeouts...
4530 //Check if we are into SECTIONS zone
4531 //if ($this->tree[3] == "SECTIONS") //Debug
4532 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4535 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4536 function startElementFormatData($parser, $tagName, $attrs) {
4537 //Refresh properties
4539 $this->tree
[$this->level
] = $tagName;
4541 //Output something to avoid browser timeouts...
4544 //Accumulate all the data inside this tag
4545 if (isset($this->tree
[3]) && $this->tree
[3] == "FORMATDATA") {
4546 if (!isset($this->temp
)) {
4549 $this->temp
.= "<".$tagName.">";
4552 //Check if we are into FORMATDATA zone
4553 //if ($this->tree[3] == "FORMATDATA") //Debug
4554 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4557 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4558 function startElementMetacourse($parser, $tagName, $attrs) {
4560 //Refresh properties
4562 $this->tree
[$this->level
] = $tagName;
4564 //Output something to avoid browser timeouts...
4567 //Check if we are into METACOURSE zone
4568 //if ($this->tree[3] == "METACOURSE") //Debug
4569 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4572 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4573 function startElementGradebook($parser, $tagName, $attrs) {
4575 //Refresh properties
4577 $this->tree
[$this->level
] = $tagName;
4579 //Output something to avoid browser timeouts...
4582 //Check if we are into GRADEBOOK zone
4583 //if ($this->tree[3] == "GRADEBOOK") //Debug
4584 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4586 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4587 if (isset($this->tree
[5]) and isset($this->tree
[3])) {
4588 if (($this->tree
[5] == "GRADE_ITEM" ||
$this->tree
[5] == "GRADE_CATEGORY" ||
$this->tree
[5] == "GRADE_LETTER" ||
$this->tree
[5] == "GRADE_OUTCOME" ||
$this->tree
[5] == "GRADE_OUTCOMES_COURSE" ||
$this->tree
[5] == "GRADE_CATEGORIES_HISTORY" ||
$this->tree
[5] == "GRADE_GRADES_HISTORY" ||
$this->tree
[5] == "GRADE_TEXT_HISTORY" ||
$this->tree
[5] == "GRADE_ITEM_HISTORY" ||
$this->tree
[5] == "GRADE_OUTCOME_HISTORY") && ($this->tree
[3] == "GRADEBOOK")) {
4590 if (!isset($this->temp
)) {
4593 $this->temp
.= "<".$tagName.">";
4598 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4599 function startElementOldGradebook($parser, $tagName, $attrs) {
4601 //Refresh properties
4603 $this->tree
[$this->level
] = $tagName;
4605 //Output something to avoid browser timeouts...
4608 //Check if we are into GRADEBOOK zone
4609 //if ($this->tree[3] == "GRADEBOOK") //Debug
4610 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4612 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4613 if (isset($this->tree
[5]) and isset($this->tree
[3])) {
4614 if (($this->tree
[5] == "GRADE_PREFERENCE" ||
$this->tree
[5] == "GRADE_LETTER" ||
$this->tree
[5] == "GRADE_CATEGORY" ) && ($this->tree
[3] == "GRADEBOOK")) {
4615 if (!isset($this->temp
)) {
4618 $this->temp
.= "<".$tagName.">";
4624 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
4625 function startElementUsers($parser, $tagName, $attrs) {
4626 //Refresh properties
4628 $this->tree
[$this->level
] = $tagName;
4630 //Check if we are into USERS zone
4631 //if ($this->tree[3] == "USERS") //Debug
4632 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4635 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
4636 function startElementMessages($parser, $tagName, $attrs) {
4637 //Refresh properties
4639 $this->tree
[$this->level
] = $tagName;
4641 //Output something to avoid browser timeouts...
4644 //Check if we are into MESSAGES zone
4645 //if ($this->tree[3] == "MESSAGES") //Debug
4646 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4648 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
4649 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4650 if (($this->tree
[4] == "MESSAGE" ||
(isset($this->tree
[5]) && $this->tree
[5] == "CONTACT" )) and ($this->tree
[3] == "MESSAGES")) {
4651 if (!isset($this->temp
)) {
4654 $this->temp
.= "<".$tagName.">";
4659 //This is the startTag handler we use where we are reading the blogs zone (todo="BLOGS")
4660 function startElementBlogs($parser, $tagName, $attrs) {
4661 //Refresh properties
4663 $this->tree
[$this->level
] = $tagName;
4665 //Output something to avoid browser timeouts...
4668 //Check if we are into BLOGS zone
4669 //if ($this->tree[3] == "BLOGS") //Debug
4670 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4672 //If we are under a BLOG tag under a BLOGS zone, accumule it
4673 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4674 if ($this->tree
[4] == "BLOG" and $this->tree
[3] == "BLOGS") {
4675 if (!isset($this->temp
)) {
4678 $this->temp
.= "<".$tagName.">";
4683 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4684 function startElementQuestions($parser, $tagName, $attrs) {
4685 //Refresh properties
4687 $this->tree
[$this->level
] = $tagName;
4689 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
4690 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
4693 //Output something to avoid browser timeouts...
4696 //Check if we are into QUESTION_CATEGORIES zone
4697 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
4698 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4700 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
4701 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4702 if (($this->tree
[4] == "QUESTION_CATEGORY") and ($this->tree
[3] == "QUESTION_CATEGORIES")) {
4703 if (!isset($this->temp
)) {
4706 $this->temp
.= "<".$tagName.">";
4711 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
4712 function startElementScales($parser, $tagName, $attrs) {
4713 //Refresh properties
4715 $this->tree
[$this->level
] = $tagName;
4717 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
4718 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
4721 //Output something to avoid browser timeouts...
4724 //Check if we are into SCALES zone
4725 //if ($this->tree[3] == "SCALES") //Debug
4726 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4728 //If we are under a SCALE tag under a SCALES zone, accumule it
4729 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4730 if (($this->tree
[4] == "SCALE") and ($this->tree
[3] == "SCALES")) {
4731 if (!isset($this->temp
)) {
4734 $this->temp
.= "<".$tagName.">";
4739 function startElementGroups($parser, $tagName, $attrs) {
4740 //Refresh properties
4742 $this->tree
[$this->level
] = $tagName;
4744 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
4745 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
4748 //Output something to avoid browser timeouts...
4751 //Check if we are into GROUPS zone
4752 //if ($this->tree[3] == "GROUPS") //Debug
4753 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4755 //If we are under a GROUP tag under a GROUPS zone, accumule it
4756 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4757 if (($this->tree
[4] == "GROUP") and ($this->tree
[3] == "GROUPS")) {
4758 if (!isset($this->temp
)) {
4761 $this->temp
.= "<".$tagName.">";
4766 function startElementGroupings($parser, $tagName, $attrs) {
4767 //Refresh properties
4769 $this->tree
[$this->level
] = $tagName;
4771 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
4772 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
4775 //Output something to avoid browser timeouts...
4778 //Check if we are into GROUPINGS zone
4779 //if ($this->tree[3] == "GROUPINGS") //Debug
4780 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4782 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
4783 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4784 if (($this->tree
[4] == "GROUPING") and ($this->tree
[3] == "GROUPINGS")) {
4785 if (!isset($this->temp
)) {
4788 $this->temp
.= "<".$tagName.">";
4793 function startElementGroupingsGroups($parser, $tagName, $attrs) {
4794 //Refresh properties
4796 $this->tree
[$this->level
] = $tagName;
4798 //if ($tagName == "GROUPINGGROUP" && $this->tree[3] == "GROUPINGSGROUPS") { //Debug
4799 // echo "<P>GROUPINGSGROUP: ".strftime ("%X",time()),"-"; //Debug
4802 //Output something to avoid browser timeouts...
4805 //Check if we are into GROUPINGSGROUPS zone
4806 //if ($this->tree[3] == "GROUPINGSGROUPS") //Debug
4807 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4809 //If we are under a GROUPINGGROUP tag under a GROUPINGSGROUPS zone, accumule it
4810 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4811 if (($this->tree
[4] == "GROUPINGGROUP") and ($this->tree
[3] == "GROUPINGSGROUPS")) {
4812 if (!isset($this->temp
)) {
4815 $this->temp
.= "<".$tagName.">";
4820 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
4821 function startElementEvents($parser, $tagName, $attrs) {
4822 //Refresh properties
4824 $this->tree
[$this->level
] = $tagName;
4826 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
4827 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
4830 //Output something to avoid browser timeouts...
4833 //Check if we are into EVENTS zone
4834 //if ($this->tree[3] == "EVENTS") //Debug
4835 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4837 //If we are under a EVENT tag under a EVENTS zone, accumule it
4838 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4839 if (($this->tree
[4] == "EVENT") and ($this->tree
[3] == "EVENTS")) {
4840 if (!isset($this->temp
)) {
4843 $this->temp
.= "<".$tagName.">";
4848 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
4849 function startElementModules($parser, $tagName, $attrs) {
4850 //Refresh properties
4852 $this->tree
[$this->level
] = $tagName;
4854 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
4855 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
4858 //Output something to avoid browser timeouts...
4861 //Check if we are into MODULES zone
4862 //if ($this->tree[3] == "MODULES") //Debug
4863 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4865 //If we are under a MOD tag under a MODULES zone, accumule it
4866 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4867 if (($this->tree
[4] == "MOD") and ($this->tree
[3] == "MODULES")) {
4868 if (!isset($this->temp
)) {
4871 $this->temp
.= "<".$tagName.">";
4876 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
4877 function startElementLogs($parser, $tagName, $attrs) {
4878 //Refresh properties
4880 $this->tree
[$this->level
] = $tagName;
4882 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
4883 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
4886 //Output something to avoid browser timeouts...
4889 //Check if we are into LOGS zone
4890 //if ($this->tree[3] == "LOGS") //Debug
4891 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4893 //If we are under a LOG tag under a LOGS zone, accumule it
4894 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4895 if (($this->tree
[4] == "LOG") and ($this->tree
[3] == "LOGS")) {
4896 if (!isset($this->temp
)) {
4899 $this->temp
.= "<".$tagName.">";
4904 //This is the startTag default handler we use when todo is undefined
4905 function startElement($parser, $tagName, $attrs) {
4907 $this->tree
[$this->level
] = $tagName;
4909 //Output something to avoid browser timeouts...
4912 echo $this->level
.str_repeat(" ",$this->level
*2)."<".$tagName."><br />\n"; //Debug
4915 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
4916 function endElementInfo($parser, $tagName) {
4917 //Check if we are into INFO zone
4918 if ($this->tree
[2] == "INFO") {
4919 //if (trim($this->content)) //Debug
4920 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4921 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4922 //Dependig of different combinations, do different things
4923 if ($this->level
== 3) {
4926 $this->info
->backup_name
= $this->getContents();
4928 case "MOODLE_VERSION":
4929 $this->info
->backup_moodle_version
= $this->getContents();
4931 case "MOODLE_RELEASE":
4932 $this->info
->backup_moodle_release
= $this->getContents();
4934 case "BACKUP_VERSION":
4935 $this->info
->backup_backup_version
= $this->getContents();
4937 case "BACKUP_RELEASE":
4938 $this->info
->backup_backup_release
= $this->getContents();
4941 $this->info
->backup_date
= $this->getContents();
4943 case "ORIGINAL_WWWROOT":
4944 $this->info
->original_wwwroot
= $this->getContents();
4946 case "MNET_EXTERNALUSERS":
4947 $this->info
->mnet_externalusers
= $this->getContents();
4951 if ($this->tree
[3] == "DETAILS") {
4952 if ($this->level
== 4) {
4955 $this->info
->backup_metacourse
= $this->getContents();
4958 $this->info
->backup_users
= $this->getContents();
4961 $this->info
->backup_logs
= $this->getContents();
4964 $this->info
->backup_user_files
= $this->getContents();
4967 $this->info
->backup_course_files
= $this->getContents();
4970 $this->info
->backup_site_files
= $this->getContents();
4972 case "GRADEBOOKHISTORIES":
4973 $this->info
->gradebook_histories
= $this->getContents();
4976 $this->info
->backup_messages
= $this->getContents();
4979 $this->info
->backup_blogs
= $this->getContents();
4982 $this->info
->backup_block_format
= $this->getContents();
4986 if ($this->level
== 5) {
4989 $this->info
->tempName
= $this->getContents();
4992 $this->info
->mods
[$this->info
->tempName
]->backup
= $this->getContents();
4995 $this->info
->mods
[$this->info
->tempName
]->userinfo
= $this->getContents();
4999 if ($this->level
== 7) {
5002 $this->info
->tempId
= $this->getContents();
5003 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->id
= $this->info
->tempId
;
5006 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->name
= $this->getContents();
5009 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->backup
= $this->getContents();
5012 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->userinfo
= $this->getContents();
5019 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
5020 //Speed up a lot (avoid parse all)
5021 if ($tagName == "INFO") {
5022 $this->finished
= true;
5026 $this->tree
[$this->level
] = "";
5028 $this->content
= "";
5032 function endElementRoles($parser, $tagName) {
5033 //Check if we are into INFO zone
5034 if ($this->tree
[2] == "ROLES") {
5036 if ($this->tree
[3] == "ROLE") {
5037 if ($this->level
== 4) {
5039 case "ID": // this is the old id
5040 $this->info
->tempid
= $this->getContents();
5041 $this->info
->roles
[$this->info
->tempid
]->id
= $this->info
->tempid
;
5044 $this->info
->roles
[$this->info
->tempid
]->name
= $this->getContents();;
5047 $this->info
->roles
[$this->info
->tempid
]->shortname
= $this->getContents();;
5049 case "NAMEINCOURSE": // custom name of the role in course
5050 $this->info
->roles
[$this->info
->tempid
]->nameincourse
= $this->getContents();;
5054 if ($this->level
== 6) {
5057 $this->info
->tempcapname
= $this->getContents();
5058 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->name
= $this->getContents();
5061 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->permission
= $this->getContents();
5063 case "TIMEMODIFIED":
5064 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->timemodified
= $this->getContents();
5067 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->modifierid
= $this->getContents();
5074 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
5075 //Speed up a lot (avoid parse all)
5076 if ($tagName == "ROLES") {
5077 $this->finished
= true;
5081 $this->tree
[$this->level
] = "";
5083 $this->content
= "";
5087 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
5088 function endElementCourseHeader($parser, $tagName) {
5089 //Check if we are into COURSE_HEADER zone
5090 if ($this->tree
[3] == "HEADER") {
5091 //if (trim($this->content)) //Debug
5092 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5093 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5094 //Dependig of different combinations, do different things
5095 if ($this->level
== 4) {
5098 $this->info
->course_id
= $this->getContents();
5101 $this->info
->course_password
= $this->getContents();
5104 $this->info
->course_fullname
= $this->getContents();
5107 $this->info
->course_shortname
= $this->getContents();
5110 $this->info
->course_idnumber
= $this->getContents();
5113 $this->info
->course_summary
= $this->getContents();
5116 $this->info
->course_format
= $this->getContents();
5119 $this->info
->course_showgrades
= $this->getContents();
5122 $this->info
->blockinfo
= $this->getContents();
5125 $this->info
->course_newsitems
= $this->getContents();
5128 $this->info
->course_teacher
= $this->getContents();
5131 $this->info
->course_teachers
= $this->getContents();
5134 $this->info
->course_student
= $this->getContents();
5137 $this->info
->course_students
= $this->getContents();
5140 $this->info
->course_guest
= $this->getContents();
5143 $this->info
->course_startdate
= $this->getContents();
5146 $this->info
->course_numsections
= $this->getContents();
5148 //case "SHOWRECENT": INFO: This is out in 1.3
5149 // $this->info->course_showrecent = $this->getContents();
5152 $this->info
->course_maxbytes
= $this->getContents();
5155 $this->info
->course_showreports
= $this->getContents();
5158 $this->info
->course_groupmode
= $this->getContents();
5160 case "GROUPMODEFORCE":
5161 $this->info
->course_groupmodeforce
= $this->getContents();
5163 case "DEFAULTGROUPINGID":
5164 $this->info
->course_defaultgroupingid
= $this->getContents();
5167 $this->info
->course_lang
= $this->getContents();
5170 $this->info
->course_theme
= $this->getContents();
5173 $this->info
->course_cost
= $this->getContents();
5176 $this->info
->course_currency
= $this->getContents();
5179 $this->info
->course_marker
= $this->getContents();
5182 $this->info
->course_visible
= $this->getContents();
5184 case "HIDDENSECTIONS":
5185 $this->info
->course_hiddensections
= $this->getContents();
5188 $this->info
->course_timecreated
= $this->getContents();
5190 case "TIMEMODIFIED":
5191 $this->info
->course_timemodified
= $this->getContents();
5194 $this->info
->course_metacourse
= $this->getContents();
5196 case "EXPIRENOTIFY":
5197 $this->info
->course_expirynotify
= $this->getContents();
5199 case "NOTIFYSTUDENTS":
5200 $this->info
->course_notifystudents
= $this->getContents();
5202 case "EXPIRYTHRESHOLD":
5203 $this->info
->course_expirythreshold
= $this->getContents();
5206 $this->info
->course_enrollable
= $this->getContents();
5208 case "ENROLSTARTDATE":
5209 $this->info
->course_enrolstartdate
= $this->getContents();
5211 case "ENROLENDDATE":
5212 $this->info
->course_enrolenddate
= $this->getContents();
5215 $this->info
->course_enrolperiod
= $this->getContents();
5219 if ($this->tree
[4] == "CATEGORY") {
5220 if ($this->level
== 5) {
5223 $this->info
->category
->id
= $this->getContents();
5226 $this->info
->category
->name
= $this->getContents();
5232 if ($this->tree
[4] == "ROLES_ASSIGNMENTS") {
5233 if ($this->level
== 6) {
5236 $this->info
->tempname
= $this->getContents();
5239 $this->info
->tempshortname
= $this->getContents();
5242 $this->info
->tempid
= $this->getContents();
5247 if ($this->level
== 8) {
5250 $this->info
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5251 $this->info
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5252 $this->info
->tempuser
= $this->getContents();
5253 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
5256 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
5259 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
5262 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
5264 case "TIMEMODIFIED":
5265 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
5268 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
5271 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
5274 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
5279 } /// ends role_assignments
5281 if ($this->tree
[4] == "ROLES_OVERRIDES") {
5282 if ($this->level
== 6) {
5285 $this->info
->tempname
= $this->getContents();
5288 $this->info
->tempshortname
= $this->getContents();
5291 $this->info
->tempid
= $this->getContents();
5296 if ($this->level
== 8) {
5299 $this->info
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5300 $this->info
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5301 $this->info
->tempname
= $this->getContents(); // change to name of capability
5302 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
5305 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
5307 case "TIMEMODIFIED":
5308 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
5311 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5315 } /// ends role_overrides
5318 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
5319 //Speed up a lot (avoid parse all)
5320 if ($tagName == "HEADER") {
5321 $this->finished
= true;
5325 $this->tree
[$this->level
] = "";
5327 $this->content
= "";
5331 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
5332 function endElementBlocks($parser, $tagName) {
5333 //Check if we are into BLOCKS zone
5334 if ($this->tree
[3] == 'BLOCKS') {
5335 //if (trim($this->content)) //Debug
5336 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5337 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5339 // Collect everything into $this->temp
5340 if (!isset($this->temp
)) {
5343 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5345 //Dependig of different combinations, do different things
5346 if ($this->level
== 4) {
5349 //We've finalized a block, get it
5350 $this->info
->instances
[] = $this->info
->tempinstance
;
5351 unset($this->info
->tempinstance
);
5353 //Also, xmlize INSTANCEDATA and save to db
5354 //Prepend XML standard header to info gathered
5355 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5356 //Call to xmlize for this portion of xml data (one BLOCK)
5357 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5358 $data = xmlize($xml_data,0);
5359 //echo strftime ("%X",time())."<p>"; //Debug
5360 //traverse_xmlize($data); //Debug
5361 //print_object ($GLOBALS['traverse_array']); //Debug
5362 //$GLOBALS['traverse_array']=""; //Debug
5363 //Check for instancedata, is exists, then save to DB
5364 if (isset($data['BLOCK']['#']['INSTANCEDATA']['0']['#'])) {
5366 $oldid = $data['BLOCK']['#']['ID']['0']['#'];
5369 if ($data = $data['BLOCK']['#']['INSTANCEDATA']['0']['#']) {
5370 //Restore code calls this multiple times - so might already have the newid
5371 if ($newid = backup_getid($this->preferences
->backup_unique_code
,'block_instance',$oldid)) {
5372 $newid = $newid->new_id
;
5376 //Save to DB, we will use it later
5377 $status = backup_putid($this->preferences
->backup_unique_code
,'block_instance',$oldid,$newid,$data);
5388 if ($this->level
== 5) {
5391 $this->info
->tempinstance
->id
= $this->getContents();
5393 $this->info
->tempinstance
->name
= $this->getContents();
5396 $this->info
->tempinstance
->pageid
= $this->getContents();
5399 $this->info
->tempinstance
->pagetype
= $this->getContents();
5402 $this->info
->tempinstance
->position
= $this->getContents();
5405 $this->info
->tempinstance
->weight
= $this->getContents();
5408 $this->info
->tempinstance
->visible
= $this->getContents();
5411 $this->info
->tempinstance
->configdata
= $this->getContents();
5418 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
5419 if ($this->level
== 7) {
5422 $this->info
->tempname
= $this->getContents();
5425 $this->info
->tempshortname
= $this->getContents();
5428 $this->info
->tempid
= $this->getContents(); // temp roleid
5433 if ($this->level
== 9) {
5437 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5439 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5441 $this->info
->tempuser
= $this->getContents();
5443 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
5446 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
5449 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
5452 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
5454 case "TIMEMODIFIED":
5455 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
5458 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
5461 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
5464 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
5469 } /// ends role_assignments
5471 if ($this->tree
[5] == "ROLES_OVERRIDES") {
5472 if ($this->level
== 7) {
5475 $this->info
->tempname
= $this->getContents();
5478 $this->info
->tempshortname
= $this->getContents();
5481 $this->info
->tempid
= $this->getContents(); // temp roleid
5486 if ($this->level
== 9) {
5490 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5491 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5492 $this->info
->tempname
= $this->getContents(); // change to name of capability
5493 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
5496 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
5498 case "TIMEMODIFIED":
5499 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
5502 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5506 } /// ends role_overrides
5509 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
5510 //Speed up a lot (avoid parse all)
5511 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
5512 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
5513 if ($this->tree
[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
5514 $this->finished
= true;
5518 $this->tree
[$this->level
] = '';
5520 $this->content
= "";
5523 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
5524 function endElementSections($parser, $tagName) {
5525 //Check if we are into SECTIONS zone
5526 if ($this->tree
[3] == "SECTIONS") {
5527 //if (trim($this->content)) //Debug
5528 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5529 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5530 //Dependig of different combinations, do different things
5531 if ($this->level
== 4) {
5534 //We've finalized a section, get it
5535 $this->info
->sections
[$this->info
->tempsection
->id
] = $this->info
->tempsection
;
5536 unset($this->info
->tempsection
);
5539 if ($this->level
== 5) {
5542 $this->info
->tempsection
->id
= $this->getContents();
5545 $this->info
->tempsection
->number
= $this->getContents();
5548 $this->info
->tempsection
->summary
= $this->getContents();
5551 $this->info
->tempsection
->visible
= $this->getContents();
5555 if ($this->level
== 6) {
5558 if (!isset($this->info
->tempmod
->groupmode
)) {
5559 $this->info
->tempmod
->groupmode
= 0;
5561 if (!isset($this->info
->tempmod
->groupingid
)) {
5562 $this->info
->tempmod
->groupingid
= 0;
5564 if (!isset($this->info
->tempmod
->groupmembersonly
)) {
5565 $this->info
->tempmod
->groupmembersonly
= 0;
5567 if (!isset($this->info
->tempmod
->idnumber
)) {
5568 $this->info
->tempmod
->idnumber
= null;
5571 //We've finalized a mod, get it
5572 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->type
=
5573 $this->info
->tempmod
->type
;
5574 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->instance
=
5575 $this->info
->tempmod
->instance
;
5576 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->added
=
5577 $this->info
->tempmod
->added
;
5578 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->score
=
5579 $this->info
->tempmod
->score
;
5580 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->indent
=
5581 $this->info
->tempmod
->indent
;
5582 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->visible
=
5583 $this->info
->tempmod
->visible
;
5584 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupmode
=
5585 $this->info
->tempmod
->groupmode
;
5586 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupingid
=
5587 $this->info
->tempmod
->groupingid
;
5588 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupmembersonly
=
5589 $this->info
->tempmod
->groupmembersonly
;
5590 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->idnumber
=
5591 $this->info
->tempmod
->idnumber
;
5593 unset($this->info
->tempmod
);
5596 if ($this->level
== 7) {
5599 $this->info
->tempmod
->id
= $this->getContents();
5602 $this->info
->tempmod
->type
= $this->getContents();
5605 $this->info
->tempmod
->instance
= $this->getContents();
5608 $this->info
->tempmod
->added
= $this->getContents();
5611 $this->info
->tempmod
->score
= $this->getContents();
5614 $this->info
->tempmod
->indent
= $this->getContents();
5617 $this->info
->tempmod
->visible
= $this->getContents();
5620 $this->info
->tempmod
->groupmode
= $this->getContents();
5623 $this->info
->tempmod
->groupingid
= $this->getContents();
5625 case "GROUPMEMBERSONLY":
5626 $this->info
->tempmod
->groupmembersonly
= $this->getContents();
5629 $this->info
->tempmod
->idnumber
= $this->getContents();
5636 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_ASSIGNMENTS") {
5638 if ($this->level
== 9) {
5641 $this->info
->tempname
= $this->getContents();
5644 $this->info
->tempshortname
= $this->getContents();
5647 $this->info
->tempid
= $this->getContents(); // temp roleid
5652 if ($this->level
== 11) {
5655 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5657 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5659 $this->info
->tempuser
= $this->getContents();
5661 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
5664 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
5667 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
5670 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
5672 case "TIMEMODIFIED":
5673 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
5676 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
5679 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
5682 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
5687 } /// ends role_assignments
5689 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_OVERRIDES") {
5690 if ($this->level
== 9) {
5693 $this->info
->tempname
= $this->getContents();
5696 $this->info
->tempshortname
= $this->getContents();
5699 $this->info
->tempid
= $this->getContents(); // temp roleid
5704 if ($this->level
== 11) {
5708 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5709 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5710 $this->info
->tempname
= $this->getContents(); // change to name of capability
5711 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
5714 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
5716 case "TIMEMODIFIED":
5717 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
5720 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5724 } /// ends role_overrides
5728 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
5729 //Speed up a lot (avoid parse all)
5730 if ($tagName == "SECTIONS") {
5731 $this->finished
= true;
5735 $this->tree
[$this->level
] = "";
5737 $this->content
= "";
5741 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
5742 function endElementFormatData($parser, $tagName) {
5743 //Check if we are into FORMATDATA zone
5744 if ($this->tree
[3] == 'FORMATDATA') {
5745 if (!isset($this->temp
)) {
5748 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5751 if($tagName=='FORMATDATA') {
5752 //Did we have any data? If not don't bother
5753 if($this->temp
!='<FORMATDATA></FORMATDATA>') {
5754 //Prepend XML standard header to info gathered
5755 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5758 //Call to xmlize for this portion of xml data (the FORMATDATA block)
5759 $this->info
->format_data
= xmlize($xml_data,0);
5761 //Stop parsing at end of FORMATDATA
5762 $this->finished
=true;
5766 $this->tree
[$this->level
] = "";
5768 $this->content
= "";
5771 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
5772 function endElementMetacourse($parser, $tagName) {
5773 //Check if we are into METACOURSE zone
5774 if ($this->tree
[3] == 'METACOURSE') {
5775 //if (trim($this->content)) //Debug
5776 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5777 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5778 //Dependig of different combinations, do different things
5779 if ($this->level
== 5) {
5782 //We've finalized a child, get it
5783 $this->info
->childs
[] = $this->info
->tempmeta
;
5784 unset($this->info
->tempmeta
);
5787 //We've finalized a parent, get it
5788 $this->info
->parents
[] = $this->info
->tempmeta
;
5789 unset($this->info
->tempmeta
);
5795 if ($this->level
== 6) {
5798 $this->info
->tempmeta
->id
= $this->getContents();
5801 $this->info
->tempmeta
->idnumber
= $this->getContents();
5804 $this->info
->tempmeta
->shortname
= $this->getContents();
5810 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
5811 //Speed up a lot (avoid parse all)
5812 if ($this->tree
[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
5813 $this->finished
= true;
5817 $this->tree
[$this->level
] = '';
5819 $this->content
= "";
5822 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5823 function endElementGradebook($parser, $tagName) {
5824 //Check if we are into GRADEBOOK zone
5825 if ($this->tree
[3] == "GRADEBOOK") {
5826 //if (trim($this->content)) //Debug
5827 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5828 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
5829 //Acumulate data to info (content + close tag)
5830 //Reconvert: strip htmlchars again and trim to generate xml data
5831 if (!isset($this->temp
)) {
5834 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5835 // We have finished outcome, grade_category or grade_item, reset accumulated
5836 // data because they are close tags
5837 if ($this->level
== 4) {
5840 //If we've finished a grade item, xmlize it an save to db
5841 if (($this->level
== 5) and ($tagName == "GRADE_ITEM")) {
5842 //Prepend XML standard header to info gathered
5843 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5844 //Call to xmlize for this portion of xml data (one PREFERENCE)
5845 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5846 $data = xmlize($xml_data,0);
5847 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
5851 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_items', $item_id,
5853 //Create returning info
5854 $this->info
= $this->counter
;
5860 //If we've finished a grade_category, xmlize it an save to db
5861 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORY")) {
5862 //Prepend XML standard header to info gathered
5863 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5864 //Call to xmlize for this portion of xml data (one CATECORY)
5865 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5866 $data = xmlize($xml_data,0);
5867 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5870 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_categories' ,$category_id,
5872 //Create returning info
5873 $this->info
= $this->counter
;
5878 if (($this->level
== 5) and ($tagName == "GRADE_LETTER")) {
5879 //Prepend XML standard header to info gathered
5880 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5881 //Call to xmlize for this portion of xml data (one CATECORY)
5882 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5883 $data = xmlize($xml_data,0);
5884 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
5887 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_letters' ,$letter_id,
5889 //Create returning info
5890 $this->info
= $this->counter
;
5895 //If we've finished a grade_outcome, xmlize it an save to db
5896 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOME")) {
5897 //Prepend XML standard header to info gathered
5898 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5899 //Call to xmlize for this portion of xml data (one CATECORY)
5900 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5901 $data = xmlize($xml_data,0);
5902 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
5905 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes' ,$outcome_id,
5907 //Create returning info
5908 $this->info
= $this->counter
;
5913 //If we've finished a grade_outcomes_course, xmlize it an save to db
5914 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOMES_COURSE")) {
5915 //Prepend XML standard header to info gathered
5916 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5917 //Call to xmlize for this portion of xml data (one CATECORY)
5918 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5919 $data = xmlize($xml_data,0);
5920 $outcomes_course_id = $data["GRADE_OUTCOMES_COURSE"]["#"]["ID"]["0"]["#"];
5923 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes_courses' ,$outcomes_course_id,
5925 //Create returning info
5926 $this->info
= $this->counter
;
5931 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORIES_HISTORY")) {
5932 //Prepend XML standard header to info gathered
5933 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5934 //Call to xmlize for this portion of xml data (one PREFERENCE)
5935 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5936 $data = xmlize($xml_data,0);
5937 $id = $data["GRADE_CATEGORIES_HISTORY"]["#"]["ID"]["0"]["#"];
5941 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_categories_history', $id,
5943 //Create returning info
5944 $this->info
= $this->counter
;
5950 if (($this->level
== 5) and ($tagName == "GRADE_GRADES_HISTORY")) {
5951 //Prepend XML standard header to info gathered
5952 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5953 //Call to xmlize for this portion of xml data (one PREFERENCE)
5954 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5955 $data = xmlize($xml_data,0);
5956 $id = $data["GRADE_GRADES_HISTORY"]["#"]["ID"]["0"]["#"];
5960 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_grades_history', $id,
5962 //Create returning info
5963 $this->info
= $this->counter
;
5969 if (($this->level
== 5) and ($tagName == "GRADE_ITEM_HISTORY")) {
5970 //Prepend XML standard header to info gathered
5971 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5972 //Call to xmlize for this portion of xml data (one PREFERENCE)
5973 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5974 $data = xmlize($xml_data,0);
5975 $id = $data["GRADE_ITEM_HISTORY"]["#"]["ID"]["0"]["#"];
5979 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_items_history', $id,
5981 //Create returning info
5982 $this->info
= $this->counter
;
5988 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOME_HISTORY")) {
5989 //Prepend XML standard header to info gathered
5990 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5991 //Call to xmlize for this portion of xml data (one PREFERENCE)
5992 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5993 $data = xmlize($xml_data,0);
5994 $id = $data["GRADE_OUTCOME_HISTORY"]["#"]["ID"]["0"]["#"];
5998 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes_history', $id,
6000 //Create returning info
6001 $this->info
= $this->counter
;
6008 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
6009 //Speed up a lot (avoid parse all)
6010 if ($tagName == "GRADEBOOK" and $this->level
== 3) {
6011 $this->finished
= true;
6016 $this->tree
[$this->level
] = "";
6018 $this->content
= "";
6022 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
6023 function endElementOldGradebook($parser, $tagName) {
6024 //Check if we are into GRADEBOOK zone
6025 if ($this->tree
[3] == "GRADEBOOK") {
6026 //if (trim($this->content)) //Debug
6027 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6028 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
6029 //Acumulate data to info (content + close tag)
6030 //Reconvert: strip htmlchars again and trim to generate xml data
6031 if (!isset($this->temp
)) {
6034 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6035 //We have finished preferences, letters or categories, reset accumulated
6036 //data because they are close tags
6037 if ($this->level
== 4) {
6040 //If we've finished a message, xmlize it an save to db
6041 if (($this->level
== 5) and ($tagName == "GRADE_PREFERENCE")) {
6042 //Prepend XML standard header to info gathered
6043 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6044 //Call to xmlize for this portion of xml data (one PREFERENCE)
6045 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6046 $data = xmlize($xml_data,0);
6047 //echo strftime ("%X",time())."<p>"; //Debug
6048 //traverse_xmlize($data); //Debug
6049 //print_object ($GLOBALS['traverse_array']); //Debug
6050 //$GLOBALS['traverse_array']=""; //Debug
6051 //Now, save data to db. We'll use it later
6052 //Get id and status from data
6053 $preference_id = $data["GRADE_PREFERENCE"]["#"]["ID"]["0"]["#"];
6056 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_preferences', $preference_id,
6058 //Create returning info
6059 $this->info
= $this->counter
;
6063 //If we've finished a grade_letter, xmlize it an save to db
6064 if (($this->level
== 5) and ($tagName == "GRADE_LETTER")) {
6065 //Prepend XML standard header to info gathered
6066 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6067 //Call to xmlize for this portion of xml data (one LETTER)
6068 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6069 $data = xmlize($xml_data,0);
6070 //echo strftime ("%X",time())."<p>"; //Debug
6071 //traverse_xmlize($data); //Debug
6072 //print_object ($GLOBALS['traverse_array']); //Debug
6073 //$GLOBALS['traverse_array']=""; //Debug
6074 //Now, save data to db. We'll use it later
6075 //Get id and status from data
6076 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
6079 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_letter' ,$letter_id,
6081 //Create returning info
6082 $this->info
= $this->counter
;
6087 //If we've finished a grade_category, xmlize it an save to db
6088 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORY")) {
6089 //Prepend XML standard header to info gathered
6090 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6091 //Call to xmlize for this portion of xml data (one CATECORY)
6092 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6093 $data = xmlize($xml_data,0);
6094 //echo strftime ("%X",time())."<p>"; //Debug
6095 //traverse_xmlize($data); //Debug
6096 //print_object ($GLOBALS['traverse_array']); //Debug
6097 //$GLOBALS['traverse_array']=""; //Debug
6098 //Now, save data to db. We'll use it later
6099 //Get id and status from data
6100 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
6103 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_category' ,$category_id,
6105 //Create returning info
6106 $this->info
= $this->counter
;
6112 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
6113 //Speed up a lot (avoid parse all)
6114 if ($tagName == "GRADEBOOK" and $this->level
== 3) {
6115 $this->finished
= true;
6120 $this->tree
[$this->level
] = "";
6122 $this->content
= "";
6126 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
6127 function endElementUsers($parser, $tagName) {
6129 //Check if we are into USERS zone
6130 if ($this->tree
[3] == "USERS") {
6131 //if (trim($this->content)) //Debug
6132 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6133 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6134 //Dependig of different combinations, do different things
6135 if ($this->level
== 4) {
6140 //Save to db, only save if record not already exist
6141 // if there already is an new_id for this entry, just use that new_id?
6142 $newuser = backup_getid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
);
6143 if (isset($newuser->new_id
)) {
6144 $newid = $newuser->new_id
;
6149 backup_putid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
,
6150 $newid,$this->info
->tempuser
);
6153 if ($this->counter %
10 == 0) {
6154 if (!defined('RESTORE_SILENTLY')) {
6156 if ($this->counter %
200 == 0) {
6163 //Delete temp obejct
6164 unset($this->info
->tempuser
);
6169 if ($this->level
== 5) {
6172 $this->info
->users
[$this->getContents()] = $this->getContents();
6173 $this->info
->tempuser
->id
= $this->getContents();
6176 $this->info
->tempuser
->auth
= $this->getContents();
6179 $this->info
->tempuser
->confirmed
= $this->getContents();
6181 case "POLICYAGREED":
6182 $this->info
->tempuser
->policyagreed
= $this->getContents();
6185 $this->info
->tempuser
->deleted
= $this->getContents();
6188 $this->info
->tempuser
->username
= $this->getContents();
6191 $this->info
->tempuser
->password
= $this->getContents();
6194 $this->info
->tempuser
->idnumber
= $this->getContents();
6197 $this->info
->tempuser
->firstname
= $this->getContents();
6200 $this->info
->tempuser
->lastname
= $this->getContents();
6203 $this->info
->tempuser
->email
= $this->getContents();
6206 $this->info
->tempuser
->emailstop
= $this->getContents();
6209 $this->info
->tempuser
->icq
= $this->getContents();
6212 $this->info
->tempuser
->skype
= $this->getContents();
6215 $this->info
->tempuser
->aim
= $this->getContents();
6218 $this->info
->tempuser
->yahoo
= $this->getContents();
6221 $this->info
->tempuser
->msn
= $this->getContents();
6224 $this->info
->tempuser
->phone1
= $this->getContents();
6227 $this->info
->tempuser
->phone2
= $this->getContents();
6230 $this->info
->tempuser
->institution
= $this->getContents();
6233 $this->info
->tempuser
->department
= $this->getContents();
6236 $this->info
->tempuser
->address
= $this->getContents();
6239 $this->info
->tempuser
->city
= $this->getContents();
6242 $this->info
->tempuser
->country
= $this->getContents();
6245 $this->info
->tempuser
->lang
= $this->getContents();
6248 $this->info
->tempuser
->theme
= $this->getContents();
6251 $this->info
->tempuser
->timezone
= $this->getContents();
6254 $this->info
->tempuser
->firstaccess
= $this->getContents();
6257 $this->info
->tempuser
->lastaccess
= $this->getContents();
6260 $this->info
->tempuser
->lastlogin
= $this->getContents();
6262 case "CURRENTLOGIN":
6263 $this->info
->tempuser
->currentlogin
= $this->getContents();
6266 $this->info
->tempuser
->lastip
= $this->getContents();
6269 $this->info
->tempuser
->secret
= $this->getContents();
6272 $this->info
->tempuser
->picture
= $this->getContents();
6275 $this->info
->tempuser
->url
= $this->getContents();
6278 $this->info
->tempuser
->description
= $this->getContents();
6281 $this->info
->tempuser
->mailformat
= $this->getContents();
6284 $this->info
->tempuser
->maildigest
= $this->getContents();
6287 $this->info
->tempuser
->maildisplay
= $this->getContents();
6290 $this->info
->tempuser
->htmleditor
= $this->getContents();
6293 $this->info
->tempuser
->ajax
= $this->getContents();
6295 case "AUTOSUBSCRIBE":
6296 $this->info
->tempuser
->autosubscribe
= $this->getContents();
6299 $this->info
->tempuser
->trackforums
= $this->getContents();
6302 $this->info
->tempuser
->mnethosturl
= $this->getContents();
6304 case "TIMEMODIFIED":
6305 $this->info
->tempuser
->timemodified
= $this->getContents();
6312 if ($this->level
== 6 && $this->tree
[5]!="ROLES_ASSIGNMENTS" && $this->tree
[5]!="ROLES_OVERRIDES") {
6315 //We've finalized a role, get it
6316 $this->info
->tempuser
->roles
[$this->info
->temprole
->type
] = $this->info
->temprole
;
6317 unset($this->info
->temprole
);
6319 case "USER_PREFERENCE":
6320 //We've finalized a user_preference, get it
6321 $this->info
->tempuser
->user_preferences
[$this->info
->tempuserpreference
->name
] = $this->info
->tempuserpreference
;
6322 unset($this->info
->tempuserpreference
);
6324 case "USER_CUSTOM_PROFILE_FIELD":
6325 //We've finalized a user_custom_profile_field, get it
6326 $this->info
->tempuser
->user_custom_profile_fields
[] = $this->info
->tempusercustomprofilefield
;
6327 unset($this->info
->tempusercustomprofilefield
);
6330 //We've finalized a user_tag, get it
6331 $this->info
->tempuser
->user_tags
[] = $this->info
->tempusertag
;
6332 unset($this->info
->tempusertag
);
6339 if ($this->level
== 7 && $this->tree
[5]!="ROLES_ASSIGNMENTS" && $this->tree
[5]!="ROLES_OVERRIDES") {
6340 /// If we are reading roles
6341 if($this->tree
[6] == 'ROLE') {
6344 $this->info
->temprole
->type
= $this->getContents();
6347 $this->info
->temprole
->authority
= $this->getContents();
6350 $this->info
->temprole
->tea_role
= $this->getContents();
6353 $this->info
->temprole
->editall
= $this->getContents();
6356 $this->info
->temprole
->timestart
= $this->getContents();
6359 $this->info
->temprole
->timeend
= $this->getContents();
6361 case "TIMEMODIFIED":
6362 $this->info
->temprole
->timemodified
= $this->getContents();
6365 $this->info
->temprole
->timestart
= $this->getContents();
6368 $this->info
->temprole
->timeend
= $this->getContents();
6371 $this->info
->temprole
->time
= $this->getContents();
6374 $this->info
->temprole
->timeaccess
= $this->getContents();
6377 $this->info
->temprole
->enrol
= $this->getContents();
6382 /// If we are reading user_preferences
6383 } else if ($this->tree
[6] == 'USER_PREFERENCE') {
6386 $this->info
->tempuserpreference
->name
= $this->getContents();
6389 $this->info
->tempuserpreference
->value
= $this->getContents();
6394 /// If we are reading user_custom_profile_fields
6395 } else if ($this->tree
[6] == 'USER_CUSTOM_PROFILE_FIELD') {
6398 $this->info
->tempusercustomprofilefield
->field_name
= $this->getContents();
6401 $this->info
->tempusercustomprofilefield
->field_type
= $this->getContents();
6404 $this->info
->tempusercustomprofilefield
->field_data
= $this->getContents();
6409 /// If we are reading user_tags
6410 } else if ($this->tree
[6] == 'USER_TAG') {
6413 $this->info
->tempusertag
->name
= $this->getContents();
6416 $this->info
->tempusertag
->rawname
= $this->getContents();
6424 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
6426 if ($this->level
== 7) {
6429 $this->info
->tempname
= $this->getContents();
6432 $this->info
->tempshortname
= $this->getContents();
6435 $this->info
->tempid
= $this->getContents(); // temp roleid
6440 if ($this->level
== 9) {
6444 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
6446 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
6448 $this->info
->tempuserid
= $this->getContents();
6450 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->userid
= $this->getContents();
6453 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->hidden
= $this->getContents();
6456 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timestart
= $this->getContents();
6459 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timeend
= $this->getContents();
6461 case "TIMEMODIFIED":
6462 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timemodified
= $this->getContents();
6465 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->modifierid
= $this->getContents();
6468 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->enrol
= $this->getContents();
6471 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->sortorder
= $this->getContents();
6476 } /// ends role_assignments
6478 if ($this->tree
[5] == "ROLES_OVERRIDES") {
6479 if ($this->level
== 7) {
6482 $this->info
->tempname
= $this->getContents();
6485 $this->info
->tempshortname
= $this->getContents();
6488 $this->info
->tempid
= $this->getContents(); // temp roleid
6493 if ($this->level
== 9) {
6497 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
6498 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
6499 $this->info
->tempname
= $this->getContents(); // change to name of capability
6500 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
6503 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
6505 case "TIMEMODIFIED":
6506 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
6509 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
6513 } /// ends role_overrides
6515 } // closes if this->tree[3]=="users"
6517 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
6518 //Speed up a lot (avoid parse all)
6519 if ($tagName == "USERS" and $this->level
== 3) {
6520 $this->finished
= true;
6525 $this->tree
[$this->level
] = "";
6527 $this->content
= "";
6531 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
6532 function endElementMessages($parser, $tagName) {
6533 //Check if we are into MESSAGES zone
6534 if ($this->tree
[3] == "MESSAGES") {
6535 //if (trim($this->content)) //Debug
6536 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6537 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
6538 //Acumulate data to info (content + close tag)
6539 //Reconvert: strip htmlchars again and trim to generate xml data
6540 if (!isset($this->temp
)) {
6543 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6544 //If we've finished a message, xmlize it an save to db
6545 if (($this->level
== 4) and ($tagName == "MESSAGE")) {
6546 //Prepend XML standard header to info gathered
6547 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6548 //Call to xmlize for this portion of xml data (one MESSAGE)
6549 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6550 $data = xmlize($xml_data,0);
6551 //echo strftime ("%X",time())."<p>"; //Debug
6552 //traverse_xmlize($data); //Debug
6553 //print_object ($GLOBALS['traverse_array']); //Debug
6554 //$GLOBALS['traverse_array']=""; //Debug
6555 //Now, save data to db. We'll use it later
6556 //Get id and status from data
6557 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
6558 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
6559 if ($message_status == "READ") {
6560 $table = "message_read";
6566 $status = backup_putid($this->preferences
->backup_unique_code
, $table,$message_id,
6568 //Create returning info
6569 $this->info
= $this->counter
;
6573 //If we've finished a contact, xmlize it an save to db
6574 if (($this->level
== 5) and ($tagName == "CONTACT")) {
6575 //Prepend XML standard header to info gathered
6576 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6577 //Call to xmlize for this portion of xml data (one MESSAGE)
6578 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6579 $data = xmlize($xml_data,0);
6580 //echo strftime ("%X",time())."<p>"; //Debug
6581 //traverse_xmlize($data); //Debug
6582 //print_object ($GLOBALS['traverse_array']); //Debug
6583 //$GLOBALS['traverse_array']=""; //Debug
6584 //Now, save data to db. We'll use it later
6585 //Get id and status from data
6586 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
6589 $status = backup_putid($this->preferences
->backup_unique_code
, 'message_contacts' ,$contact_id,
6591 //Create returning info
6592 $this->info
= $this->counter
;
6598 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
6599 //Speed up a lot (avoid parse all)
6600 if ($tagName == "MESSAGES" and $this->level
== 3) {
6601 $this->finished
= true;
6606 $this->tree
[$this->level
] = "";
6608 $this->content
= "";
6612 //This is the endTag handler we use where we are reading the blogs zone (todo="BLOGS")
6613 function endElementBlogs($parser, $tagName) {
6614 //Check if we are into BLOGS zone
6615 if ($this->tree
[3] == "BLOGS") {
6616 //if (trim($this->content)) //Debug
6617 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6618 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
6619 //Acumulate data to info (content + close tag)
6620 //Reconvert: strip htmlchars again and trim to generate xml data
6621 if (!isset($this->temp
)) {
6624 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6625 //If we've finished a blog, xmlize it an save to db
6626 if (($this->level
== 4) and ($tagName == "BLOG")) {
6627 //Prepend XML standard header to info gathered
6628 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6629 //Call to xmlize for this portion of xml data (one BLOG)
6630 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6631 $data = xmlize($xml_data,0);
6632 //echo strftime ("%X",time())."<p>"; //Debug
6633 //traverse_xmlize($data); //Debug
6634 //print_object ($GLOBALS['traverse_array']); //Debug
6635 //$GLOBALS['traverse_array']=""; //Debug
6636 //Now, save data to db. We'll use it later
6638 $blog_id = $data["BLOG"]["#"]["ID"]["0"]["#"];
6641 $status = backup_putid($this->preferences
->backup_unique_code
, 'blog', $blog_id,
6643 //Create returning info
6644 $this->info
= $this->counter
;
6650 //Stop parsing if todo = BLOGS and tagName = BLOGS (end of the tag, of course)
6651 //Speed up a lot (avoid parse all)
6652 if ($tagName == "BLOGS" and $this->level
== 3) {
6653 $this->finished
= true;
6658 $this->tree
[$this->level
] = "";
6660 $this->content
= "";
6664 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
6665 function endElementQuestions($parser, $tagName) {
6666 //Check if we are into QUESTION_CATEGORIES zone
6667 if ($this->tree
[3] == "QUESTION_CATEGORIES") {
6668 //if (trim($this->content)) //Debug
6669 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6670 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6671 //Acumulate data to info (content + close tag)
6672 //Reconvert: strip htmlchars again and trim to generate xml data
6673 if (!isset($this->temp
)) {
6676 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6677 //If we've finished a mod, xmlize it an save to db
6678 if (($this->level
== 4) and ($tagName == "QUESTION_CATEGORY")) {
6679 //Prepend XML standard header to info gathered
6680 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6681 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
6682 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6683 $data = xmlize($xml_data,0);
6684 //echo strftime ("%X",time())."<p>"; //Debug
6685 //traverse_xmlize($data); //Debug
6686 //print_object ($GLOBALS['traverse_array']); //Debug
6687 //$GLOBALS['traverse_array']=""; //Debug
6688 //Now, save data to db. We'll use it later
6690 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
6692 $status = backup_putid($this->preferences
->backup_unique_code
,"question_categories",$category_id,
6694 //Create returning info
6695 $ret_info = new object();
6696 $ret_info->id
= $category_id;
6697 $this->info
[] = $ret_info;
6703 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
6704 //Speed up a lot (avoid parse all)
6705 if ($tagName == "QUESTION_CATEGORIES" and $this->level
== 3) {
6706 $this->finished
= true;
6710 $this->tree
[$this->level
] = "";
6712 $this->content
= "";
6716 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
6717 function endElementScales($parser, $tagName) {
6718 //Check if we are into SCALES zone
6719 if ($this->tree
[3] == "SCALES") {
6720 //if (trim($this->content)) //Debug
6721 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6722 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6723 //Acumulate data to info (content + close tag)
6724 //Reconvert: strip htmlchars again and trim to generate xml data
6725 if (!isset($this->temp
)) {
6728 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6729 //If we've finished a scale, xmlize it an save to db
6730 if (($this->level
== 4) and ($tagName == "SCALE")) {
6731 //Prepend XML standard header to info gathered
6732 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6733 //Call to xmlize for this portion of xml data (one SCALE)
6734 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6735 $data = xmlize($xml_data,0);
6736 //echo strftime ("%X",time())."<p>"; //Debug
6737 //traverse_xmlize($data); //Debug
6738 //print_object ($GLOBALS['traverse_array']); //Debug
6739 //$GLOBALS['traverse_array']=""; //Debug
6740 //Now, save data to db. We'll use it later
6741 //Get id and from data
6742 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
6744 $status = backup_putid($this->preferences
->backup_unique_code
,"scale",$scale_id,
6746 //Create returning info
6747 $ret_info = new object();
6748 $ret_info->id
= $scale_id;
6749 $this->info
[] = $ret_info;
6755 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
6756 //Speed up a lot (avoid parse all)
6757 if ($tagName == "SCALES" and $this->level
== 3) {
6758 $this->finished
= true;
6762 $this->tree
[$this->level
] = "";
6764 $this->content
= "";
6768 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
6769 function endElementGroups($parser, $tagName) {
6770 //Check if we are into GROUPS zone
6771 if ($this->tree
[3] == "GROUPS") {
6772 //if (trim($this->content)) //Debug
6773 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6774 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6775 //Acumulate data to info (content + close tag)
6776 //Reconvert: strip htmlchars again and trim to generate xml data
6777 if (!isset($this->temp
)) {
6780 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6781 //If we've finished a group, xmlize it an save to db
6782 if (($this->level
== 4) and ($tagName == "GROUP")) {
6783 //Prepend XML standard header to info gathered
6784 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6785 //Call to xmlize for this portion of xml data (one GROUP)
6786 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6787 $data = xmlize($xml_data,0);
6788 //echo strftime ("%X",time())."<p>"; //Debug
6789 //traverse_xmlize($data); //Debug
6790 //print_object ($GLOBALS['traverse_array']); //Debug
6791 //$GLOBALS['traverse_array']=""; //Debug
6792 //Now, save data to db. We'll use it later
6793 //Get id and from data
6794 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
6796 $status = backup_putid($this->preferences
->backup_unique_code
,"groups",$group_id,
6798 //Create returning info
6799 $ret_info = new Object();
6800 $ret_info->id
= $group_id;
6801 $this->info
[] = $ret_info;
6807 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
6808 //Speed up a lot (avoid parse all)
6809 if ($tagName == "GROUPS" and $this->level
== 3) {
6810 $this->finished
= true;
6814 $this->tree
[$this->level
] = "";
6816 $this->content
= "";
6820 //This is the endTag handler we use where we are reading the groupings zone (todo="GROUPINGS")
6821 function endElementGroupings($parser, $tagName) {
6822 //Check if we are into GROUPINGS zone
6823 if ($this->tree
[3] == "GROUPINGS") {
6824 //Acumulate data to info (content + close tag)
6825 //Reconvert: strip htmlchars again and trim to generate xml data
6826 if (!isset($this->temp
)) {
6829 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6830 //If we've finished a group, xmlize it an save to db
6831 if (($this->level
== 4) and ($tagName == "GROUPING")) {
6832 //Prepend XML standard header to info gathered
6833 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6834 //Call to xmlize for this portion of xml data (one GROUPING)
6835 $data = xmlize($xml_data,0);
6836 //Now, save data to db. We'll use it later
6837 //Get id and from data
6838 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
6840 $status = backup_putid($this->preferences
->backup_unique_code
,"groupings",$grouping_id,
6842 //Create returning info
6843 $ret_info = new Object();
6844 $ret_info->id
= $grouping_id;
6845 $this->info
[] = $ret_info;
6851 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6852 //Speed up a lot (avoid parse all)
6853 if ($tagName == "GROUPINGS" and $this->level
== 3) {
6854 $this->finished
= true;
6858 $this->tree
[$this->level
] = "";
6860 $this->content
= "";
6864 //This is the endTag handler we use where we are reading the groupingsgroups zone (todo="GROUPINGGROUPS")
6865 function endElementGroupingsGroups($parser, $tagName) {
6866 //Check if we are into GROUPINGSGROUPS zone
6867 if ($this->tree
[3] == "GROUPINGSGROUPS") {
6868 //Acumulate data to info (content + close tag)
6869 //Reconvert: strip htmlchars again and trim to generate xml data
6870 if (!isset($this->temp
)) {
6873 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6874 //If we've finished a group, xmlize it an save to db
6875 if (($this->level
== 4) and ($tagName == "GROUPINGGROUP")) {
6876 //Prepend XML standard header to info gathered
6877 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6878 //Call to xmlize for this portion of xml data (one GROUPING)
6879 $data = xmlize($xml_data,0);
6880 //Now, save data to db. We'll use it later
6881 //Get id and from data
6882 $groupinggroup_id = $data["GROUPINGGROUP"]["#"]["ID"]["0"]["#"];
6884 $status = backup_putid($this->preferences
->backup_unique_code
,"groupingsgroups",$groupinggroup_id,
6886 //Create returning info
6887 $ret_info = new Object();
6888 $ret_info->id
= $groupinggroup_id;
6889 $this->info
[] = $ret_info;
6895 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6896 //Speed up a lot (avoid parse all)
6897 if ($tagName == "GROUPINGSGROUPS" and $this->level
== 3) {
6898 $this->finished
= true;
6902 $this->tree
[$this->level
] = "";
6904 $this->content
= "";
6908 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
6909 function endElementEvents($parser, $tagName) {
6910 //Check if we are into EVENTS zone
6911 if ($this->tree
[3] == "EVENTS") {
6912 //if (trim($this->content)) //Debug
6913 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6914 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6915 //Acumulate data to info (content + close tag)
6916 //Reconvert: strip htmlchars again and trim to generate xml data
6917 if (!isset($this->temp
)) {
6920 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6921 //If we've finished a event, xmlize it an save to db
6922 if (($this->level
== 4) and ($tagName == "EVENT")) {
6923 //Prepend XML standard header to info gathered
6924 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6925 //Call to xmlize for this portion of xml data (one EVENT)
6926 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6927 $data = xmlize($xml_data,0);
6928 //echo strftime ("%X",time())."<p>"; //Debug
6929 //traverse_xmlize($data); //Debug
6930 //print_object ($GLOBALS['traverse_array']); //Debug
6931 //$GLOBALS['traverse_array']=""; //Debug
6932 //Now, save data to db. We'll use it later
6933 //Get id and from data
6934 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
6936 $status = backup_putid($this->preferences
->backup_unique_code
,"event",$event_id,
6938 //Create returning info
6939 $ret_info = new object();
6940 $ret_info->id
= $event_id;
6941 $this->info
[] = $ret_info;
6947 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
6948 //Speed up a lot (avoid parse all)
6949 if ($tagName == "EVENTS" and $this->level
== 3) {
6950 $this->finished
= true;
6954 $this->tree
[$this->level
] = "";
6956 $this->content
= "";
6960 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
6961 function endElementModules($parser, $tagName) {
6962 //Check if we are into MODULES zone
6963 if ($this->tree
[3] == "MODULES") {
6964 //if (trim($this->content)) //Debug
6965 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6966 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6967 //Acumulate data to info (content + close tag)
6968 //Reconvert: strip htmlchars again and trim to generate xml data
6969 if (!isset($this->temp
)) {
6972 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6973 //If we've finished a mod, xmlize it an save to db
6974 if (($this->level
== 4) and ($tagName == "MOD")) {
6975 //Prepend XML standard header to info gathered
6976 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6977 //Call to xmlize for this portion of xml data (one MOD)
6978 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6979 $data = xmlize($xml_data,0);
6980 //echo strftime ("%X",time())."<p>"; //Debug
6981 //traverse_xmlize($data); //Debug
6982 //print_object ($GLOBALS['traverse_array']); //Debug
6983 //$GLOBALS['traverse_array']=""; //Debug
6984 //Now, save data to db. We'll use it later
6985 //Get id and modtype from data
6986 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
6987 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
6988 //Only if we've selected to restore it
6989 if (!empty($this->preferences
->mods
[$mod_type]->restore
)) {
6991 $status = backup_putid($this->preferences
->backup_unique_code
,$mod_type,$mod_id,
6993 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6994 //Create returning info
6995 $ret_info = new object();
6996 $ret_info->id
= $mod_id;
6997 $ret_info->modtype
= $mod_type;
6998 $this->info
[] = $ret_info;
7007 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
7008 //Speed up a lot (avoid parse all)
7009 if ($tagName == "MODULES" and $this->level
== 3) {
7010 $this->finished
= true;
7014 $this->tree
[$this->level
] = "";
7016 $this->content
= "";
7020 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
7021 function endElementLogs($parser, $tagName) {
7022 //Check if we are into LOGS zone
7023 if ($this->tree
[3] == "LOGS") {
7024 //if (trim($this->content)) //Debug
7025 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
7026 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
7027 //Acumulate data to info (content + close tag)
7028 //Reconvert: strip htmlchars again and trim to generate xml data
7029 if (!isset($this->temp
)) {
7032 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
7033 //If we've finished a log, xmlize it an save to db
7034 if (($this->level
== 4) and ($tagName == "LOG")) {
7035 //Prepend XML standard header to info gathered
7036 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
7037 //Call to xmlize for this portion of xml data (one LOG)
7038 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
7039 $data = xmlize($xml_data,0);
7040 //echo strftime ("%X",time())."<p>"; //Debug
7041 //traverse_xmlize($data); //Debug
7042 //print_object ($GLOBALS['traverse_array']); //Debug
7043 //$GLOBALS['traverse_array']=""; //Debug
7044 //Now, save data to db. We'll use it later
7045 //Get id and modtype from data
7046 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
7047 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
7048 //We only save log entries from backup file if they are:
7051 // - Module logs about one restored module
7052 if ($log_module == "course" or
7053 $log_module == "user" or
7054 $this->preferences
->mods
[$log_module]->restore
) {
7058 $status = backup_putid($this->preferences
->backup_unique_code
,"log",$log_id,
7060 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
7061 //Create returning info
7062 $this->info
= $this->counter
;
7069 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
7070 //Speed up a lot (avoid parse all)
7071 if ($tagName == "LOGS" and $this->level
== 3) {
7072 $this->finished
= true;
7077 $this->tree
[$this->level
] = "";
7079 $this->content
= "";
7083 //This is the endTag default handler we use when todo is undefined
7084 function endElement($parser, $tagName) {
7085 if (trim($this->content
)) //Debug
7086 echo "C".str_repeat(" ",($this->level+
2)*2).$this->getContents()."<br />\n"; //Debug
7087 echo $this->level
.str_repeat(" ",$this->level
*2)."</".$tagName."><br />\n"; //Debug
7090 $this->tree
[$this->level
] = "";
7092 $this->content
= "";
7095 //This is the handler to read data contents (simple accumule it)
7096 function characterData($parser, $data) {
7097 $this->content
.= $data;
7101 //This function executes the MoodleParser
7102 function restore_read_xml ($xml_file,$todo,$preferences) {
7106 $xml_parser = xml_parser_create('UTF-8');
7107 $moodle_parser = new MoodleParser();
7108 $moodle_parser->todo
= $todo;
7109 $moodle_parser->preferences
= $preferences;
7110 xml_set_object($xml_parser,$moodle_parser);
7111 //Depending of the todo we use some element_handler or another
7112 if ($todo == "INFO") {
7113 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
7114 } else if ($todo == "ROLES") {
7115 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
7116 } else if ($todo == "COURSE_HEADER") {
7117 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
7118 } else if ($todo == 'BLOCKS') {
7119 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
7120 } else if ($todo == "SECTIONS") {
7121 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
7122 } else if ($todo == 'FORMATDATA') {
7123 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
7124 } else if ($todo == "METACOURSE") {
7125 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
7126 } else if ($todo == "GRADEBOOK") {
7127 if ($preferences->backup_version
> 2007090500) {
7128 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
7130 xml_set_element_handler($xml_parser, "startElementOldGradebook", "endElementOldGradebook");
7132 } else if ($todo == "USERS") {
7133 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
7134 } else if ($todo == "MESSAGES") {
7135 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
7136 } else if ($todo == "BLOGS") {
7137 xml_set_element_handler($xml_parser, "startElementBlogs", "endElementBlogs");
7138 } else if ($todo == "QUESTIONS") {
7139 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
7140 } else if ($todo == "SCALES") {
7141 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
7142 } else if ($todo == "GROUPS") {
7143 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
7144 } else if ($todo == "GROUPINGS") {
7145 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
7146 } else if ($todo == "GROUPINGSGROUPS") {
7147 xml_set_element_handler($xml_parser, "startElementGroupingsGroups", "endElementGroupingsGroups");
7148 } else if ($todo == "EVENTS") {
7149 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
7150 } else if ($todo == "MODULES") {
7151 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
7152 } else if ($todo == "LOGS") {
7153 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
7155 //Define default handlers (must no be invoked when everything become finished)
7156 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
7158 xml_set_character_data_handler($xml_parser, "characterData");
7159 $fp = fopen($xml_file,"r")
7162 // MDL-9290 performance improvement on reading large xml
7163 $lasttime = time(); // crmas
7164 while ($data = fread($fp, 4096) and !$moodle_parser->finished
) {
7166 if ((time() - $lasttime) > 5) {
7171 xml_parse($xml_parser, $data, feof($fp))
7172 or die(sprintf("XML error: %s at line %d",
7173 xml_error_string(xml_get_error_code($xml_parser)),
7174 xml_get_current_line_number($xml_parser)));
7178 //Get info from parser
7179 $info = $moodle_parser->info
;
7182 xml_parser_free($xml_parser);
7184 if ($status && !empty($info)) {
7192 * @param string $errorstr passed by reference, if silent is true,
7193 * errorstr will be populated and this function will return false rather than calling error() or notify()
7194 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
7195 * redirect to the next step in the restore process, instead will return $backup_unique_code
7197 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
7199 global $CFG, $SESSION;
7201 //Prepend dataroot to variable to have the absolute path
7202 $file = $CFG->dataroot
."/".$file;
7204 if (!defined('RESTORE_SILENTLY')) {
7205 //Start the main table
7206 echo "<table cellpadding=\"5\">";
7213 //Check the file exists
7214 if (!is_file($file)) {
7215 if (!defined('RESTORE_SILENTLY')) {
7216 error ("File not exists ($file)");
7218 $errorstr = "File not exists ($file)";
7223 //Check the file name ends with .zip
7224 if (!substr($file,-4) == ".zip") {
7225 if (!defined('RESTORE_SILENTLY')) {
7226 error ("File has an incorrect extension");
7228 $errorstr = 'File has an incorrect extension';
7233 //Now calculate the unique_code for this restore
7234 $backup_unique_code = time();
7236 //Now check and create the backup dir (if it doesn't exist)
7237 if (!defined('RESTORE_SILENTLY')) {
7238 echo "<li>".get_string("creatingtemporarystructures").'</li>';
7240 $status = check_and_create_backup_dir($backup_unique_code);
7243 $status = clear_backup_dir($backup_unique_code);
7246 //Now delete old data and directories under dataroot/temp/backup
7248 if (!defined('RESTORE_SILENTLY')) {
7249 echo "<li>".get_string("deletingolddata").'</li>';
7251 $status = backup_delete_old_data();
7254 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
7256 if (!defined('RESTORE_SILENTLY')) {
7257 echo "<li>".get_string("copyingzipfile").'</li>';
7259 if (! $status = backup_copy_file($file,$CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
7260 if (!defined('RESTORE_SILENTLY')) {
7261 notify("Error copying backup file. Invalid name or bad perms.");
7263 $errorstr = "Error copying backup file. Invalid name or bad perms";
7269 //Now unzip the file
7271 if (!defined('RESTORE_SILENTLY')) {
7272 echo "<li>".get_string("unzippingbackup").'</li>';
7274 if (! $status = restore_unzip ($CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
7275 if (!defined('RESTORE_SILENTLY')) {
7276 notify("Error unzipping backup file. Invalid zip file.");
7278 $errorstr = "Error unzipping backup file. Invalid zip file.";
7284 //Check for Blackboard backups and convert
7286 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
7287 if (!defined('RESTORE_SILENTLY')) {
7288 echo "<li>".get_string("checkingforbbexport").'</li>';
7290 $status = blackboard_convert($CFG->dataroot
."/temp/backup/".$backup_unique_code);
7293 //Now check for the moodle.xml file
7295 $xml_file = $CFG->dataroot
."/temp/backup/".$backup_unique_code."/moodle.xml";
7296 if (!defined('RESTORE_SILENTLY')) {
7297 echo "<li>".get_string("checkingbackup").'</li>';
7299 if (! $status = restore_check_moodle_file ($xml_file)) {
7300 if (!is_file($xml_file)) {
7301 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
7303 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
7305 if (!defined('RESTORE_SILENTLY')) {
7314 $course_header = "";
7316 //Now read the info tag (all)
7318 if (!defined('RESTORE_SILENTLY')) {
7319 echo "<li>".get_string("readinginfofrombackup").'</li>';
7321 //Reading info from file
7322 $info = restore_read_xml_info ($xml_file);
7323 //Reading course_header from file
7324 $course_header = restore_read_xml_course_header ($xml_file);
7326 if(!is_object($course_header)){
7327 // ensure we fail if there is no course header
7328 $course_header = false;
7332 if (!defined('RESTORE_SILENTLY')) {
7336 //End the main table
7341 //We compare Moodle's versions
7342 if ($CFG->version
< $info->backup_moodle_version
&& $status) {
7343 $message = new object();
7344 $message->serverversion
= $CFG->version
;
7345 $message->serverrelease
= $CFG->release
;
7346 $message->backupversion
= $info->backup_moodle_version
;
7347 $message->backuprelease
= $info->backup_moodle_release
;
7348 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
7352 //Now we print in other table, the backup and the course it contains info
7353 if ($info and $course_header and $status) {
7354 //First, the course info
7355 if (!defined('RESTORE_SILENTLY')) {
7356 $status = restore_print_course_header($course_header);
7358 //Now, the backup info
7360 if (!defined('RESTORE_SILENTLY')) {
7361 $status = restore_print_info($info);
7366 //Save course header and info into php session
7368 $SESSION->info
= $info;
7369 $SESSION->course_header
= $course_header;
7372 //Finally, a little form to continue
7373 //with some hidden fields
7375 if (!defined('RESTORE_SILENTLY')) {
7376 echo "<br /><div style='text-align:center'>";
7377 $hidden["backup_unique_code"] = $backup_unique_code;
7378 $hidden["launch"] = "form";
7379 $hidden["file"] = $file;
7380 $hidden["id"] = $id;
7381 print_single_button("restore.php", $hidden, get_string("continue"),"post");
7385 if (empty($noredirect)) {
7386 redirect($CFG->wwwroot
.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
7388 return $backup_unique_code;
7394 if (!defined('RESTORE_SILENTLY')) {
7395 error ("An error has ocurred");
7397 $errorstr = "An error has occured"; // helpful! :P
7404 function restore_setup_for_check(&$restore,$backup_unique_code) {
7406 $restore->backup_unique_code
=$backup_unique_code;
7407 $restore->users
= 2; // yuk
7408 $restore->course_files
= $SESSION->restore
->restore_course_files
;
7409 $restore->site_files
= $SESSION->restore
->restore_site_files
;
7410 if ($allmods = get_records("modules")) {
7411 foreach ($allmods as $mod) {
7412 $modname = $mod->name
;
7413 $var = "restore_".$modname;
7414 //Now check that we have that module info in the backup file
7415 if (isset($SESSION->info
->mods
[$modname]) && $SESSION->info
->mods
[$modname]->backup
== "true") {
7423 function backup_to_restore_array($backup,$k=0) {
7424 if (is_array($backup) ) {
7425 foreach ($backup as $key => $value) {
7426 $newkey = str_replace('backup','restore',$key);
7427 $restore[$newkey] = backup_to_restore_array($value,$key);
7430 else if (is_object($backup)) {
7431 $tmp = get_object_vars($backup);
7432 foreach ($tmp as $key => $value) {
7433 $newkey = str_replace('backup','restore',$key);
7434 $restore->$newkey = backup_to_restore_array($value,$key);
7438 $newkey = str_replace('backup','restore',$k);
7445 * compatibility function
7446 * checks for per-instance backups AND
7447 * older per-module backups
7448 * and returns whether userdata has been selected.
7450 function restore_userdata_selected($restore,$modname,$modid) {
7451 // check first for per instance array
7452 if (!empty($restore->mods
[$modname]->granular
)) { // supports per instance
7453 return array_key_exists($modid,$restore->mods
[$modname]->instances
)
7454 && !empty($restore->mods
[$modname]->instances
[$modid]->userinfo
);
7457 //print_object($restore->mods[$modname]);
7458 return !empty($restore->mods
[$modname]->userinfo
);
7461 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
7466 //Checks for the required files/functions to restore every module
7468 if ($allmods = get_records("modules") ) {
7469 foreach ($allmods as $mod) {
7470 $modname = $mod->name
;
7471 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
7472 //If file exists and we have selected to restore that type of module
7473 if ((file_exists($modfile)) and !empty($restore->mods
[$modname]) and ($restore->mods
[$modname]->restore
)) {
7474 include_once($modfile);
7479 if (!defined('RESTORE_SILENTLY')) {
7480 //Start the main table
7481 echo "<table cellpadding=\"5\">";
7488 //Localtion of the xml file
7489 $xml_file = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/moodle.xml";
7491 //If we've selected to restore into new course
7492 //create it (course)
7493 //Saving conversion id variables into backup_tables
7494 if ($restore->restoreto
== 2) {
7495 if (!defined('RESTORE_SILENTLY')) {
7496 echo '<li>'.get_string('creatingnewcourse') . '</li>';
7498 $oldidnumber = $course_header->course_idnumber
;
7499 if (!$status = restore_create_new_course($restore,$course_header)) {
7500 if (!defined('RESTORE_SILENTLY')) {
7501 notify("Error while creating the new empty course.");
7503 $errorstr = "Error while creating the new empty course.";
7508 //Print course fullname and shortname and category
7510 if (!defined('RESTORE_SILENTLY')) {
7512 echo "<li>".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
7513 echo "<li>".get_string("category").": ".$course_header->category
->name
.'</li>';
7514 if (!empty($oldidnumber)) {
7515 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
7518 //Put the destination course_id
7520 $restore->course_id
= $course_header->course_id
;
7523 if ($status = restore_open_html($restore,$course_header)){
7524 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
7528 $course = get_record("course","id",$restore->course_id
);
7530 if (!defined('RESTORE_SILENTLY')) {
7531 echo "<li>".get_string("usingexistingcourse");
7533 echo "<li>".get_string("from").": ".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
7534 echo "<li>".get_string("to").": ". format_string($course->fullname
) ." (".format_string($course->shortname
).")".'</li>';
7535 if (($restore->deleting
)) {
7536 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
7538 echo "<li>".get_string("addingdatatoexisting").'</li>';
7542 //If we have selected to restore deleting, we do it now.
7543 if ($restore->deleting
) {
7544 if (!defined('RESTORE_SILENTLY')) {
7545 echo "<li>".get_string("deletingolddata").'</li>';
7547 $status = remove_course_contents($restore->course_id
,false) and
7548 delete_dir_contents($CFG->dataroot
."/".$restore->course_id
,"backupdata");
7550 //Now , this situation is equivalent to the "restore to new course" one (we
7551 //have a course record and nothing more), so define it as "to new course"
7552 $restore->restoreto
= 2;
7554 if (!defined('RESTORE_SILENTLY')) {
7555 notify("An error occurred while deleting some of the course contents.");
7557 $errrostr = "An error occurred while deleting some of the course contents.";
7563 if (!defined('RESTORE_SILENTLY')) {
7564 notify("Error opening existing course.");
7567 $errorstr = "Error opening existing course.";
7573 //Now create users as needed
7574 if ($status and ($restore->users
== 0 or $restore->users
== 1)) {
7575 if (!defined('RESTORE_SILENTLY')) {
7576 echo "<li>".get_string("creatingusers")."<br />";
7578 if (!$status = restore_create_users($restore,$xml_file)) {
7579 if (!defined('RESTORE_SILENTLY')) {
7580 notify("Could not restore users.");
7582 $errorstr = "Could not restore users.";
7587 //Now print info about the work done
7589 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
7590 where backup_code = '$restore->backup_unique_code' and
7591 table_name = 'user'");
7599 //Iterate, filling counters
7600 foreach ($recs as $rec) {
7601 //Get full record, using backup_getids
7602 $record = backup_getid($restore->backup_unique_code
,"user",$rec->old_id
);
7603 if (strpos($record->info
,"new") !== false) {
7606 if (strpos($record->info
,"exists") !== false) {
7609 if (strpos($record->info
,"student") !== false) {
7611 } else if (strpos($record->info
,"teacher") !== false) {
7616 if ($counter %
10 == 0) {
7617 if (!defined('RESTORE_SILENTLY')) {
7619 if ($counter %
200 == 0) {
7626 if (!defined('RESTORE_SILENTLY')) {
7627 //Now print information gathered
7628 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
7630 echo "<li>".get_string("students").": ".$student_count.'</li>';
7631 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
7635 if (!defined('RESTORE_SILENTLY')) {
7636 notify("No users were found!");
7637 } // no need to return false here, it's recoverable.
7641 if (!defined('RESTORE_SILENTLY')) {
7647 //Now create groups as needed
7648 if ($status and ($restore->groups
== RESTORE_GROUPS_ONLY
or $restore->groups
== RESTORE_GROUPS_GROUPINGS
)) {
7649 if (!defined('RESTORE_SILENTLY')) {
7650 echo "<li>".get_string("creatinggroups");
7652 if (!$status = restore_create_groups($restore,$xml_file)) {
7653 if (!defined('RESTORE_SILENTLY')) {
7654 notify("Could not restore groups!");
7656 $errorstr = "Could not restore groups!";
7660 if (!defined('RESTORE_SILENTLY')) {
7665 //Now create groupings as needed
7666 if ($status and ($restore->groups
== RESTORE_GROUPINGS_ONLY
or $restore->groups
== RESTORE_GROUPS_GROUPINGS
)) {
7667 if (!defined('RESTORE_SILENTLY')) {
7668 echo "<li>".get_string("creatinggroupings");
7670 if (!$status = restore_create_groupings($restore,$xml_file)) {
7671 if (!defined('RESTORE_SILENTLY')) {
7672 notify("Could not restore groupings!");
7674 $errorstr = "Could not restore groupings!";
7678 if (!defined('RESTORE_SILENTLY')) {
7683 //Now create groupingsgroups as needed
7684 if ($status and $restore->groups
== RESTORE_GROUPS_GROUPINGS
) {
7685 if (!defined('RESTORE_SILENTLY')) {
7686 echo "<li>".get_string("creatinggroupingsgroups");
7688 if (!$status = restore_create_groupings_groups($restore,$xml_file)) {
7689 if (!defined('RESTORE_SILENTLY')) {
7690 notify("Could not restore groups in groupings!");
7692 $errorstr = "Could not restore groups in groupings!";
7696 if (!defined('RESTORE_SILENTLY')) {
7702 //Now create the course_sections and their associated course_modules
7703 //we have to do this after groups and groupings are restored, because we need the new groupings id
7706 if ($restore->restoreto
== 2) {
7707 if (!defined('RESTORE_SILENTLY')) {
7708 echo "<li>".get_string("creatingsections");
7710 if (!$status = restore_create_sections($restore,$xml_file)) {
7711 if (!defined('RESTORE_SILENTLY')) {
7712 notify("Error creating sections in the existing course.");
7714 $errorstr = "Error creating sections in the existing course.";
7718 if (!defined('RESTORE_SILENTLY')) {
7721 //Into existing course
7722 } else if ($restore->restoreto
== 0 or $restore->restoreto
== 1) {
7723 if (!defined('RESTORE_SILENTLY')) {
7724 echo "<li>".get_string("checkingsections");
7726 if (!$status = restore_create_sections($restore,$xml_file)) {
7727 if (!defined('RESTORE_SILENTLY')) {
7728 notify("Error creating sections in the existing course.");
7730 $errorstr = "Error creating sections in the existing course.";
7734 if (!defined('RESTORE_SILENTLY')) {
7739 if (!defined('RESTORE_SILENTLY')) {
7740 notify("Neither a new course or an existing one was specified.");
7743 $errorstr = "Neither a new course or an existing one was specified.";
7749 //Now create metacourse info
7750 if ($status and $restore->metacourse
) {
7751 //Only to new courses!
7752 if ($restore->restoreto
== 2) {
7753 if (!defined('RESTORE_SILENTLY')) {
7754 echo "<li>".get_string("creatingmetacoursedata");
7756 if (!$status = restore_create_metacourse($restore,$xml_file)) {
7757 if (!defined('RESTORE_SILENTLY')) {
7758 notify("Error creating metacourse in the course.");
7760 $errorstr = "Error creating metacourse in the course.";
7764 if (!defined('RESTORE_SILENTLY')) {
7771 //Now create categories and questions as needed
7773 include_once("$CFG->dirroot/question/restorelib.php");
7774 if (!defined('RESTORE_SILENTLY')) {
7775 echo "<li>".get_string("creatingcategoriesandquestions");
7778 if (!$status = restore_create_questions($restore,$xml_file)) {
7779 if (!defined('RESTORE_SILENTLY')) {
7780 notify("Could not restore categories and questions!");
7782 $errorstr = "Could not restore categories and questions!";
7786 if (!defined('RESTORE_SILENTLY')) {
7791 //Now create user_files as needed
7792 if ($status and ($restore->user_files
)) {
7793 if (!defined('RESTORE_SILENTLY')) {
7794 echo "<li>".get_string("copyinguserfiles");
7796 if (!$status = restore_user_files($restore)) {
7797 if (!defined('RESTORE_SILENTLY')) {
7798 notify("Could not restore user files!");
7800 $errorstr = "Could not restore user files!";
7804 //If all is ok (and we have a counter)
7805 if ($status and ($status !== true)) {
7806 //Inform about user dirs created from backup
7807 if (!defined('RESTORE_SILENTLY')) {
7809 echo "<li>".get_string("userzones").": ".$status;
7813 if (!defined('RESTORE_SILENTLY')) {
7818 //Now create course files as needed
7819 if ($status and ($restore->course_files
)) {
7820 if (!defined('RESTORE_SILENTLY')) {
7821 echo "<li>".get_string("copyingcoursefiles");
7823 if (!$status = restore_course_files($restore)) {
7824 if (empty($status)) {
7825 notify("Could not restore course files!");
7827 $errorstr = "Could not restore course files!";
7831 //If all is ok (and we have a counter)
7832 if ($status and ($status !== true)) {
7833 //Inform about user dirs created from backup
7834 if (!defined('RESTORE_SILENTLY')) {
7836 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7840 if (!defined('RESTORE_SILENTLY')) {
7846 //Now create site files as needed
7847 if ($status and ($restore->site_files
)) {
7848 if (!defined('RESTORE_SILENTLY')) {
7849 echo "<li>".get_string('copyingsitefiles');
7851 if (!$status = restore_site_files($restore)) {
7852 if (empty($status)) {
7853 notify("Could not restore site files!");
7855 $errorstr = "Could not restore site files!";
7859 //If all is ok (and we have a counter)
7860 if ($status and ($status !== true)) {
7861 //Inform about user dirs created from backup
7862 if (!defined('RESTORE_SILENTLY')) {
7864 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7868 if (!defined('RESTORE_SILENTLY')) {
7873 //Now create messages as needed
7874 if ($status and ($restore->messages
)) {
7875 if (!defined('RESTORE_SILENTLY')) {
7876 echo "<li>".get_string("creatingmessagesinfo");
7878 if (!$status = restore_create_messages($restore,$xml_file)) {
7879 if (!defined('RESTORE_SILENTLY')) {
7880 notify("Could not restore messages!");
7882 $errorstr = "Could not restore messages!";
7886 if (!defined('RESTORE_SILENTLY')) {
7891 //Now create blogs as needed
7892 if ($status and ($restore->blogs
)) {
7893 if (!defined('RESTORE_SILENTLY')) {
7894 echo "<li>".get_string("creatingblogsinfo");
7896 if (!$status = restore_create_blogs($restore,$xml_file)) {
7897 if (!defined('RESTORE_SILENTLY')) {
7898 notify("Could not restore blogs!");
7900 $errorstr = "Could not restore blogs!";
7904 if (!defined('RESTORE_SILENTLY')) {
7909 //Now create scales as needed
7911 if (!defined('RESTORE_SILENTLY')) {
7912 echo "<li>".get_string("creatingscales");
7914 if (!$status = restore_create_scales($restore,$xml_file)) {
7915 if (!defined('RESTORE_SILENTLY')) {
7916 notify("Could not restore custom scales!");
7918 $errorstr = "Could not restore custom scales!";
7922 if (!defined('RESTORE_SILENTLY')) {
7927 //Now create events as needed
7929 if (!defined('RESTORE_SILENTLY')) {
7930 echo "<li>".get_string("creatingevents");
7932 if (!$status = restore_create_events($restore,$xml_file)) {
7933 if (!defined('RESTORE_SILENTLY')) {
7934 notify("Could not restore course events!");
7936 $errorstr = "Could not restore course events!";
7940 if (!defined('RESTORE_SILENTLY')) {
7945 //Now create course modules as needed
7947 if (!defined('RESTORE_SILENTLY')) {
7948 echo "<li>".get_string("creatingcoursemodules");
7950 if (!$status = restore_create_modules($restore,$xml_file)) {
7951 if (!defined('RESTORE_SILENTLY')) {
7952 notify("Could not restore modules!");
7954 $errorstr = "Could not restore modules!";
7958 if (!defined('RESTORE_SILENTLY')) {
7963 //Bring back the course blocks -- do it AFTER the modules!!!
7965 //If we are deleting and bringing into a course or making a new course, same situation
7966 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
7967 if (!defined('RESTORE_SILENTLY')) {
7968 echo '<li>'.get_string('creatingblocks');
7970 $course_header->blockinfo
= !empty($course_header->blockinfo
) ?
$course_header->blockinfo
: NULL;
7971 if (!$status = restore_create_blocks($restore, $info->backup_block_format
, $course_header->blockinfo
, $xml_file)) {
7972 if (!defined('RESTORE_SILENTLY')) {
7973 notify('Error while creating the course blocks');
7975 $errorstr = "Error while creating the course blocks";
7979 if (!defined('RESTORE_SILENTLY')) {
7986 //If we are deleting and bringing into a course or making a new course, same situation
7987 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
7988 if (!defined('RESTORE_SILENTLY')) {
7989 echo '<li>'.get_string('courseformatdata');
7991 if (!$status = restore_set_format_data($restore, $xml_file)) {
7992 $error = "Error while setting the course format data";
7993 if (!defined('RESTORE_SILENTLY')) {
8000 if (!defined('RESTORE_SILENTLY')) {
8006 //Now create log entries as needed
8007 if ($status and ($restore->logs
)) {
8008 if (!defined('RESTORE_SILENTLY')) {
8009 echo "<li>".get_string("creatinglogentries");
8011 if (!$status = restore_create_logs($restore,$xml_file)) {
8012 if (!defined('RESTORE_SILENTLY')) {
8013 notify("Could not restore logs!");
8015 $errorstr = "Could not restore logs!";
8019 if (!defined('RESTORE_SILENTLY')) {
8024 //Now, if all is OK, adjust the instance field in course_modules !!
8025 //this also calculates the final modinfo information so, after this,
8026 //code needing it can be used (like role_assignments. MDL-13740)
8028 if (!defined('RESTORE_SILENTLY')) {
8029 echo "<li>".get_string("checkinginstances");
8031 if (!$status = restore_check_instances($restore)) {
8032 if (!defined('RESTORE_SILENTLY')) {
8033 notify("Could not adjust instances in course_modules!");
8035 $errorstr = "Could not adjust instances in course_modules!";
8039 if (!defined('RESTORE_SILENTLY')) {
8044 //Now, if all is OK, adjust activity events
8046 if (!defined('RESTORE_SILENTLY')) {
8047 echo "<li>".get_string("refreshingevents");
8049 if (!$status = restore_refresh_events($restore)) {
8050 if (!defined('RESTORE_SILENTLY')) {
8051 notify("Could not refresh events for activities!");
8053 $errorstr = "Could not refresh events for activities!";
8057 if (!defined('RESTORE_SILENTLY')) {
8062 //Now, if all is OK, adjust inter-activity links
8064 if (!defined('RESTORE_SILENTLY')) {
8065 echo "<li>".get_string("decodinginternallinks");
8067 if (!$status = restore_decode_content_links($restore)) {
8068 if (!defined('RESTORE_SILENTLY')) {
8069 notify("Could not decode content links!");
8071 $errorstr = "Could not decode content links!";
8075 if (!defined('RESTORE_SILENTLY')) {
8080 //Now, with backup files prior to version 2005041100,
8081 //convert all the wiki texts in the course to markdown
8082 if ($status && $restore->backup_version
< 2005041100) {
8083 if (!defined('RESTORE_SILENTLY')) {
8084 echo "<li>".get_string("convertingwikitomarkdown");
8086 if (!$status = restore_convert_wiki2markdown($restore)) {
8087 if (!defined('RESTORE_SILENTLY')) {
8088 notify("Could not convert wiki texts to markdown!");
8090 $errorstr = "Could not convert wiki texts to markdown!";
8094 if (!defined('RESTORE_SILENTLY')) {
8099 //Now create gradebook as needed -- AFTER modules and blocks!!!
8101 if ($restore->backup_version
> 2007090500) {
8102 if (!defined('RESTORE_SILENTLY')) {
8103 echo "<li>".get_string("creatinggradebook");
8105 if (!$status = restore_create_gradebook($restore,$xml_file)) {
8106 if (!defined('RESTORE_SILENTLY')) {
8107 notify("Could not restore gradebook!");
8109 $errorstr = "Could not restore gradebook!";
8114 if (!defined('RESTORE_SILENTLY')) {
8119 // for moodle versions before 1.9, those grades need to be converted to use the new gradebook
8120 // this code needs to execute *after* the course_modules are sorted out
8121 if (!defined('RESTORE_SILENTLY')) {
8122 echo "<li>".get_string("migratinggrades");
8125 /// force full refresh of grading data before migration == crete all items first
8126 if (!$status = restore_migrate_old_gradebook($restore,$xml_file)) {
8127 if (!defined('RESTORE_SILENTLY')) {
8128 notify("Could not migrate gradebook!");
8130 $errorstr = "Could not migrade gradebook!";
8134 if (!defined('RESTORE_SILENTLY')) {
8138 /// force full refresh of grading data after all items are created
8139 grade_force_full_regrading($restore->course_id
);
8140 grade_grab_course_grades($restore->course_id
);
8143 /*******************************************************************************
8144 ************* Restore of Roles and Capabilities happens here ******************
8145 *******************************************************************************/
8146 // try to restore roles even when restore is going to fail - teachers might have
8147 // at least some role assigned - this is not correct though
8148 $status = restore_create_roles($restore, $xml_file) && $status;
8149 $status = restore_roles_settings($restore, $xml_file) && $status;
8151 //Now if all is OK, update:
8152 // - course modinfo field
8153 // - categories table
8154 // - add user as teacher
8156 if (!defined('RESTORE_SILENTLY')) {
8157 echo "<li>".get_string("checkingcourse");
8160 $course = get_record("course","id",$restore->course_id
);
8161 fix_course_sortorder();
8162 // Check if the user has course update capability in the newly restored course
8163 // there is no need to load his capabilities again, because restore_roles_settings
8164 // would have loaded it anyway, if there is any assignments.
8166 $newcontext = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
8167 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
8168 // fix for MDL-9065, use the new config setting if exists
8169 if ($CFG->creatornewroleid
) {
8170 role_assign($CFG->creatornewroleid
, $USER->id
, 0, $newcontext->id
);
8172 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW
, get_context_instance(CONTEXT_SYSTEM
))) {
8173 if ($legacyteacher = array_shift($legacyteachers)) {
8174 role_assign($legacyteacher->id
, $USER->id
, 0, $newcontext->id
);
8177 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
8181 if (!defined('RESTORE_SILENTLY')) {
8186 //Cleanup temps (files and db)
8188 if (!defined('RESTORE_SILENTLY')) {
8189 echo "<li>".get_string("cleaningtempdata");
8191 if (!$status = clean_temp_data ($restore)) {
8192 if (!defined('RESTORE_SILENTLY')) {
8193 notify("Could not clean up temporary data from files and database");
8195 $errorstr = "Could not clean up temporary data from files and database";
8199 if (!defined('RESTORE_SILENTLY')) {
8204 // this is not a critical check - the result can be ignored
8205 if (restore_close_html($restore)){
8206 if (!defined('RESTORE_SILENTLY')) {
8207 echo '<li>Closing the Restorelog.html file.</li>';
8211 if (!defined('RESTORE_SILENTLY')) {
8212 notify("Could not close the restorelog.html file");
8216 if (!defined('RESTORE_SILENTLY')) {
8220 //End the main table
8227 //Create, open and write header of the html log file
8228 function restore_open_html($restore,$course_header) {
8234 //Open file for writing
8235 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
8236 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
8237 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
8239 $status = check_dir_exists($dest_dir,true);
8240 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8241 //Add the stylesheet
8242 $stylesheetshtml = '';
8243 foreach ($CFG->stylesheets
as $stylesheet) {
8244 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
8246 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
8247 $languagehtml = get_html_lang($dir=true);
8249 //Write the header in the new logging file
8250 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
8251 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
8252 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
8253 fwrite ($restorelog_file,"<head>");
8254 fwrite ($restorelog_file,$stylesheetshtml);
8255 fwrite ($restorelog_file,"<title>".$course_header->course_shortname
." Restored </title>");
8256 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
8257 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname
." The FullName is now - ".$course_header->course_fullname
."<br/><br/>");
8258 $startdate = addslashes($course_header->course_startdate
);
8259 $date = usergetdate($startdate);
8260 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
8261 $startdate +
= $restore->course_startdateoffset
;
8262 $date = usergetdate($startdate);
8263 fwrite ($restorelog_file," This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
8266 return $restorelog_file;
8271 //Create & close footer of the html log file
8272 function restore_close_html($restore) {
8278 //Open file for writing
8279 //First, check that course_id/backupdata folder exists in CFG->dataroot
8280 $dest_dir = $CFG->dataroot
."/".$restore->course_id
."/backupdata";
8281 $status = check_dir_exists($dest_dir, true, true);
8282 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8283 //Write the footer to close the logging file
8284 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
8285 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
8288 return $restorelog_file;
8294 /********************** Roles and Capabilities Related Functions *******************************/
8296 /* Yu: Note recovering of role assignments/overrides need to take place after
8297 users have been recovered, i.e. after we get their new_id, and after all
8298 roles have been recreated or mapped. Contexts can be created on the fly.
8299 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
8300 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
8301 once roles and users have been restored.
8305 * This function restores all the needed roles for this course
8306 * i.e. roles with an assignment in any of the mods or blocks,
8307 * roles assigned on any user (e.g. parent role) and roles
8308 * assigned at course levle
8309 * This function should check for duplicate roles first
8310 * It isn't now, just overwriting
8312 function restore_create_roles($restore, $xmlfile) {
8313 if (!defined('RESTORE_SILENTLY')) {
8314 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
8316 $info = restore_read_xml_roles($xmlfile);
8318 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
8320 // the following code creates new roles
8321 // but we could use more intelligent detection, and role mapping
8322 // get role mapping info from $restore
8323 $rolemappings = array();
8325 if (!empty($restore->rolesmapping
)) {
8326 $rolemappings = $restore->rolesmapping
;
8328 // $info->roles will be empty for backups pre 1.7
8329 if (isset($info->roles
) && $info->roles
) {
8331 foreach ($info->roles
as $oldroleid=>$roledata) {
8333 if (empty($restore->rolesmapping
)) {
8334 // if this is empty altogether, we came from import or there's no roles used in course at all
8335 // in this case, write the same oldid as this is the same site
8336 // no need to do mapping
8337 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
8338 $oldroleid); // adding a new id
8339 continue; // do not create additonal roles;
8341 // first we check if the roles are in the mappings
8342 // if so, we just do a mapping i.e. update oldids table
8343 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
8344 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
8345 $rolemappings[$oldroleid]); // adding a new id
8349 // code to make new role name/short name if same role name or shortname exists
8350 $fullname = $roledata->name
;
8351 $shortname = $roledata->shortname
;
8352 $currentfullname = "";
8353 $currentshortname = "";
8358 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
8359 $suffixshort = "_".$counter;
8364 $currentfullname = $fullname.$suffixfull;
8365 // Limit the size of shortname - database column accepts <= 100 chars
8366 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
8367 $coursefull = get_record("role","name",addslashes($currentfullname));
8368 $courseshort = get_record("role","shortname",addslashes($currentshortname));
8370 } while ($coursefull ||
$courseshort);
8372 $roledata->name
= $currentfullname;
8373 $roledata->shortname
= $currentshortname;
8375 // done finding a unique name
8377 $newroleid = create_role(addslashes($roledata->name
),addslashes($roledata->shortname
),'');
8378 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
8379 $newroleid); // adding a new id
8380 foreach ($roledata->capabilities
as $capability) {
8382 $roleinfo = new object();
8383 $roleinfo = (object)$capability;
8384 $roleinfo->contextid
= $sitecontext->id
;
8385 $roleinfo->capability
= $capability->name
;
8386 $roleinfo->roleid
= $newroleid;
8388 insert_record('role_capabilities', $roleinfo);
8391 /// Now, restore role nameincourse (only if the role had nameincourse in backup)
8392 if (!empty($roledata->nameincourse
)) {
8393 $newrole = backup_getid($restore->backup_unique_code
, 'role', $oldroleid); /// Look for target role
8394 $coursecontext = get_context_instance(CONTEXT_COURSE
, $restore->course_id
); /// Look for target context
8395 if (!empty($newrole->new_id
) && !empty($coursecontext)) {
8396 /// Check the role hasn't any custom name in context
8397 if (!record_exists('role_names', 'roleid', $newrole->new_id
, 'contextid', $coursecontext->id
)) {
8398 $rolename = new object();
8399 $rolename->roleid
= $newrole->new_id
;
8400 $rolename->contextid
= $coursecontext->id
;
8401 $rolename->name
= addslashes($roledata->nameincourse
);
8403 insert_record('role_names', $rolename);
8413 * this function restores role assignments and role overrides
8414 * in course/user/block/mod level, it passed through
8415 * the xml file again
8417 function restore_roles_settings($restore, $xmlfile) {
8418 // data pulls from course, mod, user, and blocks
8420 /*******************************************************
8421 * Restoring from course level assignments *
8422 *******************************************************/
8423 if (!defined('RESTORE_SILENTLY')) {
8424 echo "<li>".get_string("creatingcourseroles").'</li>';
8426 $course = restore_read_xml_course_header($xmlfile);
8428 if (!isset($restore->rolesmapping
)) {
8429 $isimport = true; // course import from another course, or course with no role assignments
8431 $isimport = false; // course restore with role assignments
8434 if (!empty($course->roleassignments
) && !$isimport) {
8435 $courseassignments = $course->roleassignments
;
8437 foreach ($courseassignments as $oldroleid => $courseassignment) {
8438 restore_write_roleassignments($restore, $courseassignment->assignments
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
8441 /*****************************************************
8442 * Restoring from course level overrides *
8443 *****************************************************/
8445 if (!empty($course->roleoverrides
) && !$isimport) {
8446 $courseoverrides = $course->roleoverrides
;
8447 foreach ($courseoverrides as $oldroleid => $courseoverride) {
8448 // if not importing into exiting course, or creating new role, we are ok
8449 // local course overrides to be respected (i.e. restored course overrides ignored)
8450 if ($restore->restoreto
!= 1 ||
empty($restore->rolesmapping
[$oldroleid])) {
8451 restore_write_roleoverrides($restore, $courseoverride->overrides
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
8456 /*******************************************************
8457 * Restoring role assignments/overrdies *
8458 * from module level assignments *
8459 *******************************************************/
8461 if (!defined('RESTORE_SILENTLY')) {
8462 echo "<li>".get_string("creatingmodroles").'</li>';
8464 $sections = restore_read_xml_sections($xmlfile);
8465 $secs = $sections->sections
;
8467 foreach ($secs as $section) {
8468 if (isset($section->mods
)) {
8469 foreach ($section->mods
as $modid=>$mod) {
8470 if (isset($mod->roleassignments
) && !$isimport) {
8471 foreach ($mod->roleassignments
as $oldroleid=>$modassignment) {
8472 restore_write_roleassignments($restore, $modassignment->assignments
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
8475 // role overrides always applies, in import or backup/restore
8476 if (isset($mod->roleoverrides
)) {
8477 foreach ($mod->roleoverrides
as $oldroleid=>$modoverride) {
8478 restore_write_roleoverrides($restore, $modoverride->overrides
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
8485 /*************************************************
8486 * Restoring assignments from blocks level *
8487 * role assignments/overrides *
8488 *************************************************/
8490 if ($restore->restoreto
!= 1) { // skip altogether if restoring to exisitng course by adding
8491 if (!defined('RESTORE_SILENTLY')) {
8492 echo "<li>".get_string("creatingblocksroles").'</li>';
8494 $blocks = restore_read_xml_blocks($restore, $xmlfile);
8495 if (isset($blocks->instances
)) {
8496 foreach ($blocks->instances
as $instance) {
8497 if (isset($instance->roleassignments
) && !$isimport) {
8498 foreach ($instance->roleassignments
as $oldroleid=>$blockassignment) {
8499 restore_write_roleassignments($restore, $blockassignment->assignments
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
8503 // likewise block overrides should always be restored like mods
8504 if (isset($instance->roleoverrides
)) {
8505 foreach ($instance->roleoverrides
as $oldroleid=>$blockoverride) {
8506 restore_write_roleoverrides($restore, $blockoverride->overrides
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
8512 /************************************************
8513 * Restoring assignments from userid level *
8514 * role assignments/overrides *
8515 ************************************************/
8516 if (!defined('RESTORE_SILENTLY')) {
8517 echo "<li>".get_string("creatinguserroles").'</li>';
8519 $info = restore_read_xml_users($restore, $xmlfile);
8520 if (!empty($info->users
) && !$isimport) { // no need to restore user assignments for imports (same course)
8521 //For each user, take its info from backup_ids
8522 foreach ($info->users
as $userid) {
8523 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
8524 if (isset($rec->info
->roleassignments
)) {
8525 foreach ($rec->info
->roleassignments
as $oldroleid=>$userassignment) {
8526 restore_write_roleassignments($restore, $userassignment->assignments
, "user", CONTEXT_USER
, $userid, $oldroleid);
8529 if (isset($rec->info
->roleoverrides
)) {
8530 foreach ($rec->info
->roleoverrides
as $oldroleid=>$useroverride) {
8531 restore_write_roleoverrides($restore, $useroverride->overrides
, "user", CONTEXT_USER
, $userid, $oldroleid);
8540 // auxillary function to write role assignments read from xml to db
8541 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
8543 $role = backup_getid($restore->backup_unique_code
, "role", $oldroleid);
8545 foreach ($assignments as $assignment) {
8547 $olduser = backup_getid($restore->backup_unique_code
,"user",$assignment->userid
);
8548 //Oh dear, $olduser... can be an object, $obj->string or bool!
8549 if (!$olduser ||
(is_string($olduser->info
) && $olduser->info
== "notincourse")) { // it's possible that user is not in the course
8552 $assignment->userid
= $olduser->new_id
; // new userid here
8553 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$assignment->modifierid
);
8554 $assignment->modifierid
= !empty($oldmodifier->new_id
) ?
$oldmodifier->new_id
: 0; // new modifier id here
8555 $assignment->roleid
= $role->new_id
; // restored new role id
8557 // hack to make the correct contextid for course level imports
8558 if ($contextlevel == CONTEXT_COURSE
) {
8559 $oldinstance->new_id
= $restore->course_id
;
8561 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
8564 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
8565 $assignment->contextid
= $newcontext->id
; // new context id
8566 // might already have same assignment
8567 role_assign($assignment->roleid
, $assignment->userid
, 0, $assignment->contextid
, $assignment->timestart
, $assignment->timeend
, $assignment->hidden
, $assignment->enrol
, $assignment->timemodified
);
8572 // auxillary function to write role assignments read from xml to db
8573 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
8575 // it is possible to have an override not relevant to this course context.
8576 // should be ignored(?)
8577 if (!$role = backup_getid($restore->backup_unique_code
, "role", $oldroleid)) {
8581 foreach ($overrides as $override) {
8582 $override->capability
= $override->name
;
8583 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$override->modifierid
);
8584 $override->modifierid
= !empty($oldmodifier->new_id
)?
$oldmodifier->new_id
:0; // new modifier id here
8585 $override->roleid
= $role->new_id
; // restored new role id
8587 // hack to make the correct contextid for course level imports
8588 if ($contextlevel == CONTEXT_COURSE
) {
8589 $oldinstance->new_id
= $restore->course_id
;
8591 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
8594 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
8595 $override->contextid
= $newcontext->id
; // new context id
8596 // use assign capability instead so we can add context to context_rel
8597 assign_capability($override->capability
, $override->permission
, $override->roleid
, $override->contextid
);
8600 //write activity date changes to the html log file, and update date values in the the xml array
8601 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
8606 // loop through time fields in $TAGS
8607 foreach ($TAGS as $TAG) {
8609 // check $TAG has a sensible value
8610 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
8612 if ($openlog==false) {
8613 $openlog = true; // only come through here once
8615 // open file for writing
8616 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
8617 check_dir_exists($course_dir, true);
8618 $restorelog = fopen("$course_dir/restorelog.html", "a");
8620 // start output for this record
8621 $msg = new stdClass();
8622 $msg->recordtype
= $recordtype;
8623 $msg->recordname
= $xml[$NAMETAG][0]['#'];
8624 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
8627 // write old date to $restorelog
8628 $value = $xml[$TAG][0]['#'];
8629 $date = usergetdate($value);
8631 $msg = new stdClass();
8633 $msg->weekday
= $date['weekday'];
8634 $msg->mday
= $date['mday'];
8635 $msg->month
= $date['month'];
8636 $msg->year
= $date['year'];
8637 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
8639 // write new date to $restorelog
8640 $value +
= $restore->course_startdateoffset
;
8641 $date = usergetdate($value);
8643 $msg = new stdClass();
8645 $msg->weekday
= $date['weekday'];
8646 $msg->mday
= $date['mday'];
8647 $msg->month
= $date['month'];
8648 $msg->year
= $date['year'];
8649 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
8651 // update $value in $xml tree for calling module
8652 $xml[$TAG][0]['#'] = "$value";
8655 // close the restore log, if it was opened
8657 fclose($restorelog);