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 // Restore links in modules.
97 foreach ($restore->mods
as $name => $info) {
98 //If the module is being restored
99 if (isset($info->restore
) && $info->restore
== 1) {
100 //Check if the xxxx_decode_content_links_caller exists
101 include_once("$CFG->dirroot/mod/$name/restorelib.php");
102 $function_name = $name."_decode_content_links_caller";
103 if (function_exists($function_name)) {
104 if (!defined('RESTORE_SILENTLY')) {
105 echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
107 $status = $function_name($restore) && $status;
108 if (!defined('RESTORE_SILENTLY')) {
115 // Process all html text also in blocks too
116 if (!defined('RESTORE_SILENTLY')) {
117 echo '<li>'.get_string ('from').' '.get_string('blocks');
120 if ($blocks = get_records('block', 'visible', 1)) {
121 foreach ($blocks as $block) {
122 if ($blockobject = block_instance($block->name
)) {
123 $blockobject->decode_content_links_caller($restore);
128 if (!defined('RESTORE_SILENTLY')) {
132 // Restore links in questions.
133 require_once("$CFG->dirroot/question/restorelib.php");
134 if (!defined('RESTORE_SILENTLY')) {
135 echo '<li>' . get_string('from') . ' ' . get_string('questions', 'quiz');
137 $status = question_decode_content_links_caller($restore) && $status;
138 if (!defined('RESTORE_SILENTLY')) {
142 if (!defined('RESTORE_SILENTLY')) {
149 //This function is called from all xxxx_decode_content_links_caller(),
150 //its task is to ask all modules (maybe other linkable objects) to restore
152 function restore_decode_content_links_worker($content,$restore) {
153 foreach($restore->mods
as $name => $info) {
154 $function_name = $name."_decode_content_links";
155 if (function_exists($function_name)) {
156 $content = $function_name($content,$restore);
160 // For each block, call its encode_content_links method
161 static $blockobjects = null;
162 if (!isset($blockobjects)) {
163 $blockobjects = array();
164 if ($blocks = get_records('block', 'visible', 1)) {
165 foreach ($blocks as $block) {
166 if ($blockobject = block_instance($block->name
)) {
167 $blockobjects[] = $blockobject;
173 foreach ($blockobjects as $blockobject) {
174 $content = $blockobject->decode_content_links($content,$restore);
180 //This function converts all the wiki texts in the restored course
181 //to the Markdown format. Used only for backup files prior 2005041100.
182 //It calls every module xxxx_convert_wiki2markdown function
183 function restore_convert_wiki2markdown($restore) {
187 if (!defined('RESTORE_SILENTLY')) {
190 foreach ($restore->mods
as $name => $info) {
191 //If the module is being restored
192 if ($info->restore
== 1) {
193 //Check if the xxxx_restore_wiki2markdown exists
194 $function_name = $name."_restore_wiki2markdown";
195 if (function_exists($function_name)) {
196 $status = $function_name($restore);
197 if (!defined('RESTORE_SILENTLY')) {
198 echo "<li>".get_string("modulenameplural",$name);
204 if (!defined('RESTORE_SILENTLY')) {
210 //This function receives a wiki text in the restore process and
211 //return it with every link to modules " modulename:moduleid"
212 //converted if possible. See the space before modulename!!
213 function restore_decode_wiki_content($content,$restore) {
219 $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
221 preg_match_all($searchstring,$content,$foundset);
222 //If found, then we are going to look for its new id (in backup tables)
224 //print_object($foundset); //Debug
225 //Iterate over foundset[2]. They are the old_ids
226 foreach($foundset[2] as $old_id) {
227 //We get the needed variables here (course id)
228 $rec = backup_getid($restore->backup_unique_code
,"course_modules",$old_id);
229 //Personalize the searchstring
230 $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/';
231 //If it is a link to this course, update the link to its new location
234 $result= preg_replace($searchstring,' $1:'.$rec->new_id
.'($2)',$result);
236 //It's a foreign link so redirect it to its original URL
237 $result= preg_replace($searchstring,$restore->original_wwwroot
.'/mod/$1/view.php?id='.$old_id.'($2)',$result);
245 //This function read the xml file and store it data from the info zone in an object
246 function restore_read_xml_info ($xml_file) {
248 //We call the main read_xml function, with todo = INFO
249 $info = restore_read_xml ($xml_file,"INFO",false);
254 //This function read the xml file and store it data from the course header zone in an object
255 function restore_read_xml_course_header ($xml_file) {
257 //We call the main read_xml function, with todo = COURSE_HEADER
258 $info = restore_read_xml ($xml_file,"COURSE_HEADER",false);
263 //This function read the xml file and store its data from the blocks in a object
264 function restore_read_xml_blocks ($restore, $xml_file) {
266 //We call the main read_xml function, with todo = BLOCKS
267 $info = restore_read_xml ($xml_file,'BLOCKS',$restore);
272 //This function read the xml file and store its data from the sections in a object
273 function restore_read_xml_sections ($xml_file) {
275 //We call the main read_xml function, with todo = SECTIONS
276 $info = restore_read_xml ($xml_file,"SECTIONS",false);
281 //This function read the xml file and store its data from the course format in an object
282 function restore_read_xml_formatdata ($xml_file) {
284 //We call the main read_xml function, with todo = FORMATDATA
285 $info = restore_read_xml ($xml_file,'FORMATDATA',false);
290 //This function read the xml file and store its data from the metacourse in a object
291 function restore_read_xml_metacourse ($xml_file) {
293 //We call the main read_xml function, with todo = METACOURSE
294 $info = restore_read_xml ($xml_file,"METACOURSE",false);
299 //This function read the xml file and store its data from the gradebook in a object
300 function restore_read_xml_gradebook ($restore, $xml_file) {
302 //We call the main read_xml function, with todo = GRADEBOOK
303 $info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
308 //This function read the xml file and store its data from the users in
309 //backup_ids->info db (and user's id in $info)
310 function restore_read_xml_users ($restore,$xml_file) {
312 //We call the main read_xml function, with todo = USERS
313 $info = restore_read_xml ($xml_file,"USERS",$restore);
318 //This function read the xml file and store its data from the messages in
319 //backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
320 function restore_read_xml_messages ($restore,$xml_file) {
322 //We call the main read_xml function, with todo = MESSAGES
323 $info = restore_read_xml ($xml_file,"MESSAGES",$restore);
329 //This function read the xml file and store its data from the questions in
330 //backup_ids->info db (and category's id in $info)
331 function restore_read_xml_questions ($restore,$xml_file) {
333 //We call the main read_xml function, with todo = QUESTIONS
334 $info = restore_read_xml ($xml_file,"QUESTIONS",$restore);
339 //This function read the xml file and store its data from the scales in
340 //backup_ids->info db (and scale's id in $info)
341 function restore_read_xml_scales ($restore,$xml_file) {
343 //We call the main read_xml function, with todo = SCALES
344 $info = restore_read_xml ($xml_file,"SCALES",$restore);
349 //This function read the xml file and store its data from the groups in
350 //backup_ids->info db (and group's id in $info)
351 function restore_read_xml_groups ($restore,$xml_file) {
353 //We call the main read_xml function, with todo = GROUPS
354 $info = restore_read_xml ($xml_file,"GROUPS",$restore);
359 //This function read the xml file and store its data from the groupings in
360 //backup_ids->info db (and grouping's id in $info)
361 function restore_read_xml_groupings ($restore,$xml_file) {
363 //We call the main read_xml function, with todo = GROUPINGS
364 $info = restore_read_xml ($xml_file,"GROUPINGS",$restore);
369 //This function read the xml file and store its data from the groupings in
370 //backup_ids->info db (and grouping's id in $info)
371 function restore_read_xml_groupings_groups ($restore,$xml_file) {
373 //We call the main read_xml function, with todo = GROUPINGS
374 $info = restore_read_xml ($xml_file,"GROUPINGSGROUPS",$restore);
379 //This function read the xml file and store its data from the events (course) in
380 //backup_ids->info db (and event's id in $info)
381 function restore_read_xml_events ($restore,$xml_file) {
383 //We call the main read_xml function, with todo = EVENTS
384 $info = restore_read_xml ($xml_file,"EVENTS",$restore);
389 //This function read the xml file and store its data from the modules in
391 function restore_read_xml_modules ($restore,$xml_file) {
393 //We call the main read_xml function, with todo = MODULES
394 $info = restore_read_xml ($xml_file,"MODULES",$restore);
399 //This function read the xml file and store its data from the logs in
401 function restore_read_xml_logs ($restore,$xml_file) {
403 //We call the main read_xml function, with todo = LOGS
404 $info = restore_read_xml ($xml_file,"LOGS",$restore);
409 function restore_read_xml_roles ($xml_file) {
410 //We call the main read_xml function, with todo = ROLES
411 $info = restore_read_xml ($xml_file,"ROLES",false);
416 //This function prints the contents from the info parammeter passed
417 function restore_print_info ($info) {
423 $table = new object();
424 //This is tha align to every ingo table
425 $table->align
= array ("right","left");
426 //This is the nowrap clause
427 $table->wrap
= array ("","nowrap");
429 $table->width
= "70%";
430 //Put interesting info in table
431 //The backup original name
432 $tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
433 $tab[0][1] = $info->backup_name
;
435 $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
436 $tab[1][1] = $info->backup_moodle_release
." (".$info->backup_moodle_version
.")";
438 $tab[2][0] = "<b>".get_string("backupversion").":</b>";
439 $tab[2][1] = $info->backup_backup_release
." (".$info->backup_backup_version
.")";
441 $tab[3][0] = "<b>".get_string("backupdate").":</b>";
442 $tab[3][1] = userdate($info->backup_date
);
444 print_heading(get_string("backup").":");
446 //Print backup general info
449 if ($info->backup_backup_version
<= 2005070500) {
450 notify(get_string('backupnonisowarning')); // Message informing that this backup may not work!
453 //Now backup contents in another table
458 foreach ($mods as $key => $mod) {
459 $tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
460 if ($mod->backup
== "false") {
461 $tab[$elem][1] = get_string("notincluded");
463 if ($mod->userinfo
== "true") {
464 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
466 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
468 if (isset($mod->instances
) && is_array($mod->instances
) && count($mod->instances
)) {
469 foreach ($mod->instances
as $instance) {
470 if ($instance->backup
) {
472 $tab[$elem][0] = $instance->name
;
473 if ($instance->userinfo
== 'true') {
474 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
476 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
485 $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
486 if ($info->backup_metacourse
== "true") {
487 $tab[$elem][1] = get_string("yes");
489 $tab[$elem][1] = get_string("no");
493 $tab[$elem][0] = "<b>".get_string("users").":</b>";
494 $tab[$elem][1] = get_string($info->backup_users
);
497 $tab[$elem][0] = "<b>".get_string("logs").":</b>";
498 if ($info->backup_logs
== "true") {
499 $tab[$elem][1] = get_string("yes");
501 $tab[$elem][1] = get_string("no");
505 $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
506 if ($info->backup_user_files
== "true") {
507 $tab[$elem][1] = get_string("yes");
509 $tab[$elem][1] = get_string("no");
513 $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
514 if ($info->backup_course_files
== "true") {
515 $tab[$elem][1] = get_string("yes");
517 $tab[$elem][1] = get_string("no");
521 $tab[$elem][0] = "<b>".get_string("sitefiles").":</b>";
522 if (isset($info->backup_site_files
) && $info->backup_site_files
== "true") {
523 $tab[$elem][1] = get_string("yes");
525 $tab[$elem][1] = get_string("no");
528 //gradebook history info
529 $tab[$elem][0] = "<b>".get_string('gradebookhistories', 'grades').":</b>";
530 if (isset($info->gradebook_histories
) && $info->gradebook_histories
== "true") {
531 $tab[$elem][1] = get_string("yes");
533 $tab[$elem][1] = get_string("no");
536 //Messages info (only showed if present)
537 if ($info->backup_messages
== 'true') {
538 $tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
539 $tab[$elem][1] = get_string('yes');
546 print_heading(get_string("backupdetails").":");
547 //Print backup general info
556 //This function prints the contents from the course_header parammeter passed
557 function restore_print_course_header ($course_header) {
560 if ($course_header) {
561 $table = new object();
562 //This is tha align to every ingo table
563 $table->align
= array ("right","left");
565 $table->width
= "70%";
566 //Put interesting course header in table
568 $tab[0][0] = "<b>".get_string("name").":</b>";
569 $tab[0][1] = $course_header->course_fullname
." (".$course_header->course_shortname
.")";
571 $tab[1][0] = "<b>".get_string("summary").":</b>";
572 $tab[1][1] = $course_header->course_summary
;
575 print_heading(get_string("course").":");
576 //Print backup course header info
584 //This function create a new course record.
585 //When finished, course_header contains the id of the new course
586 function restore_create_new_course($restore,&$course_header) {
592 $fullname = $course_header->course_fullname
;
593 $shortname = $course_header->course_shortname
;
594 $currentfullname = "";
595 $currentshortname = "";
597 //Iteratere while the name exists
600 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
601 $suffixshort = "_".$counter;
606 $currentfullname = $fullname.$suffixfull;
607 // Limit the size of shortname - database column accepts <= 100 chars
608 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
609 $coursefull = get_record("course","fullname",addslashes($currentfullname));
610 $courseshort = get_record("course","shortname",addslashes($currentshortname));
612 } while ($coursefull ||
$courseshort);
614 //New name = currentname
615 $course_header->course_fullname
= $currentfullname;
616 $course_header->course_shortname
= $currentshortname;
618 // first try to get it from restore
619 if ($restore->restore_restorecatto
) {
620 $category = get_record('course_categories', 'id', $restore->restore_restorecatto
);
623 // else we try to get it from the xml file
624 //Now calculate the category
626 $category = get_record("course_categories","id",$course_header->category
->id
,
627 "name",addslashes($course_header->category
->name
));
630 //If no exists, try by name only
632 $category = get_record("course_categories","name",addslashes($course_header->category
->name
));
635 //If no exists, get category id 1
637 $category = get_record("course_categories","id","1");
640 //If category 1 doesn'exists, lets create the course category (get it from backup file)
642 $ins_category = new object();
643 $ins_category->name
= addslashes($course_header->category
->name
);
644 $ins_category->parent
= 0;
645 $ins_category->sortorder
= 0;
646 $ins_category->coursecount
= 0;
647 $ins_category->visible
= 0; //To avoid interferences with the rest of the site
648 $ins_category->timemodified
= time();
649 $newid = insert_record("course_categories",$ins_category);
650 $category->id
= $newid;
651 $category->name
= $course_header->category
->name
;
653 //If exists, put new category id
655 $course_header->category
->id
= $category->id
;
656 $course_header->category
->name
= $category->name
;
657 //Error, cannot locate category
659 $course_header->category
->id
= 0;
660 $course_header->category
->name
= get_string("unknowncategory");
664 //Create the course_object
666 $course = new object();
667 $course->category
= addslashes($course_header->category
->id
);
668 $course->password
= addslashes($course_header->course_password
);
669 $course->fullname
= addslashes($course_header->course_fullname
);
670 $course->shortname
= addslashes($course_header->course_shortname
);
671 $course->idnumber
= addslashes($course_header->course_idnumber
);
672 $course->idnumber
= ''; //addslashes($course_header->course_idnumber); // we don't want this at all.
673 $course->summary
= backup_todb($course_header->course_summary
);
674 $course->format
= addslashes($course_header->course_format
);
675 $course->showgrades
= addslashes($course_header->course_showgrades
);
676 $course->newsitems
= addslashes($course_header->course_newsitems
);
677 $course->teacher
= addslashes($course_header->course_teacher
);
678 $course->teachers
= addslashes($course_header->course_teachers
);
679 $course->student
= addslashes($course_header->course_student
);
680 $course->students
= addslashes($course_header->course_students
);
681 $course->guest
= addslashes($course_header->course_guest
);
682 $course->startdate
= addslashes($course_header->course_startdate
);
683 $course->startdate +
= $restore->course_startdateoffset
;
684 $course->numsections
= addslashes($course_header->course_numsections
);
685 //$course->showrecent = addslashes($course_header->course_showrecent); INFO: This is out in 1.3
686 $course->maxbytes
= addslashes($course_header->course_maxbytes
);
687 $course->showreports
= addslashes($course_header->course_showreports
);
688 if (isset($course_header->course_groupmode
)) {
689 $course->groupmode
= addslashes($course_header->course_groupmode
);
691 if (isset($course_header->course_groupmodeforce
)) {
692 $course->groupmodeforce
= addslashes($course_header->course_groupmodeforce
);
694 if (isset($course_header->course_defaultgroupingid
)) {
695 //keep the original now - convert after groupings restored
696 $course->defaultgroupingid
= addslashes($course_header->course_defaultgroupingid
);
698 $course->lang
= addslashes($course_header->course_lang
);
699 $course->theme
= addslashes($course_header->course_theme
);
700 $course->cost
= addslashes($course_header->course_cost
);
701 $course->currency
= isset($course_header->course_currency
)?
addslashes($course_header->course_currency
):'';
702 $course->marker
= addslashes($course_header->course_marker
);
703 $course->visible
= addslashes($course_header->course_visible
);
704 $course->hiddensections
= addslashes($course_header->course_hiddensections
);
705 $course->timecreated
= addslashes($course_header->course_timecreated
);
706 $course->timemodified
= addslashes($course_header->course_timemodified
);
707 $course->metacourse
= addslashes($course_header->course_metacourse
);
708 $course->expirynotify
= isset($course_header->course_expirynotify
) ?
addslashes($course_header->course_expirynotify
):0;
709 $course->notifystudents
= isset($course_header->course_notifystudents
) ?
addslashes($course_header->course_notifystudents
) : 0;
710 $course->expirythreshold
= isset($course_header->course_expirythreshold
) ?
addslashes($course_header->course_expirythreshold
) : 0;
711 $course->enrollable
= isset($course_header->course_enrollable
) ?
addslashes($course_header->course_enrollable
) : 1;
712 $course->enrolstartdate
= isset($course_header->course_enrolstartdate
) ?
addslashes($course_header->course_enrolstartdate
) : 0;
713 if ($course->enrolstartdate
) { //Roll course dates
714 $course->enrolstartdate +
= $restore->course_startdateoffset
;
716 $course->enrolenddate
= isset($course_header->course_enrolenddate
) ?
addslashes($course_header->course_enrolenddate
) : 0;
717 if ($course->enrolenddate
) { //Roll course dates
718 $course->enrolenddate +
= $restore->course_startdateoffset
;
720 $course->enrolperiod
= addslashes($course_header->course_enrolperiod
);
721 //Calculate sortorder field
722 $sortmax = get_record_sql('SELECT MAX(sortorder) AS max
723 FROM ' . $CFG->prefix
. 'course
724 WHERE category=' . $course->category
);
725 if (!empty($sortmax->max
)) {
726 $course->sortorder
= $sortmax->max +
1;
729 $course->sortorder
= 100;
732 //Now, recode some languages (Moodle 1.5)
733 if ($course->lang
== 'ma_nt') {
734 $course->lang
= 'mi_nt';
737 //Disable course->metacourse if avoided in restore config
738 if (!$restore->metacourse
) {
739 $course->metacourse
= 0;
742 //Check if the theme exists in destination server
743 $themes = get_list_of_themes();
744 if (!in_array($course->theme
, $themes)) {
748 //Now insert the record
749 $newid = insert_record("course",$course);
751 //save old and new course id
752 backup_putid ($restore->backup_unique_code
,"course",$course_header->course_id
,$newid);
753 //Replace old course_id in course_header
754 $course_header->course_id
= $newid;
765 //This function creates all the block stuff when restoring courses
766 //It calls selectively to restore_create_block_instances() for 1.5
767 //and above backups. Upwards compatible with old blocks.
768 function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) {
772 delete_records('block_instance', 'pageid', $restore->course_id
, 'pagetype', PAGE_COURSE_VIEW
);
773 if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5
774 if (empty($blockinfo)) {
775 // Looks like it's from Moodle < 1.3. Let's give the course default blocks...
776 $newpage = page_create_object(PAGE_COURSE_VIEW
, $restore->course_id
);
777 blocks_repopulate_page($newpage);
778 } else if (!empty($CFG->showblocksonmodpages
)) {
779 // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup
780 $blockrecords = get_records_select('block', '', '', 'name, id');
781 $temp_blocks_l = array();
782 $temp_blocks_r = array();
783 @list
($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo);
784 $temp_blocks = array(BLOCK_POS_LEFT
=> explode(',', $temp_blocks_l), BLOCK_POS_RIGHT
=> explode(',', $temp_blocks_r));
785 foreach($temp_blocks as $blockposition => $blocks) {
787 foreach($blocks as $blockname) {
788 if(!isset($blockrecords[$blockname])) {
789 // We don't know anything about this block!
792 $blockinstance = new stdClass
;
793 // Remove any - prefix before doing the name-to-id mapping
794 if(substr($blockname, 0, 1) == '-') {
795 $blockname = substr($blockname, 1);
796 $blockinstance->visible
= 0;
798 $blockinstance->visible
= 1;
800 $blockinstance->blockid
= $blockrecords[$blockname]->id
;
801 $blockinstance->pageid
= $restore->course_id
;
802 $blockinstance->pagetype
= PAGE_COURSE_VIEW
;
803 $blockinstance->position
= $blockposition;
804 $blockinstance->weight
= $blockweight;
805 if(!$status = insert_record('block_instance', $blockinstance)) {
812 } else if($backup_block_format == 'instances') {
813 $status = restore_create_block_instances($restore,$xml_file);
820 //This function creates all the block_instances from xml when restoring in a
822 function restore_create_block_instances($restore,$xml_file) {
827 if (!file_exists($xml_file)) {
832 $info = restore_read_xml_blocks($restore,$xml_file);
835 if(empty($info->instances
)) {
839 // First of all, iterate over the blocks to see which distinct pages we have
840 // in our hands and arrange the blocks accordingly.
841 $pageinstances = array();
842 foreach($info->instances
as $instance) {
844 //pagetype and pageid black magic, we have to handle the case of blocks for the
845 //course, blocks from other pages in that course etc etc etc.
847 if($instance->pagetype
== PAGE_COURSE_VIEW
) {
848 // This one's easy...
849 $instance->pageid
= $restore->course_id
;
851 } else if (!empty($CFG->showblocksonmodpages
)) {
852 $parts = explode('-', $instance->pagetype
);
853 if($parts[0] == 'mod') {
854 if(!$restore->mods
[$parts[1]]->restore
) {
857 $getid = backup_getid($restore->backup_unique_code
, $parts[1], $instance->pageid
);
859 if (empty($getid->new_id
)) {
860 // Failed, perhaps the module was not included in the restore MDL-13554
863 $instance->pageid
= $getid->new_id
;
866 // Not invented here ;-)
871 // do not restore activity blocks if disabled
875 if(!isset($pageinstances[$instance->pagetype
])) {
876 $pageinstances[$instance->pagetype
] = array();
878 if(!isset($pageinstances[$instance->pagetype
][$instance->pageid
])) {
879 $pageinstances[$instance->pagetype
][$instance->pageid
] = array();
882 $pageinstances[$instance->pagetype
][$instance->pageid
][] = $instance;
885 $blocks = get_records_select('block', 'visible = 1', '', 'name, id, multiple');
887 // For each type of page we have restored
888 foreach($pageinstances as $thistypeinstances) {
890 // For each page id of that type
891 foreach($thistypeinstances as $thisidinstances) {
893 $addedblocks = array();
894 $maxweights = array();
896 // For each block instance in that page
897 foreach($thisidinstances as $instance) {
899 if(!isset($blocks[$instance->name
])) {
900 //We are trying to restore a block we don't have...
904 //If we have already added this block once and multiples aren't allowed, disregard it
905 if(!$blocks[$instance->name
]->multiple
&& isset($addedblocks[$instance->name
])) {
909 //If its the first block we add to a new position, start weight counter equal to 0.
910 if(empty($maxweights[$instance->position
])) {
911 $maxweights[$instance->position
] = 0;
914 //If the instance weight is greater than the weight counter (we skipped some earlier
915 //blocks most probably), bring it back in line.
916 if($instance->weight
> $maxweights[$instance->position
]) {
917 $instance->weight
= $maxweights[$instance->position
];
921 $instance->blockid
= $blocks[$instance->name
]->id
;
923 // This will only be set if we come from 1.7 and above backups
924 // Also, must do this before insert (insert_record unsets id)
925 if (!empty($instance->id
)) {
926 $oldid = $instance->id
;
931 if ($instance->id
= insert_record('block_instance', $instance)) {
932 // Create block instance
933 if (!$blockobj = block_instance($instance->name
, $instance)) {
937 // Run the block restore if needed
938 if ($blockobj->backuprestore_instancedata_used()) {
939 // Get restore information
940 $data = backup_getid($restore->backup_unique_code
,'block_instance',$oldid);
941 $data->new_id
= $instance->id
; // For completeness
942 if (!$blockobj->instance_restore($restore, $data)) {
947 // Save oldid after block restore process because info will be over-written with blank string
949 backup_putid ($restore->backup_unique_code
,"block_instance",$oldid,$instance->id
);
957 //Get an object for the block and tell it it's been restored so it can update dates
959 if ($blockobj = block_instance($instance->name
,$instance)) {
960 $blockobj->after_restore($restore);
963 //Now we can increment the weight counter
964 ++
$maxweights[$instance->position
];
966 //Keep track of block types we have already added
967 $addedblocks[$instance->name
] = true;
976 //This function creates all the course_sections and course_modules from xml
977 //when restoring in a new course or simply checks sections and create records
978 //in backup_ids when restoring in a existing course
979 function restore_create_sections(&$restore, $xml_file) {
985 if (!file_exists($xml_file)) {
990 $info = restore_read_xml_sections($xml_file);
992 //Put the info in the DB, recoding ids and saving the in backup tables
997 //For each, section, save it to db
998 foreach ($info->sections
as $key => $sect) {
1000 $section = new object();
1001 $section->course
= $restore->course_id
;
1002 $section->section
= $sect->number
;
1003 $section->summary
= backup_todb($sect->summary
);
1004 $section->visible
= $sect->visible
;
1005 $section->sequence
= "";
1006 //Now calculate the section's newid
1008 if ($restore->restoreto
== 2) {
1009 //Save it to db (only if restoring to new course)
1010 $newid = insert_record("course_sections",$section);
1012 //Get section id when restoring in existing course
1013 $rec = get_record("course_sections","course",$restore->course_id
,
1014 "section",$section->section
);
1015 //If that section doesn't exist, get section 0 (every mod will be
1018 $rec = get_record("course_sections","course",$restore->course_id
,
1021 //New check. If section 0 doesn't exist, insert it here !!
1022 //Teorically this never should happen but, in practice, some users
1023 //have reported this issue.
1025 $zero_sec = new object();
1026 $zero_sec->course
= $restore->course_id
;
1027 $zero_sec->section
= 0;
1028 $zero_sec->summary
= "";
1029 $zero_sec->sequence
= "";
1030 $newid = insert_record("course_sections",$zero_sec);
1032 $rec->sequence
= "";
1035 $sequence = $rec->sequence
;
1038 //save old and new section id
1039 backup_putid ($restore->backup_unique_code
,"course_sections",$key,$newid);
1043 //If all is OK, go with associated mods
1045 //If we have mods in the section
1046 if (!empty($sect->mods
)) {
1047 //For each mod inside section
1048 foreach ($sect->mods
as $keym => $mod) {
1049 // Yu: This part is called repeatedly for every instance,
1050 // so it is necessary to set the granular flag and check isset()
1051 // when the first instance of this type of mod is processed.
1053 //if (!isset($restore->mods[$mod->type]->granular) && isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) {
1055 if (!isset($restore->mods
[$mod->type
]->granular
)) {
1056 if (isset($restore->mods
[$mod->type
]->instances
) && is_array($restore->mods
[$mod->type
]->instances
)) {
1057 // This defines whether we want to restore specific
1058 // instances of the modules (granular restore), or
1059 // whether we don't care and just want to restore
1060 // all module instances (non-granular).
1061 $restore->mods
[$mod->type
]->granular
= true;
1063 $restore->mods
[$mod->type
]->granular
= false;
1067 //Check if we've to restore this module (and instance)
1068 if (!empty($restore->mods
[$mod->type
]->restore
)) {
1069 if (empty($restore->mods
[$mod->type
]->granular
) // we don't care about per instance
1070 ||
(array_key_exists($mod->instance
,$restore->mods
[$mod->type
]->instances
)
1071 && !empty($restore->mods
[$mod->type
]->instances
[$mod->instance
]->restore
))) {
1073 //Get the module id from modules
1074 $module = get_record("modules","name",$mod->type
);
1076 $course_module = new object();
1077 $course_module->course
= $restore->course_id
;
1078 $course_module->module
= $module->id
;
1079 $course_module->section
= $newid;
1080 $course_module->added
= $mod->added
;
1081 $course_module->score
= $mod->score
;
1082 $course_module->indent
= $mod->indent
;
1083 $course_module->visible
= $mod->visible
;
1084 $course_module->groupmode
= $mod->groupmode
;
1085 if ($mod->groupingid
and $grouping = restore_grouping_getid($restore, $mod->groupingid
)) {
1086 $course_module->groupingid
= $grouping->new_id
;
1088 $course_module->groupingid
= 0;
1090 $course_module->groupmembersonly
= $mod->groupmembersonly
;
1091 $course_module->instance
= 0;
1092 //NOTE: The instance (new) is calculated and updated in db in the
1093 // final step of the restore. We don't know it yet.
1094 //print_object($course_module); //Debug
1096 if ($mod->idnumber
) {
1097 if (grade_verify_idnumber($mod->idnumber
, $restore->course_id
)) {
1098 $course_module->idnumber
= $mod->idnumber
;
1102 $newidmod = insert_record("course_modules", addslashes_recursive($course_module));
1104 //save old and new module id
1105 //In the info field, we save the original instance of the module
1107 backup_putid ($restore->backup_unique_code
,"course_modules",
1108 $keym,$newidmod,$mod->instance
);
1110 $restore->mods
[$mod->type
]->instances
[$mod->instance
]->restored_as_course_module
= $newidmod;
1114 //Now, calculate the sequence field
1117 $sequence .= ",".$newidmod;
1119 $sequence = $newidmod;
1130 //If all is OK, update sequence field in course_sections
1132 if (isset($sequence)) {
1133 $update_rec = new object();
1134 $update_rec->id
= $newid;
1135 $update_rec->sequence
= $sequence;
1136 $status = update_record("course_sections",$update_rec);
1146 //Called to set up any course-format specific data that may be in the file
1147 function restore_set_format_data($restore,$xml_file) {
1152 if (!file_exists($xml_file)) {
1155 //Load data from XML to info
1156 if(!($info = restore_read_xml_formatdata($xml_file))) {
1160 //Process format data if there is any
1161 if (isset($info->format_data
)) {
1162 if(!$format=get_field('course','format','id',$restore->course_id
)) {
1165 // If there was any data then it must have a restore method
1166 $file=$CFG->dirroot
."/course/format/$format/restorelib.php";
1167 if(!file_exists($file)) {
1170 require_once($file);
1171 $function=$format.'_restore_format_data';
1172 if(!function_exists($function)) {
1175 return $function($restore,$info->format_data
);
1178 // If we got here then there's no data, but that's cool
1182 //This function creates all the metacourse data from xml, notifying
1183 //about each incidence
1184 function restore_create_metacourse($restore,$xml_file) {
1190 if (!file_exists($xml_file)) {
1195 //Load data from XML to info
1196 $info = restore_read_xml_metacourse($xml_file);
1199 //Process info about metacourse
1200 if ($status and $info) {
1201 //Process child records
1202 if (!empty($info->childs
)) {
1203 foreach ($info->childs
as $child) {
1205 $dbmetacourse = false;
1206 //Check if child course exists in destination server
1207 //(by id in the same server or by idnumber and shortname in other server)
1208 if ($restore->original_wwwroot
== $CFG->wwwroot
) {
1209 //Same server, lets see by id
1210 $dbcourse = get_record('course','id',$child->id
);
1212 //Different server, lets see by idnumber and shortname, and only ONE record
1213 $dbcount = count_records('course','idnumber',$child->idnumber
,'shortname',$child->shortname
);
1214 if ($dbcount == 1) {
1215 $dbcourse = get_record('course','idnumber',$child->idnumber
,'shortname',$child->shortname
);
1218 //If child course has been found, insert data
1220 $dbmetacourse->child_course
= $dbcourse->id
;
1221 $dbmetacourse->parent_course
= $restore->course_id
;
1222 $status = insert_record ('course_meta',$dbmetacourse);
1224 //Child course not found, notice!
1225 if (!defined('RESTORE_SILENTLY')) {
1226 echo '<ul><li>'.get_string ('childcoursenotfound').' ('.$child->id
.'/'.$child->idnumber
.'/'.$child->shortname
.')</li></ul>';
1230 //Now, recreate student enrolments...
1231 sync_metacourse($restore->course_id
);
1233 //Process parent records
1234 if (!empty($info->parents
)) {
1235 foreach ($info->parents
as $parent) {
1237 $dbmetacourse = false;
1238 //Check if parent course exists in destination server
1239 //(by id in the same server or by idnumber and shortname in other server)
1240 if ($restore->original_wwwroot
== $CFG->wwwroot
) {
1241 //Same server, lets see by id
1242 $dbcourse = get_record('course','id',$parent->id
);
1244 //Different server, lets see by idnumber and shortname, and only ONE record
1245 $dbcount = count_records('course','idnumber',$parent->idnumber
,'shortname',$parent->shortname
);
1246 if ($dbcount == 1) {
1247 $dbcourse = get_record('course','idnumber',$parent->idnumber
,'shortname',$parent->shortname
);
1250 //If parent course has been found, insert data if it is a metacourse
1252 if ($dbcourse->metacourse
) {
1253 $dbmetacourse->parent_course
= $dbcourse->id
;
1254 $dbmetacourse->child_course
= $restore->course_id
;
1255 $status = insert_record ('course_meta',$dbmetacourse);
1256 //Now, recreate student enrolments in parent course
1257 sync_metacourse($dbcourse->id
);
1259 //Parent course isn't metacourse, notice!
1260 if (!defined('RESTORE_SILENTLY')) {
1261 echo '<ul><li>'.get_string ('parentcoursenotmetacourse').' ('.$parent->id
.'/'.$parent->idnumber
.'/'.$parent->shortname
.')</li></ul>';
1265 //Parent course not found, notice!
1266 if (!defined('RESTORE_SILENTLY')) {
1267 echo '<ul><li>'.get_string ('parentcoursenotfound').' ('.$parent->id
.'/'.$parent->idnumber
.'/'.$parent->shortname
.')</li></ul>';
1278 * This function migrades all the pre 1.9 gradebook data from xml
1280 function restore_migrate_old_gradebook($restore,$xml_file) {
1285 if (!file_exists($xml_file)) {
1289 // Get info from xml
1290 // info will contain the number of record to process
1291 $info = restore_read_xml_gradebook($restore, $xml_file);
1293 // If we have info, then process
1298 // make sure top course category exists
1299 $course_category = grade_category
::fetch_course_category($restore->course_id
);
1300 $course_category->load_grade_item();
1302 // we need to know if all grade items that were backed up are being restored
1303 // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
1304 // i.e. the aggregated grades of that category
1306 $restoreall = true; // set to false if any grade_item is not selected/restored
1307 $importing = !empty($SESSION->restore
->importing
); // there should not be a way to import old backups, but anyway ;-)
1310 $restoreall = false;
1313 $prev_grade_items = grade_item
::fetch_all(array('courseid'=>$restore->course_id
));
1314 $prev_grade_cats = grade_category
::fetch_all(array('courseid'=>$restore->course_id
));
1316 // if any categories already present, skip restore of categories from backup
1317 if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) {
1318 $restoreall = false;
1320 unset($prev_grade_items);
1321 unset($prev_grade_cats);
1324 // force creation of all grade_items - the course_modules already exist
1325 grade_force_full_regrading($restore->course_id
);
1326 grade_grab_course_grades($restore->course_id
);
1329 if (!defined('RESTORE_SILENTLY')) {
1334 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
1335 // respect current grade letters if defined
1336 if ($status and $restoreall and !record_exists('grade_letters', 'contextid', $context->id
)) {
1337 if (!defined('RESTORE_SILENTLY')) {
1338 echo '<li>'.get_string('gradeletters','grades').'</li>';
1340 // Fetch recordset_size records in each iteration
1341 $recs = get_records_select("backup_ids","table_name = 'grade_letter' AND backup_code = $restore->backup_unique_code",
1345 foreach ($recs as $rec) {
1346 // Get the full record from backup_ids
1347 $data = backup_getid($restore->backup_unique_code
,'grade_letter',$rec->old_id
);
1349 $info = $data->info
;
1350 $dbrec = new object();
1351 $dbrec->contextid
= $context->id
;
1352 $dbrec->lowerboundary
= backup_todb($info['GRADE_LETTER']['#']['GRADE_LOW']['0']['#']);
1353 $dbrec->letter
= backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
1354 insert_record('grade_letters', $dbrec);
1360 if (!defined('RESTORE_SILENTLY')) {
1361 echo '<li>'.get_string('categories','grades').'</li>';
1363 //Fetch recordset_size records in each iteration
1364 $recs = get_records_select("backup_ids","table_name = 'grade_category' AND backup_code = $restore->backup_unique_code",
1367 $cat_count = count($recs);
1369 foreach ($recs as $rec) {
1370 //Get the full record from backup_ids
1371 $data = backup_getid($restore->backup_unique_code
,'grade_category',$rec->old_id
);
1373 //Now get completed xmlized object
1374 $info = $data->info
;
1377 if ($cat_count == 1) {
1378 $course_category->fullname
= backup_todb($info['GRADE_CATEGORY']['#']['NAME']['0']['#'], false);
1379 $course_category->droplow
= backup_todb($info['GRADE_CATEGORY']['#']['DROP_X_LOWEST']['0']['#'], false);
1380 $course_category->aggregation
= GRADE_AGGREGATE_WEIGHTED_MEAN2
;
1381 $course_category->aggregateonlygraded
= 0;
1382 $course_category->update('restore');
1383 $grade_category = $course_category;
1386 $grade_category = new grade_category();
1387 $grade_category->courseid
= $restore->course_id
;
1388 $grade_category->fullname
= backup_todb($info['GRADE_CATEGORY']['#']['NAME']['0']['#'], false);
1389 $grade_category->droplow
= backup_todb($info['GRADE_CATEGORY']['#']['DROP_X_LOWEST']['0']['#'], false);
1390 $grade_category->aggregation
= GRADE_AGGREGATE_WEIGHTED_MEAN2
;
1391 $grade_category->aggregateonlygraded
= 0;
1392 $grade_category->insert('restore');
1393 $grade_category->load_grade_item(); // force cretion of grade_item
1397 $grade_category = null;
1400 /// now, restore grade_items
1402 if (!empty($info['GRADE_CATEGORY']['#']['GRADE_ITEMS']['0']['#']['GRADE_ITEM'])) {
1403 //Iterate over items
1404 foreach ($info['GRADE_CATEGORY']['#']['GRADE_ITEMS']['0']['#']['GRADE_ITEM'] as $ite_info) {
1405 $modname = backup_todb($ite_info['#']['MODULE_NAME']['0']['#'], false);
1406 $olditeminstance = backup_todb($ite_info['#']['CMINSTANCE']['0']['#'], false);
1407 if (!$mod = backup_getid($restore->backup_unique_code
,$modname, $olditeminstance)) {
1408 continue; // not restored
1410 $iteminstance = $mod->new_id
;
1411 if (!$cm = get_coursemodule_from_instance($modname, $iteminstance, $restore->course_id
)) {
1412 continue; // does not exist
1415 if (!$grade_item = grade_item
::fetch(array('itemtype'=>'mod', 'itemmodule'=>$cm->modname
, 'iteminstance'=>$cm->instance
, 'courseid'=>$cm->course
, 'itemnumber'=>0))) {
1416 continue; // no item yet??
1419 if ($grade_category) {
1420 $grade_item->sortorder
= backup_todb($ite_info['#']['SORT_ORDER']['0']['#'], false);
1421 $grade_item->set_parent($grade_category->id
);
1425 or ($grade_item->itemtype
== 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule
, $olditeminstance))) {
1426 // module instance not selected when restored using granular
1431 //Now process grade excludes
1432 if (empty($ite_info['#']['GRADE_EXCEPTIONS'])) {
1436 foreach($ite_info['#']['GRADE_EXCEPTIONS']['0']['#']['GRADE_EXCEPTION'] as $exc_info) {
1437 if ($u = backup_getid($restore->backup_unique_code
,"user",backup_todb($exc_info['#']['USERID']['0']['#']))) {
1438 $userid = $u->new_id
;
1439 $grade_grade = new grade_grade(array('itemid'=>$grade_item->id
, 'userid'=>$userid));
1440 $grade_grade->excluded
= 1;
1441 if ($grade_grade->id
) {
1442 $grade_grade->update('restore');
1444 $grade_grade->insert('restore');
1454 if (!defined('RESTORE_SILENTLY')) {
1463 * This function creates all the gradebook data from xml
1465 function restore_create_gradebook($restore,$xml_file) {
1470 if (!file_exists($xml_file)) {
1474 // Get info from xml
1475 // info will contain the number of record to process
1476 $info = restore_read_xml_gradebook($restore, $xml_file);
1478 // If we have info, then process
1483 if (empty($CFG->disablegradehistory
) and isset($info->gradebook_histories
) and $info->gradebook_histories
== "true") {
1484 $restore_histories = true;
1486 $restore_histories = false;
1489 // make sure top course category exists
1490 $course_category = grade_category
::fetch_course_category($restore->course_id
);
1491 $course_category->load_grade_item();
1493 // we need to know if all grade items that were backed up are being restored
1494 // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
1495 // i.e. the aggregated grades of that category
1497 $restoreall = true; // set to false if any grade_item is not selected/restored or already exist
1498 $importing = !empty($SESSION->restore
->importing
);
1501 $restoreall = false;
1504 $prev_grade_items = grade_item
::fetch_all(array('courseid'=>$restore->course_id
));
1505 $prev_grade_cats = grade_category
::fetch_all(array('courseid'=>$restore->course_id
));
1507 // if any categories already present, skip restore of categories from backup - course item or category already exist
1508 if (count($prev_grade_items) > 1 or count($prev_grade_cats) > 1) {
1509 $restoreall = false;
1511 unset($prev_grade_items);
1512 unset($prev_grade_cats);
1515 if ($recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = $restore->backup_unique_code", "", "old_id")) {
1516 foreach ($recs as $rec) {
1517 if ($data = backup_getid($restore->backup_unique_code
,'grade_items',$rec->old_id
)) {
1519 $info = $data->info
;
1520 // do not restore if this grade_item is a mod, and
1521 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1523 if ($itemtype == 'mod') {
1524 $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1525 $itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1527 if (empty($restore->mods
[$itemmodule]->granular
)) {
1529 } else if (!empty($restore->mods
[$itemmodule]->instances
[$olditeminstance]->restore
)) {
1532 // at least one activity should not be restored - do not restore categories and manual items at all
1533 $restoreall = false;
1543 if (!defined('RESTORE_SILENTLY')) {
1547 // array of restored categories - speedup ;-)
1548 $cached_categories = array();
1549 $outcomes = array();
1552 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
1553 // respect current grade letters if defined
1554 if ($status and $restoreall and !record_exists('grade_letters', 'contextid', $context->id
)) {
1555 if (!defined('RESTORE_SILENTLY')) {
1556 echo '<li>'.get_string('gradeletters','grades').'</li>';
1558 // Fetch recordset_size records in each iteration
1559 $recs = get_records_select("backup_ids","table_name = 'grade_letters' AND backup_code = $restore->backup_unique_code",
1563 foreach ($recs as $rec) {
1564 // Get the full record from backup_ids
1565 $data = backup_getid($restore->backup_unique_code
,'grade_letters',$rec->old_id
);
1567 $info = $data->info
;
1568 $dbrec = new object();
1569 $dbrec->contextid
= $context->id
;
1570 $dbrec->lowerboundary
= backup_todb($info['GRADE_LETTER']['#']['LOWERBOUNDARY']['0']['#']);
1571 $dbrec->letter
= backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
1572 insert_record('grade_letters', $dbrec);
1578 /// Preprocess outcomes - do not store them yet!
1579 if ($status and !$importing and $restoreall) {
1580 if (!defined('RESTORE_SILENTLY')) {
1581 echo '<li>'.get_string('gradeoutcomes','grades').'</li>';
1583 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes' AND backup_code = '$restore->backup_unique_code'",
1587 foreach ($recs as $rec) {
1588 //Get the full record from backup_ids
1589 $data = backup_getid($restore->backup_unique_code
,'grade_outcomes',$rec->old_id
);
1591 $info = $data->info
;
1593 //first find out if outcome already exists
1594 $shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']);
1596 if ($candidates = get_records_sql("SELECT *
1597 FROM {$CFG->prefix}grade_outcomes
1598 WHERE (courseid IS NULL OR courseid = $restore->course_id)
1599 AND shortname = '$shortname'
1600 ORDER BY courseid ASC, id ASC")) {
1601 $grade_outcome = reset($candidates);
1602 $outcomes[$rec->old_id
] = $grade_outcome;
1606 $dbrec = new object();
1608 if (has_capability('moodle/grade:manageoutcomes', get_context_instance(CONTEXT_SYSTEM
))) {
1609 $oldoutcome = backup_todb($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#']);
1610 if (empty($oldoutcome)) {
1612 $dbrec->courseid
= null;
1615 $dbrec->courseid
= $restore->course_id
;
1618 // no permission to add site outcomes
1619 $dbrec->courseid
= $restore->course_id
;
1623 $dbrec->shortname
= backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#'], false);
1624 $dbrec->fullname
= backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#'], false);
1625 $dbrec->scaleid
= backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#'], false);
1626 $dbrec->description
= backup_todb($info['GRADE_OUTCOME']['#']['DESCRIPTION']['0']['#'], false);
1627 $dbrec->timecreated
= backup_todb($info['GRADE_OUTCOME']['#']['TIMECREATED']['0']['#'], false);
1628 $dbrec->timemodified
= backup_todb($info['GRADE_OUTCOME']['#']['TIMEMODIFIED']['0']['#'], false);
1629 $dbrec->usermodified
= backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#'], false);
1631 //Need to recode the scaleid
1632 if ($scale = backup_getid($restore->backup_unique_code
, 'scale', $dbrec->scaleid
)) {
1633 $dbrec->scaleid
= $scale->new_id
;
1636 //Need to recode the usermodified
1637 if ($modifier = backup_getid($restore->backup_unique_code
, 'user', $dbrec->usermodified
)) {
1638 $dbrec->usermodified
= $modifier->new_id
;
1641 $grade_outcome = new grade_outcome($dbrec, false);
1642 $outcomes[$rec->old_id
] = $grade_outcome;
1648 /// Process grade items and grades
1650 if (!defined('RESTORE_SILENTLY')) {
1651 echo '<li>'.get_string('gradeitems','grades').'</li>';
1655 //Fetch recordset_size records in each iteration
1656 $recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'",
1657 "id", // restore in the backup order
1661 foreach ($recs as $rec) {
1662 //Get the full record from backup_ids
1663 $data = backup_getid($restore->backup_unique_code
,'grade_items',$rec->old_id
);
1665 $info = $data->info
;
1667 // first find out if category or normal item
1668 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
1669 if ($itemtype == 'course' or $itemtype == 'category') {
1670 if (!$restoreall or $importing) {
1674 $oldcat = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
1675 if (!$cdata = backup_getid($restore->backup_unique_code
,'grade_categories',$oldcat)) {
1678 $cinfo = $cdata->info
;
1680 if ($itemtype == 'course') {
1682 $course_category->fullname
= backup_todb($cinfo['GRADE_CATEGORY']['#']['FULLNAME']['0']['#'], false);
1683 $course_category->aggregation
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#'], false);
1684 $course_category->keephigh
= backup_todb($cinfo['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#'], false);
1685 $course_category->droplow
= backup_todb($cinfo['GRADE_CATEGORY']['#']['DROPLOW']['0']['#'], false);
1686 $course_category->aggregateonlygraded
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEONLYGRADED']['0']['#'], false);
1687 $course_category->aggregateoutcomes
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#'], false);
1688 $course_category->aggregatesubcats
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATESUBCATS']['0']['#'], false);
1689 $course_category->timecreated
= backup_todb($cinfo['GRADE_CATEGORY']['#']['TIMECREATED']['0']['#'], false);
1690 $course_category->update('restore');
1692 $status = backup_putid($restore->backup_unique_code
,'grade_categories',$oldcat,$course_category->id
) && $status;
1693 $cached_categories[$oldcat] = $course_category;
1694 $grade_item = $course_category->get_grade_item();
1697 $oldparent = backup_todb($cinfo['GRADE_CATEGORY']['#']['PARENT']['0']['#'], false);
1698 if (empty($cached_categories[$oldparent])) {
1699 debugging('parent not found '.$oldparent);
1700 continue; // parent not found, sorry
1702 $grade_category = new grade_category();
1703 $grade_category->courseid
= $restore->course_id
;
1704 $grade_category->parent
= $cached_categories[$oldparent]->id
;
1705 $grade_category->fullname
= backup_todb($cinfo['GRADE_CATEGORY']['#']['FULLNAME']['0']['#'], false);
1706 $grade_category->aggregation
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#'], false);
1707 $grade_category->keephigh
= backup_todb($cinfo['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#'], false);
1708 $grade_category->droplow
= backup_todb($cinfo['GRADE_CATEGORY']['#']['DROPLOW']['0']['#'], false);
1709 $grade_category->aggregateonlygraded
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEONLYGRADED']['0']['#'], false);
1710 $grade_category->aggregateoutcomes
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#'], false);
1711 $grade_category->aggregatesubcats
= backup_todb($cinfo['GRADE_CATEGORY']['#']['AGGREGATESUBCATS']['0']['#'], false);
1712 $grade_category->timecreated
= backup_todb($cinfo['GRADE_CATEGORY']['#']['TIMECREATED']['0']['#'], false);
1713 $grade_category->insert('restore');
1715 $status = backup_putid($restore->backup_unique_code
,'grade_categories',$oldcat,$grade_category->id
) && $status;
1716 $cached_categories[$oldcat] = $grade_category;
1717 $grade_item = $grade_category->get_grade_item(); // creates grade_item too
1721 $idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#'], false);
1722 if (grade_verify_idnumber($idnumber, $restore->course_id
)) {
1723 $grade_item->idnumber
= $idnumber;
1726 $grade_item->itemname
= backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#'], false);
1727 $grade_item->iteminfo
= backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#'], false);
1728 $grade_item->gradetype
= backup_todb($info['GRADE_ITEM']['#']['GRADETYPE']['0']['#'], false);
1729 $grade_item->calculation
= backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#'], false);
1730 $grade_item->grademax
= backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#'], false);
1731 $grade_item->grademin
= backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#'], false);
1732 $grade_item->gradepass
= backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#'], false);
1733 $grade_item->multfactor
= backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#'], false);
1734 $grade_item->plusfactor
= backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#'], false);
1735 $grade_item->aggregationcoef
= backup_todb($info['GRADE_ITEM']['#']['AGGREGATIONCOEF']['0']['#'], false);
1736 $grade_item->display
= backup_todb($info['GRADE_ITEM']['#']['DISPLAY']['0']['#'], false);
1737 $grade_item->decimals
= backup_todb($info['GRADE_ITEM']['#']['DECIMALS']['0']['#'], false);
1738 $grade_item->hidden
= backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#'], false);
1739 $grade_item->locked
= backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#'], false);
1740 $grade_item->locktime
= backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#'], false);
1741 $grade_item->timecreated
= backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#'], false);
1743 if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false)) {
1744 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false));
1745 $grade_item->scaleid
= $scale->new_id
;
1748 if (backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'], false)) {
1749 $outcome = backup_getid($restore->backup_unique_code
,"grade_outcomes",backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'], false));
1750 $grade_item->outcomeid
= $outcome->new_id
;
1753 $grade_item->update('restore');
1754 $status = backup_putid($restore->backup_unique_code
,"grade_items", $rec->old_id
, $grade_item->id
) && $status;
1757 if ($itemtype != 'mod' and (!$restoreall or $importing)) {
1758 // not extra gradebook stuff if restoring individual activities or something already there
1762 $dbrec = new object();
1764 $dbrec->courseid
= $restore->course_id
;
1765 $dbrec->itemtype
= backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
1766 $dbrec->itemmodule
= backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#'], false);
1768 if ($itemtype == 'mod') {
1769 // iteminstance should point to new mod
1770 $olditeminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#'], false);
1771 $mod = backup_getid($restore->backup_unique_code
,$dbrec->itemmodule
, $olditeminstance);
1772 $dbrec->iteminstance
= $mod->new_id
;
1773 if (!$cm = get_coursemodule_from_instance($dbrec->itemmodule
, $mod->new_id
)) {
1774 // item not restored - no item
1777 // keep in sync with activity idnumber
1778 $dbrec->idnumber
= $cm->idnumber
;
1781 $idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#'], false);
1783 if (grade_verify_idnumber($idnumber, $restore->course_id
)) {
1784 //make sure the new idnumber is unique
1785 $dbrec->idnumber
= $idnumber;
1789 $dbrec->itemname
= backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#'], false);
1790 $dbrec->itemtype
= backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#'], false);
1791 $dbrec->itemmodule
= backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#'], false);
1792 $dbrec->itemnumber
= backup_todb($info['GRADE_ITEM']['#']['ITEMNUMBER']['0']['#'], false);
1793 $dbrec->iteminfo
= backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#'], false);
1794 $dbrec->gradetype
= backup_todb($info['GRADE_ITEM']['#']['GRADETYPE']['0']['#'], false);
1795 $dbrec->calculation
= backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#'], false);
1796 $dbrec->grademax
= backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#'], false);
1797 $dbrec->grademin
= backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#'], false);
1798 $dbrec->gradepass
= backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#'], false);
1799 $dbrec->multfactor
= backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#'], false);
1800 $dbrec->plusfactor
= backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#'], false);
1801 $dbrec->aggregationcoef
= backup_todb($info['GRADE_ITEM']['#']['AGGREGATIONCOEF']['0']['#'], false);
1802 $dbrec->display
= backup_todb($info['GRADE_ITEM']['#']['DISPLAY']['0']['#'], false);
1803 $dbrec->decimals
= backup_todb($info['GRADE_ITEM']['#']['DECIMALS']['0']['#'], false);
1804 $dbrec->hidden
= backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#'], false);
1805 $dbrec->locked
= backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#'], false);
1806 $dbrec->locktime
= backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#'], false);
1807 $dbrec->timecreated
= backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#'], false);
1809 if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false)) {
1810 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'], false));
1811 $dbrec->scaleid
= $scale->new_id
;
1814 if (backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#'])) {
1815 $oldoutcome = backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#']);
1816 if (empty($outcomes[$oldoutcome])) {
1819 if (empty($outcomes[$oldoutcome]->id
)) {
1820 $outcomes[$oldoutcome]->insert('restore');
1821 $outcomes[$oldoutcome]->use_in($restore->course_id
);
1822 backup_putid($restore->backup_unique_code
, "grade_outcomes", $oldoutcome, $outcomes[$oldoutcome]->id
);
1824 $dbrec->outcomeid
= $outcomes[$oldoutcome]->id
;
1827 $grade_item = new grade_item($dbrec, false);
1828 $grade_item->insert('restore');
1830 // set original parent if restored
1831 $oldcat = $info['GRADE_ITEM']['#']['CATEGORYID']['0']['#'];
1832 if (!empty($cached_categories[$oldcat])) {
1833 $grade_item->set_parent($cached_categories[$oldcat]->id
);
1836 $status = backup_putid($restore->backup_unique_code
,"grade_items", $rec->old_id
, $grade_item->id
) && $status;
1839 // no need to restore grades if user data is not selected or importing activities
1841 or ($grade_item->itemtype
== 'mod' and !restore_userdata_selected($restore, $grade_item->itemmodule
, $olditeminstance))) {
1842 // module instance not selected when restored using granular
1847 /// now, restore grade_grades
1848 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'])) {
1849 //Iterate over items
1850 foreach ($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'] as $g_info) {
1852 $grade = new grade_grade();
1853 $grade->itemid
= $grade_item->id
;
1855 $olduser = backup_todb($g_info['#']['USERID']['0']['#'], false);
1856 $user = backup_getid($restore->backup_unique_code
,"user",$olduser);
1857 $grade->userid
= $user->new_id
;
1859 $grade->rawgrade
= backup_todb($g_info['#']['RAWGRADE']['0']['#'], false);
1860 $grade->rawgrademax
= backup_todb($g_info['#']['RAWGRADEMAX']['0']['#'], false);
1861 $grade->rawgrademin
= backup_todb($g_info['#']['RAWGRADEMIN']['0']['#'], false);
1862 // need to find scaleid
1863 if (backup_todb($g_info['#']['RAWSCALEID']['0']['#'])) {
1864 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($g_info['#']['RAWSCALEID']['0']['#'], false));
1865 $grade->rawscaleid
= $scale->new_id
;
1868 if (backup_todb($g_info['#']['USERMODIFIED']['0']['#'])) {
1869 if ($modifier = backup_getid($restore->backup_unique_code
,"user", backup_todb($g_info['#']['USERMODIFIED']['0']['#'], false))) {
1870 $grade->usermodified
= $modifier->new_id
;
1874 $grade->finalgrade
= backup_todb($g_info['#']['FINALGRADE']['0']['#'], false);
1875 $grade->hidden
= backup_todb($g_info['#']['HIDDEN']['0']['#'], false);
1876 $grade->locked
= backup_todb($g_info['#']['LOCKED']['0']['#'], false);
1877 $grade->locktime
= backup_todb($g_info['#']['LOCKTIME']['0']['#'], false);
1878 $grade->exported
= backup_todb($g_info['#']['EXPORTED']['0']['#'], false);
1879 $grade->overridden
= backup_todb($g_info['#']['OVERRIDDEN']['0']['#'], false);
1880 $grade->excluded
= backup_todb($g_info['#']['EXCLUDED']['0']['#'], false);
1881 $grade->feedback
= backup_todb($g_info['#']['FEEDBACK']['0']['#'], false);
1882 $grade->feedbackformat
= backup_todb($g_info['#']['FEEDBACKFORMAT']['0']['#'], false);
1883 $grade->information
= backup_todb($g_info['#']['INFORMATION']['0']['#'], false);
1884 $grade->informationformat
= backup_todb($g_info['#']['INFORMATIONFORMAT']['0']['#'], false);
1885 $grade->timecreated
= backup_todb($g_info['#']['TIMECREATED']['0']['#'], false);
1886 $grade->timemodified
= backup_todb($g_info['#']['TIMEMODIFIED']['0']['#'], false);
1888 $grade->insert('restore');
1889 backup_putid($restore->backup_unique_code
,"grade_grades", backup_todb($g_info['#']['ID']['0']['#']), $grade->id
);
1892 if ($counter %
20 == 0) {
1893 if (!defined('RESTORE_SILENTLY')) {
1895 if ($counter %
400 == 0) {
1908 /// add outcomes that are not used when doing full restore
1909 if ($status and $restoreall) {
1910 foreach ($outcomes as $oldoutcome=>$grade_outcome) {
1911 if (empty($grade_outcome->id
)) {
1912 $grade_outcome->insert('restore');
1913 $grade_outcome->use_in($restore->course_id
);
1914 backup_putid($restore->backup_unique_code
, "grade_outcomes", $oldoutcome, $grade_outcome->id
);
1920 if ($status and !$importing and $restore_histories) {
1921 /// following code is very inefficient
1923 $gchcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_categories_history');
1924 $gghcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_grades_history');
1925 $gihcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_items_history');
1926 $gohcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_outcomes_history');
1928 // Number of records to get in every chunk
1929 $recordset_size = 2;
1931 // process histories
1932 if ($gchcount && $status) {
1933 if (!defined('RESTORE_SILENTLY')) {
1934 echo '<li>'.get_string('gradecategoryhistory','grades').'</li>';
1937 while ($counter < $gchcount) {
1938 //Fetch recordset_size records in each iteration
1939 $recs = get_records_select("backup_ids","table_name = 'grade_categories_history' AND backup_code = '$restore->backup_unique_code'",
1945 foreach ($recs as $rec) {
1946 //Get the full record from backup_ids
1947 $data = backup_getid($restore->backup_unique_code
,'grade_categories_history',$rec->old_id
);
1949 //Now get completed xmlized object
1950 $info = $data->info
;
1951 //traverse_xmlize($info); //Debug
1952 //print_object ($GLOBALS['traverse_array']); //Debug
1953 //$GLOBALS['traverse_array']=""; //Debug
1955 $oldobj = backup_getid($restore->backup_unique_code
,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['OLDID']['0']['#']));
1956 if (empty($oldobj->new_id
)) {
1957 // if the old object is not being restored, can't restoring its history
1961 $dbrec->oldid
= $oldobj->new_id
;
1962 $dbrec->action
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['ACTION']['0']['#']);
1963 $dbrec->source
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['SOURCE']['0']['#']);
1964 $dbrec->timemodified
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1966 // loggeduser might not be restored, e.g. admin
1967 if ($oldobj = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1968 $dbrec->loggeduser
= $oldobj->new_id
;
1971 // this item might not have a parent at all, do not skip it if no parent is specified
1972 if (backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#'])) {
1973 $oldobj = backup_getid($restore->backup_unique_code
,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#']));
1974 if (empty($oldobj->new_id
)) {
1975 // if the parent category not restored
1980 $dbrec->parent
= $oldobj->new_id
;
1981 $dbrec->depth
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DEPTH']['0']['#']);
1982 // path needs to be rebuilt
1983 if ($path = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PATH']['0']['#'])) {
1984 // to preserve the path and make it work, we need to replace the categories one by one
1985 // we first get the list of categories in current path
1986 if ($paths = explode("/", $path)) {
1988 foreach ($paths as $catid) {
1990 // find the new corresponding path
1991 $oldpath = backup_getid($restore->backup_unique_code
,"grade_categories", $catid);
1992 $newpath .= "/$oldpath->new_id";
1995 $dbrec->path
= $newpath;
1998 $dbrec->fullname
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['FULLNAME']['0']['#']);
1999 $dbrec->aggregation
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGRETGATION']['0']['#']);
2000 $dbrec->keephigh
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['KEEPHIGH']['0']['#']);
2001 $dbrec->droplow
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DROPLOW']['0']['#']);
2003 $dbrec->aggregateonlygraded
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATEONLYGRADED']['0']['#']);
2004 $dbrec->aggregateoutcomes
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATEOUTCOMES']['0']['#']);
2005 $dbrec->aggregatesubcats
= backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGREGATESUBCATS']['0']['#']);
2007 $dbrec->courseid
= $restore->course_id
;
2008 insert_record('grade_categories_history', $dbrec);
2012 //Increment counters
2015 if ($counter %
1 == 0) {
2016 if (!defined('RESTORE_SILENTLY')) {
2018 if ($counter %
20 == 0) {
2029 // process histories
2030 if ($gghcount && $status) {
2031 if (!defined('RESTORE_SILENTLY')) {
2032 echo '<li>'.get_string('gradegradeshistory','grades').'</li>';
2035 while ($counter < $gghcount) {
2036 //Fetch recordset_size records in each iteration
2037 $recs = get_records_select("backup_ids","table_name = 'grade_grades_history' AND backup_code = '$restore->backup_unique_code'",
2043 foreach ($recs as $rec) {
2044 //Get the full record from backup_ids
2045 $data = backup_getid($restore->backup_unique_code
,'grade_grades_history',$rec->old_id
);
2047 //Now get completed xmlized object
2048 $info = $data->info
;
2049 //traverse_xmlize($info); //Debug
2050 //print_object ($GLOBALS['traverse_array']); //Debug
2051 //$GLOBALS['traverse_array']=""; //Debug
2053 $oldobj = backup_getid($restore->backup_unique_code
,"grade_grades", backup_todb($info['GRADE_GRADES_HISTORY']['#']['OLDID']['0']['#']));
2054 if (empty($oldobj->new_id
)) {
2055 // if the old object is not being restored, can't restoring its history
2059 $dbrec->oldid
= $oldobj->new_id
;
2060 $dbrec->action
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['ACTION']['0']['#']);
2061 $dbrec->source
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['SOURCE']['0']['#']);
2062 $dbrec->timemodified
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2063 if ($oldobj = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2064 $dbrec->loggeduser
= $oldobj->new_id
;
2067 $oldobj = backup_getid($restore->backup_unique_code
,"grade_items", backup_todb($info['GRADE_GRADES_HISTORY']['#']['ITEMID']['0']['#']));
2068 $dbrec->itemid
= $oldobj->new_id
;
2069 if (empty($dbrec->itemid
)) {
2071 continue; // grade item not being restored
2073 $oldobj = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERID']['0']['#']));
2074 $dbrec->userid
= $oldobj->new_id
;
2075 $dbrec->rawgrade
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADE']['0']['#']);
2076 $dbrec->rawgrademax
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMAX']['0']['#']);
2077 $dbrec->rawgrademin
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMIN']['0']['#']);
2078 if ($oldobj = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERMODIFIED']['0']['#']))) {
2079 $dbrec->usermodified
= $oldobj->new_id
;
2082 if (backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWSCALEID']['0']['#'])) {
2083 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWSCALEID']['0']['#']));
2084 $dbrec->rawscaleid
= $scale->new_id
;
2087 $dbrec->finalgrade
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['FINALGRADE']['0']['#']);
2088 $dbrec->hidden
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['HIDDEN']['0']['#']);
2089 $dbrec->locked
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKED']['0']['#']);
2090 $dbrec->locktime
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKTIME']['0']['#']);
2091 $dbrec->exported
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXPORTED']['0']['#']);
2092 $dbrec->overridden
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['OVERRIDDEN']['0']['#']);
2093 $dbrec->excluded
= backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXCLUDED']['0']['#']);
2094 $dbrec->feedback
= backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACK']['0']['#']);
2095 $dbrec->feedbackformat
= backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACKFORMAT']['0']['#']);
2096 $dbrec->information
= backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATION']['0']['#']);
2097 $dbrec->informationformat
= backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATIONFORMAT']['0']['#']);
2099 insert_record('grade_grades_history', $dbrec);
2103 //Increment counters
2106 if ($counter %
1 == 0) {
2107 if (!defined('RESTORE_SILENTLY')) {
2109 if ($counter %
20 == 0) {
2120 // process histories
2122 if ($gihcount && $status) {
2123 if (!defined('RESTORE_SILENTLY')) {
2124 echo '<li>'.get_string('gradeitemshistory','grades').'</li>';
2127 while ($counter < $gihcount) {
2128 //Fetch recordset_size records in each iteration
2129 $recs = get_records_select("backup_ids","table_name = 'grade_items_history' AND backup_code = '$restore->backup_unique_code'",
2135 foreach ($recs as $rec) {
2136 //Get the full record from backup_ids
2137 $data = backup_getid($restore->backup_unique_code
,'grade_items_history',$rec->old_id
);
2139 //Now get completed xmlized object
2140 $info = $data->info
;
2141 //traverse_xmlize($info); //Debug
2142 //print_object ($GLOBALS['traverse_array']); //Debug
2143 //$GLOBALS['traverse_array']=""; //Debug
2146 $oldobj = backup_getid($restore->backup_unique_code
,"grade_items", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OLDID']['0']['#']));
2147 if (empty($oldobj->new_id
)) {
2148 // if the old object is not being restored, can't restoring its history
2152 $dbrec->oldid
= $oldobj->new_id
;
2153 $dbrec->action
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ACTION']['0']['#']);
2154 $dbrec->source
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['SOURCE']['0']['#']);
2155 $dbrec->timemodified
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2156 if ($oldobj = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2157 $dbrec->loggeduser
= $oldobj->new_id
;
2159 $dbrec->courseid
= $restore->course_id
;
2160 $oldobj = backup_getid($restore->backup_unique_code
,'grade_categories',backup_todb($info['GRADE_ITEM_HISTORY']['#']['CATEGORYID']['0']['#']));
2161 $oldobj->categoryid
= $category->new_id
;
2162 if (empty($oldobj->categoryid
)) {
2164 continue; // category not restored
2167 $dbrec->itemname
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNAME']['0']['#']);
2168 $dbrec->itemtype
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMTYPE']['0']['#']);
2169 $dbrec->itemmodule
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMMODULE']['0']['#']);
2171 // code from grade_items restore
2172 $iteminstance = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINSTANCE']['0']['#']);
2173 // do not restore if this grade_item is a mod, and
2174 if ($dbrec->itemtype
== 'mod') {
2176 if (!restore_userdata_selected($restore, $dbrec->itemmodule
, $iteminstance)) {
2177 // module instance not selected when restored using granular
2183 // iteminstance should point to new mod
2185 $mod = backup_getid($restore->backup_unique_code
,$dbrec->itemmodule
, $iteminstance);
2186 $dbrec->iteminstance
= $mod->new_id
;
2188 } else if ($dbrec->itemtype
== 'category') {
2189 // the item instance should point to the new grade category
2191 // only proceed if we are restoring all grade items
2193 $category = backup_getid($restore->backup_unique_code
,'grade_categories', $iteminstance);
2194 $dbrec->iteminstance
= $category->new_id
;
2196 // otherwise we can safely ignore this grade item and subsequent
2197 // grade_raws, grade_finals etc
2200 } elseif ($dbrec->itemtype
== 'course') { // We don't restore course type to avoid duplicate course items
2202 // TODO any special code needed here to restore course item without duplicating it?
2203 // find the course category with depth 1, and course id = current course id
2204 // this would have been already restored
2206 $cat = get_record('grade_categories', 'depth', 1, 'courseid', $restore->course_id
);
2207 $dbrec->iteminstance
= $cat->id
;
2215 $dbrec->itemnumber
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNUMBER']['0']['#']);
2216 $dbrec->iteminfo
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINFO']['0']['#']);
2217 $dbrec->idnumber
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['IDNUMBER']['0']['#']);
2218 $dbrec->calculation
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['CALCULATION']['0']['#']);
2219 $dbrec->gradetype
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADETYPE']['0']['#']);
2220 $dbrec->grademax
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMAX']['0']['#']);
2221 $dbrec->grademin
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMIN']['0']['#']);
2222 if ($oldobj = backup_getid($restore->backup_unique_code
,"scale", backup_todb($info['GRADE_ITEM_HISTORY']['#']['SCALEID']['0']['#']))) {
2223 // scaleid is optional
2224 $dbrec->scaleid
= $oldobj->new_id
;
2226 if ($oldobj = backup_getid($restore->backup_unique_code
,"grade_outcomes", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OUTCOMEID']['0']['#']))) {
2227 // outcome is optional
2228 $dbrec->outcomeid
= $oldobj->new_id
;
2230 $dbrec->gradepass
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEPASS']['0']['#']);
2231 $dbrec->multfactor
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['MULTFACTOR']['0']['#']);
2232 $dbrec->plusfactor
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['PLUSFACTOR']['0']['#']);
2233 $dbrec->aggregationcoef
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['AGGREGATIONCOEF']['0']['#']);
2234 $dbrec->sortorder
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['SORTORDER']['0']['#']);
2235 $dbrec->display
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['DISPLAY']['0']['#']);
2236 $dbrec->decimals
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['DECIMALS']['0']['#']);
2237 $dbrec->hidden
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['HIDDEN']['0']['#']);
2238 $dbrec->locked
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKED']['0']['#']);
2239 $dbrec->locktime
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKTIME']['0']['#']);
2240 $dbrec->needsupdate
= backup_todb($info['GRADE_ITEM_HISTORY']['#']['NEEDSUPDATE']['0']['#']);
2242 insert_record('grade_items_history', $dbrec);
2246 //Increment counters
2249 if ($counter %
1 == 0) {
2250 if (!defined('RESTORE_SILENTLY')) {
2252 if ($counter %
20 == 0) {
2263 // process histories
2264 if ($gohcount && $status) {
2265 if (!defined('RESTORE_SILENTLY')) {
2266 echo '<li>'.get_string('gradeoutcomeshistory','grades').'</li>';
2269 while ($counter < $gohcount) {
2270 //Fetch recordset_size records in each iteration
2271 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes_history' AND backup_code = '$restore->backup_unique_code'",
2277 foreach ($recs as $rec) {
2278 //Get the full record from backup_ids
2279 $data = backup_getid($restore->backup_unique_code
,'grade_outcomes_history',$rec->old_id
);
2281 //Now get completed xmlized object
2282 $info = $data->info
;
2283 //traverse_xmlize($info); //Debug
2284 //print_object ($GLOBALS['traverse_array']); //Debug
2285 //$GLOBALS['traverse_array']=""; //Debug
2287 $oldobj = backup_getid($restore->backup_unique_code
,"grade_outcomes", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['OLDID']['0']['#']));
2288 if (empty($oldobj->new_id
)) {
2289 // if the old object is not being restored, can't restoring its history
2293 $dbrec->oldid
= $oldobj->new_id
;
2294 $dbrec->action
= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['ACTION']['0']['#']);
2295 $dbrec->source
= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SOURCE']['0']['#']);
2296 $dbrec->timemodified
= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2297 if ($oldobj = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2298 $dbrec->loggeduser
= $oldobj->new_id
;
2300 $dbrec->courseid
= $restore->course_id
;
2301 $dbrec->shortname
= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SHORTNAME']['0']['#']);
2302 $dbrec->fullname
= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['FULLNAME']['0']['#']);
2303 $oldobj = backup_getid($restore->backup_unique_code
,"scale", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SCALEID']['0']['#']));
2304 $dbrec->scaleid
= $oldobj->new_id
;
2305 $dbrec->description
= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['DESCRIPTION']['0']['#']);
2307 insert_record('grade_outcomes_history', $dbrec);
2311 //Increment counters
2314 if ($counter %
1 == 0) {
2315 if (!defined('RESTORE_SILENTLY')) {
2317 if ($counter %
20 == 0) {
2329 if (!defined('RESTORE_SILENTLY')) {
2336 //This function creates all the user, user_students, user_teachers
2337 //user_course_creators and user_admins from xml
2338 function restore_create_users($restore,$xml_file) {
2341 require_once ($CFG->dirroot
.'/tag/lib.php');
2345 if (!file_exists($xml_file)) {
2350 //info will contain the old_id of every user
2351 //in backup_ids->info will be the real info (serialized)
2352 $info = restore_read_xml_users($restore,$xml_file);
2355 //Now, get evey user_id from $info and user data from $backup_ids
2356 //and create the necessary db structures
2358 if (!empty($info->users
)) {
2360 /// Grab mnethosts keyed by wwwroot, to map to id
2361 $mnethosts = get_records('mnet_host', '', '',
2362 'wwwroot', 'wwwroot, id');
2364 /// Get languages for quick search later
2365 $languages = get_list_of_languages();
2367 /// Iterate over all users loaded from xml
2369 foreach ($info->users
as $userid) {
2370 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
2372 foreach (array_keys(get_object_vars($user)) as $field) {
2373 if (!is_array($user->$field)) {
2374 $user->$field = backup_todb($user->$field);
2375 if (is_null($user->$field)) {
2381 //Now, recode some languages (Moodle 1.5)
2382 if ($user->lang
== 'ma_nt') {
2383 $user->lang
= 'mi_nt';
2386 //Country list updates - MDL-13060
2387 //Any user whose country code has been deleted or modified needs to be assigned a valid one.
2388 $country_update_map = array(
2395 if (array_key_exists($user->country
, $country_update_map)) {
2396 $user->country
= $country_update_map[$user->country
];
2399 //If language does not exist here - use site default
2400 if (!array_key_exists($user->lang
, $languages)) {
2401 $user->lang
= $CFG->lang
;
2404 //Check if it's admin and coursecreator
2405 $is_admin = !empty($user->roles
['admin']);
2406 $is_coursecreator = !empty($user->roles
['coursecreator']);
2408 //Check if it's teacher and student
2409 $is_teacher = !empty($user->roles
['teacher']);
2410 $is_student = !empty($user->roles
['student']);
2412 //Check if it's needed
2413 $is_needed = !empty($user->roles
['needed']);
2415 //Calculate if it is a course user
2416 //Has role teacher or student or needed
2417 $is_course_user = ($is_teacher or $is_student or $is_needed);
2419 //Calculate mnethostid
2420 if (empty($user->mnethosturl
) ||
$user->mnethosturl
===$CFG->wwwroot
) {
2421 $user->mnethostid
= $CFG->mnet_localhost_id
;
2423 // fast url-to-id lookups
2424 if (isset($mnethosts[$user->mnethosturl
])) {
2425 $user->mnethostid
= $mnethosts[$user->mnethosturl
]->id
;
2427 // should not happen, as we check in restore_chech.php
2428 // but handle the error if it does
2429 error("This backup file contains external Moodle Network Hosts that are not configured locally.");
2432 unset($user->mnethosturl
);
2434 //To store user->id along all the iteration
2436 //check if it exists (by username) and get its id
2437 $user_exists = true;
2438 $user_data = get_record("user","username",addslashes($user->username
),
2439 'mnethostid', $user->mnethostid
);
2441 $user_exists = false;
2443 $newid = $user_data->id
;
2446 //Flags to see what parts are we going to restore
2447 $create_user = true;
2448 $create_roles = true;
2449 $create_custom_profile_fields = true;
2450 $create_tags = true;
2451 $create_preferences = true;
2453 //If we are restoring course users and it isn't a course user
2454 if ($restore->users
== 1 and !$is_course_user) {
2455 //If only restoring course_users and user isn't a course_user, inform to $backup_ids
2456 $status = backup_putid($restore->backup_unique_code
,"user",$userid,null,'notincourse');
2457 $create_user = false;
2458 $create_roles = false;
2459 $create_custom_profile_fields = false;
2460 $create_tags = false;
2461 $create_preferences = false;
2464 if ($user_exists and $create_user) {
2465 //If user exists mark its newid in backup_ids (the same than old)
2466 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,'exists');
2467 $create_user = false;
2468 $create_custom_profile_fields = false;
2469 $create_tags = false;
2472 //Here, if create_user, do it
2474 //Unset the id because it's going to be inserted with a new one
2476 // relink the descriptions
2477 $user->description
= stripslashes($user->description
);
2479 /// Disable pictures based on global setting or existing empty value (old backups can contain wrong empties)
2480 if (!empty($CFG->disableuserimages
) ||
empty($user->picture
)) {
2484 //We need to analyse the AUTH field to recode it:
2485 // - if the field isn't set, we are in a pre 1.4 backup and we'll
2488 if (empty($user->auth
)) {
2489 if ($CFG->registerauth
== 'email') {
2490 $user->auth
= 'email';
2492 $user->auth
= 'manual';
2496 //We need to process the POLICYAGREED field to recalculate it:
2497 // - if the destination site is different (by wwwroot) reset it.
2498 // - if the destination site is the same (by wwwroot), leave it unmodified
2500 if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
2501 $user->policyagreed
= 0;
2503 //Nothing to do, we are in the same server
2506 //Check if the theme exists in destination server
2507 $themes = get_list_of_themes();
2508 if (!in_array($user->theme
, $themes)) {
2512 //We are going to create the user
2513 //The structure is exactly as we need
2515 $newid = insert_record ("user", addslashes_recursive($user));
2517 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,"new");
2520 ///TODO: This seccion is to support pre 1.7 course backups, using old roles
2521 /// teacher, coursecreator, student.... providing a basic mapping to new ones.
2522 /// Someday we'll drop support for them and this section will be safely deleted (2.0?)
2523 //Here, if create_roles, do it as necessary
2524 if ($create_roles) {
2525 //Get the newid and current info from backup_ids
2526 $data = backup_getid($restore->backup_unique_code
,"user",$userid);
2527 $newid = $data->new_id
;
2528 $currinfo = $data->info
.",";
2530 //Now, depending of the role, create records in user_studentes and user_teacher
2531 //and/or mark it in backup_ids
2534 //If the record (user_admins) doesn't exists
2535 //Only put status in backup_ids
2536 $currinfo = $currinfo."admin,";
2537 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
2539 if ($is_coursecreator) {
2540 //If the record (user_coursecreators) doesn't exists
2541 //Only put status in backup_ids
2542 $currinfo = $currinfo."coursecreator,";
2543 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
2546 //Only put status in backup_ids
2547 $currinfo = $currinfo."needed,";
2548 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
2551 //If the record (teacher) doesn't exists
2552 //Put status in backup_ids
2553 $currinfo = $currinfo."teacher,";
2554 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
2555 //Set course and user
2556 $user->roles
['teacher']->course
= $restore->course_id
;
2557 $user->roles
['teacher']->userid
= $newid;
2559 //Need to analyse the enrol field
2560 // - if it isn't set, set it to $CFG->enrol
2561 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2562 // - if we are in the same server (by wwwroot), maintain it unmodified.
2563 if (empty($user->roles
['teacher']->enrol
)) {
2564 $user->roles
['teacher']->enrol
= $CFG->enrol
;
2565 } else if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
2566 $user->roles
['teacher']->enrol
= $CFG->enrol
;
2568 //Nothing to do. Leave it unmodified
2571 $rolesmapping = $restore->rolesmapping
;
2572 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
2573 if ($user->roles
['teacher']->editall
) {
2574 role_assign($rolesmapping['defaultteacheredit'],
2578 $user->roles
['teacher']->timestart
,
2579 $user->roles
['teacher']->timeend
,
2581 $user->roles
['teacher']->enrol
);
2585 // non editting teacher
2586 role_assign($rolesmapping['defaultteacher'],
2590 $user->roles
['teacher']->timestart
,
2591 $user->roles
['teacher']->timeend
,
2593 $user->roles
['teacher']->enrol
);
2598 //Put status in backup_ids
2599 $currinfo = $currinfo."student,";
2600 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
2601 //Set course and user
2602 $user->roles
['student']->course
= $restore->course_id
;
2603 $user->roles
['student']->userid
= $newid;
2605 //Need to analyse the enrol field
2606 // - if it isn't set, set it to $CFG->enrol
2607 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2608 // - if we are in the same server (by wwwroot), maintain it unmodified.
2609 if (empty($user->roles
['student']->enrol
)) {
2610 $user->roles
['student']->enrol
= $CFG->enrol
;
2611 } else if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
2612 $user->roles
['student']->enrol
= $CFG->enrol
;
2614 //Nothing to do. Leave it unmodified
2616 $rolesmapping = $restore->rolesmapping
;
2617 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
2619 role_assign($rolesmapping['defaultstudent'],
2623 $user->roles
['student']->timestart
,
2624 $user->roles
['student']->timeend
,
2626 $user->roles
['student']->enrol
);
2629 if (!$is_course_user) {
2630 //If the record (user) doesn't exists
2631 if (!record_exists("user","id",$newid)) {
2632 //Put status in backup_ids
2633 $currinfo = $currinfo."user,";
2634 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
2639 /// Here, if create_custom_profile_fields, do it as necessary
2640 if ($create_custom_profile_fields) {
2641 if (isset($user->user_custom_profile_fields
)) {
2642 foreach($user->user_custom_profile_fields
as $udata) {
2643 /// If the profile field has data and the profile shortname-datatype is defined in server
2644 if ($udata->field_data
) {
2645 if ($field = get_record('user_info_field', 'shortname', $udata->field_name
, 'datatype', $udata->field_type
)) {
2646 /// Insert the user_custom_profile_field
2647 $rec = new object();
2648 $rec->userid
= $newid;
2649 $rec->fieldid
= $field->id
;
2650 $rec->data
= $udata->field_data
;
2651 insert_record('user_info_data', $rec);
2658 /// Here, if create_tags, do it as necessary
2660 /// if tags are enabled and there are user tags
2661 if (!empty($CFG->usetags
) && isset($user->user_tags
)) {
2663 foreach($user->user_tags
as $user_tag) {
2664 $tags[] = $user_tag->rawname
;
2666 tag_set('user', $newid, $tags);
2670 //Here, if create_preferences, do it as necessary
2671 if ($create_preferences) {
2672 if (isset($user->user_preferences
)) {
2673 foreach($user->user_preferences
as $user_preference) {
2674 //We check if that user_preference exists in DB
2675 if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name
)) {
2676 //Prepare the record and insert it
2677 $user_preference->userid
= $newid;
2678 $status = insert_record("user_preferences",$user_preference);
2686 if ($counter %
10 == 0) {
2687 if (!defined('RESTORE_SILENTLY')) {
2689 if ($counter %
200 == 0) {
2695 } /// End of loop over all the users loaded from xml
2701 //This function creates all the structures messages and contacts
2702 function restore_create_messages($restore,$xml_file) {
2708 if (!file_exists($xml_file)) {
2713 //info will contain the id and name of every table
2714 //(message, message_read and message_contacts)
2715 //in backup_ids->info will be the real info (serialized)
2716 $info = restore_read_xml_messages($restore,$xml_file);
2718 //If we have info, then process messages & contacts
2720 //Count how many we have
2721 $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message');
2722 $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message_read');
2723 $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message_contacts');
2724 if ($unreadcount ||
$readcount ||
$contactcount) {
2726 if (!defined('RESTORE_SILENTLY')) {
2729 //Number of records to get in every chunk
2730 $recordset_size = 4;
2734 if (!defined('RESTORE_SILENTLY')) {
2735 echo '<li>'.get_string('unreadmessages','message').'</li>';
2738 while ($counter < $unreadcount) {
2739 //Fetch recordset_size records in each iteration
2740 $recs = get_records_select("backup_ids","table_name = 'message' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2742 foreach ($recs as $rec) {
2743 //Get the full record from backup_ids
2744 $data = backup_getid($restore->backup_unique_code
,"message",$rec->old_id
);
2746 //Now get completed xmlized object
2747 $info = $data->info
;
2748 //traverse_xmlize($info); //Debug
2749 //print_object ($GLOBALS['traverse_array']); //Debug
2750 //$GLOBALS['traverse_array']=""; //Debug
2751 //Now build the MESSAGE record structure
2752 $dbrec = new object();
2753 $dbrec->useridfrom
= backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2754 $dbrec->useridto
= backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2755 $dbrec->message
= backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2756 $dbrec->format
= backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2757 $dbrec->timecreated
= backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2758 $dbrec->messagetype
= backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2759 //We have to recode the useridfrom field
2760 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridfrom
);
2762 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2763 $dbrec->useridfrom
= $user->new_id
;
2765 //We have to recode the useridto field
2766 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridto
);
2768 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2769 $dbrec->useridto
= $user->new_id
;
2771 //Check if the record doesn't exist in DB!
2772 $exist = get_record('message','useridfrom',$dbrec->useridfrom
,
2773 'useridto', $dbrec->useridto
,
2774 'timecreated',$dbrec->timecreated
);
2777 $status = insert_record('message',$dbrec);
2779 //Duplicate. Do nothing
2784 if ($counter %
10 == 0) {
2785 if (!defined('RESTORE_SILENTLY')) {
2787 if ($counter %
200 == 0) {
2800 if (!defined('RESTORE_SILENTLY')) {
2801 echo '<li>'.get_string('readmessages','message').'</li>';
2804 while ($counter < $readcount) {
2805 //Fetch recordset_size records in each iteration
2806 $recs = get_records_select("backup_ids","table_name = 'message_read' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2808 foreach ($recs as $rec) {
2809 //Get the full record from backup_ids
2810 $data = backup_getid($restore->backup_unique_code
,"message_read",$rec->old_id
);
2812 //Now get completed xmlized object
2813 $info = $data->info
;
2814 //traverse_xmlize($info); //Debug
2815 //print_object ($GLOBALS['traverse_array']); //Debug
2816 //$GLOBALS['traverse_array']=""; //Debug
2817 //Now build the MESSAGE_READ record structure
2818 $dbrec->useridfrom
= backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2819 $dbrec->useridto
= backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2820 $dbrec->message
= backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2821 $dbrec->format
= backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2822 $dbrec->timecreated
= backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2823 $dbrec->messagetype
= backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2824 $dbrec->timeread
= backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
2825 $dbrec->mailed
= backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
2826 //We have to recode the useridfrom field
2827 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridfrom
);
2829 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2830 $dbrec->useridfrom
= $user->new_id
;
2832 //We have to recode the useridto field
2833 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridto
);
2835 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2836 $dbrec->useridto
= $user->new_id
;
2838 //Check if the record doesn't exist in DB!
2839 $exist = get_record('message_read','useridfrom',$dbrec->useridfrom
,
2840 'useridto', $dbrec->useridto
,
2841 'timecreated',$dbrec->timecreated
);
2844 $status = insert_record('message_read',$dbrec);
2846 //Duplicate. Do nothing
2851 if ($counter %
10 == 0) {
2852 if (!defined('RESTORE_SILENTLY')) {
2854 if ($counter %
200 == 0) {
2866 if ($contactcount) {
2867 if (!defined('RESTORE_SILENTLY')) {
2868 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
2871 while ($counter < $contactcount) {
2872 //Fetch recordset_size records in each iteration
2873 $recs = get_records_select("backup_ids","table_name = 'message_contacts' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2875 foreach ($recs as $rec) {
2876 //Get the full record from backup_ids
2877 $data = backup_getid($restore->backup_unique_code
,"message_contacts",$rec->old_id
);
2879 //Now get completed xmlized object
2880 $info = $data->info
;
2881 //traverse_xmlize($info); //Debug
2882 //print_object ($GLOBALS['traverse_array']); //Debug
2883 //$GLOBALS['traverse_array']=""; //Debug
2884 //Now build the MESSAGE_CONTACTS record structure
2885 $dbrec->userid
= backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
2886 $dbrec->contactid
= backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
2887 $dbrec->blocked
= backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
2888 //We have to recode the userid field
2889 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->userid
);
2891 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
2892 $dbrec->userid
= $user->new_id
;
2894 //We have to recode the contactid field
2895 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->contactid
);
2897 //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />"; //Debug
2898 $dbrec->contactid
= $user->new_id
;
2900 //Check if the record doesn't exist in DB!
2901 $exist = get_record('message_contacts','userid',$dbrec->userid
,
2902 'contactid', $dbrec->contactid
);
2905 $status = insert_record('message_contacts',$dbrec);
2907 //Duplicate. Do nothing
2912 if ($counter %
10 == 0) {
2913 if (!defined('RESTORE_SILENTLY')) {
2915 if ($counter %
200 == 0) {
2925 if (!defined('RESTORE_SILENTLY')) {
2936 //This function creates all the categories and questions
2938 function restore_create_questions($restore,$xml_file) {
2944 if (!file_exists($xml_file)) {
2949 //info will contain the old_id of every category
2950 //in backup_ids->info will be the real info (serialized)
2951 $info = restore_read_xml_questions($restore,$xml_file);
2953 //Now, if we have anything in info, we have to restore that
2954 //categories/questions
2956 if ($info !== true) {
2957 $status = $status && restore_question_categories($info, $restore);
2965 //This function creates all the scales
2966 function restore_create_scales($restore,$xml_file) {
2972 if (!file_exists($xml_file)) {
2977 //scales will contain the old_id of every scale
2978 //in backup_ids->info will be the real info (serialized)
2979 $scales = restore_read_xml_scales($restore,$xml_file);
2981 //Now, if we have anything in scales, we have to restore that
2984 //Get admin->id for later use
2985 $admin = get_admin();
2986 $adminid = $admin->id
;
2987 if ($scales !== true) {
2988 //Iterate over each scale
2989 foreach ($scales as $scale) {
2990 //Get record from backup_ids
2991 $data = backup_getid($restore->backup_unique_code
,"scale",$scale->id
);
2993 $create_scale = false;
2996 //Now get completed xmlized object
2997 $info = $data->info
;
2998 //traverse_xmlize($info); //Debug
2999 //print_object ($GLOBALS['traverse_array']); //Debug
3000 //$GLOBALS['traverse_array']=""; //Debug
3002 //Now build the SCALE record structure
3003 $sca = new object();
3004 $sca->courseid
= backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
3005 $sca->userid
= backup_todb($info['SCALE']['#']['USERID']['0']['#']);
3006 $sca->name
= backup_todb($info['SCALE']['#']['NAME']['0']['#']);
3007 $sca->scale
= backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
3008 $sca->description
= backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
3009 $sca->timemodified
= backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);
3011 //Now search if that scale exists (by scale field) in course 0 (Standar scale)
3012 //or in restore->course_id course (Personal scale)
3013 if ($sca->courseid
== 0) {
3014 $course_to_search = 0;
3016 $course_to_search = $restore->course_id
;
3019 // scale is not course unique, use get_record_sql to suppress warning
3021 $sca_db = get_record_sql("SELECT * FROM {$CFG->prefix}scale
3022 WHERE scale = '$sca->scale'
3023 AND courseid = $course_to_search", true);
3025 //If it doesn't exist, create
3027 $create_scale = true;
3029 //If we must create the scale
3030 if ($create_scale) {
3031 //Me must recode the courseid if it's <> 0 (common scale)
3032 if ($sca->courseid
!= 0) {
3033 $sca->courseid
= $restore->course_id
;
3035 //We must recode the userid
3036 $user = backup_getid($restore->backup_unique_code
,"user",$sca->userid
);
3038 $sca->userid
= $user->new_id
;
3040 //Assign it to admin
3041 $sca->userid
= $adminid;
3043 //The structure is equal to the db, so insert the scale
3044 $newid = insert_record ("scale",$sca);
3046 //get current scale id
3047 $newid = $sca_db->id
;
3050 //We have the newid, update backup_ids
3051 backup_putid($restore->backup_unique_code
,"scale",
3052 $scale->id
, $newid);
3064 * Recode group ID field, and set group ID based on restore options.
3065 * @return object Group object with new_id field.
3067 function restore_group_getid($restore, $groupid) {
3068 //We have to recode the groupid field
3069 $group = backup_getid($restore->backup_unique_code
, 'groups', $groupid);
3071 if ($restore->groups
== RESTORE_GROUPS_NONE
or $restore->groups
== RESTORE_GROUPINGS_ONLY
) {
3078 * Recode grouping ID field, and set grouping ID based on restore options.
3079 * @return object Group object with new_id field.
3081 function restore_grouping_getid($restore, $groupingid) {
3082 //We have to recode the groupid field
3083 $grouping = backup_getid($restore->backup_unique_code
, 'groupings', $groupingid);
3085 if ($restore->groups
== RESTORE_GROUPS_GROUPINGS
or $restore->groups
== RESTORE_GROUPINGS_ONLY
) {
3086 $grouping->new_id
= 0;
3091 //This function creates all the groups
3092 function restore_create_groups($restore,$xml_file) {
3097 if (!file_exists($xml_file)) {
3101 if (!$groups = restore_read_xml_groups($restore,$xml_file)) {
3102 //groups will contain the old_id of every group
3103 //in backup_ids->info will be the real info (serialized)
3106 } else if ($groups === true) {
3112 //Iterate over each group
3113 foreach ($groups as $group) {
3114 //Get record from backup_ids
3115 $data = backup_getid($restore->backup_unique_code
,"groups",$group->id
);
3118 //Now get completed xmlized object
3119 $info = $data->info
;
3120 //traverse_xmlize($info); //Debug
3121 //print_object ($GLOBALS['traverse_array']); //Debug
3122 //$GLOBALS['traverse_array']=""; //Debug
3123 //Now build the GROUP record structure
3124 $gro = new Object();
3125 $gro->courseid
= $restore->course_id
;
3126 $gro->name
= backup_todb($info['GROUP']['#']['NAME']['0']['#']);
3127 $gro->description
= backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
3128 if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) {
3129 $gro->enrolmentkey
= backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']);
3131 $gro->enrolmentkey
= backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
3133 $gro->picture
= backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
3134 $gro->hidepicture
= backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
3135 $gro->timecreated
= backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
3136 $gro->timemodified
= backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
3138 //Now search if that group exists (by name and description field) in
3139 //restore->course_id course
3140 //Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides.
3141 $description_clause = '';
3142 if (!empty($gro->description
)) { /// Only for groups having a description
3143 $literal_description = "'" . $gro->description
. "'";
3144 $description_clause = " AND " .
3145 sql_compare_text('description') . " = " .
3146 sql_compare_text($literal_description);
3148 if (!$gro_db = get_record_sql("SELECT *
3149 FROM {$CFG->prefix}groups
3150 WHERE courseid = $restore->course_id AND
3151 name = '{$gro->name}'" . $description_clause, true)) {
3152 //If it doesn't exist, create
3153 $newid = insert_record('groups', $gro);
3156 //get current group id
3157 $newid = $gro_db->id
;
3161 //We have the newid, update backup_ids
3162 backup_putid($restore->backup_unique_code
,"groups", $group->id
, $newid);
3169 //Now restore members in the groups_members, only if
3170 //users are included
3171 if ($restore->users
!= 2) {
3172 if (!restore_create_groups_members($newid,$info,$restore)) {
3179 //Now, restore group_files
3181 $status = restore_group_files($restore);
3187 //This function restores the groups_members
3188 function restore_create_groups_members($group_id,$info,$restore) {
3190 if (! isset($info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'])) {
3191 //OK, some groups have no members.
3194 //Get the members array
3195 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
3199 //Iterate over members
3200 for($i = 0; $i < sizeof($members); $i++
) {
3201 $mem_info = $members[$i];
3202 //traverse_xmlize($mem_info); //Debug
3203 //print_object ($GLOBALS['traverse_array']); //Debug
3204 //$GLOBALS['traverse_array']=""; //Debug
3206 //Now, build the GROUPS_MEMBERS record structure
3207 $group_member = new Object();
3208 $group_member->groupid
= $group_id;
3209 $group_member->userid
= backup_todb($mem_info['#']['USERID']['0']['#']);
3210 $group_member->timeadded
= backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
3214 //We have to recode the userid field
3215 if (!$user = backup_getid($restore->backup_unique_code
,"user",$group_member->userid
)) {
3220 $group_member->userid
= $user->new_id
;
3222 //The structure is equal to the db, so insert the groups_members
3223 if (!insert_record ("groups_members", $group_member)) {
3229 if (($i+
1) %
50 == 0) {
3230 if (!defined('RESTORE_SILENTLY')) {
3232 if (($i+
1) %
1000 == 0) {
3243 //This function creates all the groupings
3244 function restore_create_groupings($restore,$xml_file) {
3247 if (!file_exists($xml_file)) {
3251 if (!$groupings = restore_read_xml_groupings($restore,$xml_file)) {
3254 } else if ($groupings === true) {
3260 //Iterate over each group
3261 foreach ($groupings as $grouping) {
3262 if ($data = backup_getid($restore->backup_unique_code
,"groupings",$grouping->id
)) {
3263 //Now get completed xmlized object
3264 $info = $data->info
;
3265 //Now build the GROUPING record structure
3266 $gro = new Object();
3267 ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']);
3268 $gro->courseid
= $restore->course_id
;
3269 $gro->name
= backup_todb($info['GROUPING']['#']['NAME']['0']['#']);
3270 $gro->description
= backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']);
3271 $gro->configdata
= backup_todb($info['GROUPING']['#']['CONFIGDATA']['0']['#']);
3272 $gro->timecreated
= backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']);
3274 //Now search if that group exists (by name and description field) in
3275 if ($gro_db = get_record('groupings', 'courseid', $restore->course_id
, 'name', $gro->name
, 'description', $gro->description
)) {
3276 //get current group id
3277 $newid = $gro_db->id
;
3280 //The structure is equal to the db, so insert the grouping
3281 if (!$newid = insert_record('groupings', $gro)) {
3287 //We have the newid, update backup_ids
3288 backup_putid($restore->backup_unique_code
,"groupings",
3289 $grouping->id
, $newid);
3294 // now fix the defaultgroupingid in course
3295 $course = get_record('course', 'id', $restore->course_id
);
3296 if ($course->defaultgroupingid
) {
3297 if ($grouping = restore_grouping_getid($restore, $course->defaultgroupingid
)) {
3298 set_field('course', 'defaultgroupingid', $grouping->new_id
, 'id', $course->id
);
3300 set_field('course', 'defaultgroupingid', 0, 'id', $course->id
);
3307 //This function creates all the groupingsgroups
3308 function restore_create_groupings_groups($restore,$xml_file) {
3311 if (!file_exists($xml_file)) {
3315 if (!$groupingsgroups = restore_read_xml_groupings_groups($restore,$xml_file)) {
3318 } else if ($groupingsgroups === true) {
3324 //Iterate over each group
3325 foreach ($groupingsgroups as $groupinggroup) {
3326 if ($data = backup_getid($restore->backup_unique_code
,"groupingsgroups",$groupinggroup->id
)) {
3327 //Now get completed xmlized object
3328 $info = $data->info
;
3329 //Now build the GROUPING record structure
3330 $gro_member = new Object();
3331 $gro_member->groupingid
= backup_todb($info['GROUPINGGROUP']['#']['GROUPINGID']['0']['#']);
3332 $gro_member->groupid
= backup_todb($info['GROUPINGGROUP']['#']['GROUPID']['0']['#']);
3333 $gro_member->timeadded
= backup_todb($info['GROUPINGGROUP']['#']['TIMEADDED']['0']['#']);
3335 if (!$grouping = backup_getid($restore->backup_unique_code
,"groupings",$gro_member->groupingid
)) {
3340 if (!$group = backup_getid($restore->backup_unique_code
,"groups",$gro_member->groupid
)) {
3345 $gro_member->groupid
= $group->new_id
;
3346 $gro_member->groupingid
= $grouping->new_id
;
3347 if (!get_record('groupings_groups', 'groupid', $gro_member->groupid
, 'groupingid', $gro_member->groupingid
)) {
3348 if (!insert_record('groupings_groups', $gro_member)) {
3358 //This function creates all the course events
3359 function restore_create_events($restore,$xml_file) {
3365 if (!file_exists($xml_file)) {
3370 //events will contain the old_id of every event
3371 //in backup_ids->info will be the real info (serialized)
3372 $events = restore_read_xml_events($restore,$xml_file);
3375 //Get admin->id for later use
3376 $admin = get_admin();
3377 $adminid = $admin->id
;
3379 //Now, if we have anything in events, we have to restore that
3382 if ($events !== true) {
3383 //Iterate over each event
3384 foreach ($events as $event) {
3385 //Get record from backup_ids
3386 $data = backup_getid($restore->backup_unique_code
,"event",$event->id
);
3388 $create_event = false;
3391 //Now get completed xmlized object
3392 $info = $data->info
;
3393 //traverse_xmlize($info); //Debug
3394 //print_object ($GLOBALS['traverse_array']); //Debug
3395 //$GLOBALS['traverse_array']=""; //Debug
3397 //if necessary, write to restorelog and adjust date/time fields
3398 if ($restore->course_startdateoffset
) {
3399 restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
3402 //Now build the EVENT record structure
3403 $eve->name
= backup_todb($info['EVENT']['#']['NAME']['0']['#']);
3404 $eve->description
= backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
3405 $eve->format
= backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
3406 $eve->courseid
= $restore->course_id
;
3407 $eve->groupid
= backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
3408 $eve->userid
= backup_todb($info['EVENT']['#']['USERID']['0']['#']);
3409 $eve->repeatid
= backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
3410 $eve->modulename
= "";
3411 if (!empty($info['EVENT']['#']['MODULENAME'])) {
3412 $eve->modulename
= backup_todb($info['EVENT']['#']['MODULENAME']['0']['#']);
3415 $eve->eventtype
= backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
3416 $eve->timestart
= backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
3417 $eve->timeduration
= backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
3418 $eve->visible
= backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
3419 $eve->timemodified
= backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
3421 //Now search if that event exists (by name, description, timestart fields) in
3422 //restore->course_id course
3423 $eve_db = get_record_select("event",
3424 "courseid={$eve->courseid} AND name='{$eve->name}' AND description='{$eve->description}' AND timestart=$eve->timestart");
3425 //If it doesn't exist, create
3427 $create_event = true;
3429 //If we must create the event
3430 if ($create_event) {
3432 //We must recode the userid
3433 $user = backup_getid($restore->backup_unique_code
,"user",$eve->userid
);
3435 $eve->userid
= $user->new_id
;
3437 //Assign it to admin
3438 $eve->userid
= $adminid;
3441 //We have to recode the groupid field
3442 $group = backup_getid($restore->backup_unique_code
,"groups",$eve->groupid
);
3444 $eve->groupid
= $group->new_id
;
3446 //Assign it to group 0
3450 //The structure is equal to the db, so insert the event
3451 $newid = insert_record ("event",$eve);
3453 //We must recode the repeatid if the event has it
3454 //The repeatid now refers to the id of the original event. (see Bug#5956)
3455 if ($newid && !empty($eve->repeatid
)) {
3456 $repeat_rec = backup_getid($restore->backup_unique_code
,"event_repeatid",$eve->repeatid
);
3457 if ($repeat_rec) { //Exists, so use it...
3458 $eve->repeatid
= $repeat_rec->new_id
;
3459 } else { //Doesn't exists, calculate the next and save it
3460 $oldrepeatid = $eve->repeatid
;
3461 $eve->repeatid
= $newid;
3462 backup_putid($restore->backup_unique_code
,"event_repeatid", $oldrepeatid, $eve->repeatid
);
3465 // update the record to contain the correct repeatid
3466 update_record('event',$eve);
3469 //get current event id
3470 $newid = $eve_db->id
;
3473 //We have the newid, update backup_ids
3474 backup_putid($restore->backup_unique_code
,"event",
3475 $event->id
, $newid);
3486 //This function decode things to make restore multi-site fully functional
3487 //It does this conversions:
3488 // - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
3489 // |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
3491 //Note: Inter-activities linking is being implemented as a final
3492 //step in the restore execution, because we need to have it
3493 //finished to know all the oldid, newid equivaleces
3494 function restore_decode_absolute_links($content) {
3496 global $CFG,$restore;
3499 // This function was replacing null with empty string
3500 // Nullity check is added in backup_todb(), this function will no longer not be called from backup_todb() if content is null
3501 // I noticed some parts of the restore code is calling this directly instead of calling backup_todb(), so just in case
3502 // 3rd party mod etc are doing the same
3503 if ($content === NULL) {
3507 //Now decode wwwroot and file.php calls
3508 $search = array ("$@FILEPHP@$");
3510 //Check for the status of the slasharguments config variable
3511 $slash = $CFG->slasharguments
;
3513 //Build the replace string as needed
3515 $replace = array ($CFG->wwwroot
."/file.php/".$restore->course_id
);
3517 $replace = array ($CFG->wwwroot
."/file.php?file=/".$restore->course_id
);
3520 $result = str_replace($search,$replace,$content);
3522 if ($result != $content && debugging()) { //Debug
3523 if (!defined('RESTORE_SILENTLY')) {
3524 echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />'; //Debug
3531 //This function restores the userfiles from the temp (user_files) directory to the
3532 //dataroot/users directory
3533 function restore_user_files($restore) {
3541 // 'users' is the old users folder, 'user' is the new one, with a new hierarchy. Detect which one is here and treat accordingly
3543 $dest_dir = $CFG->dataroot
."/user";
3544 $status = check_dir_exists($dest_dir,true);
3546 //Now, we iterate over "user_files" records to check if that user dir must be
3547 //copied (and renamed) to the "users" dir.
3548 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/user_files";
3550 //Check if directory exists
3551 $userlist = array();
3553 if (is_dir($rootdir) && ($list = list_directories ($rootdir))) {
3555 foreach ($list as $dir) {
3556 // If there are directories in this folder, we are in the new user hierarchy
3557 if ($newlist = list_directories("$rootdir/$dir")) {
3558 foreach ($newlist as $olduserid) {
3559 $userlist[$olduserid] = "$rootdir/$dir/$olduserid";
3562 $userlist[$dir] = "$rootdir/$dir";
3566 foreach ($userlist as $olduserid => $backup_location) {
3567 //Look for dir like username in backup_ids
3568 //If that user exists in backup_ids
3569 if ($user = backup_getid($restore->backup_unique_code
,"user",$olduserid)) {
3570 //Only if user has been created now or if it existed previously, but he hasn't got an image (see bug 1123)
3571 $newuserdir = make_user_directory($user->new_id
, true); // Doesn't create the folder, just returns the location
3573 // restore images if new user or image does not exist yet
3574 if (!empty($user->new) or !check_dir_exists($newuserdir)) {
3575 if (make_user_directory($user->new_id
)) { // Creates the folder
3576 $status = backup_copy_file($backup_location, $newuserdir, true);
3580 if ($counter %
2 == 0) {
3581 if (!defined('RESTORE_SILENTLY')) {
3583 if ($counter %
40 == 0) {
3593 //If status is ok and whe have dirs created, returns counter to inform
3594 if ($status and $counter) {
3601 //This function restores the groupfiles from the temp (group_files) directory to the
3602 //dataroot/groups directory
3603 function restore_group_files($restore) {
3611 //First, we check to "groups" exists and create is as necessary
3613 $dest_dir = $CFG->dataroot
.'/groups';
3614 $status = check_dir_exists($dest_dir,true);
3616 //Now, we iterate over "group_files" records to check if that user dir must be
3617 //copied (and renamed) to the "groups" dir.
3618 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/group_files";
3619 //Check if directory exists
3620 if (is_dir($rootdir)) {
3621 $list = list_directories ($rootdir);
3625 foreach ($list as $dir) {
3626 //Look for dir like groupid in backup_ids
3627 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code
,
3628 "table_name","groups",
3630 //If that group exists in backup_ids
3632 if (!file_exists($dest_dir."/".$data->new_id
)) {
3633 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id
,true);
3637 if ($counter %
2 == 0) {
3638 if (!defined('RESTORE_SILENTLY')) {
3640 if ($counter %
40 == 0) {
3650 //If status is ok and whe have dirs created, returns counter to inform
3651 if ($status and $counter) {
3658 //This function restores the course files from the temp (course_files) directory to the
3659 //dataroot/course_id directory
3660 function restore_course_files($restore) {
3668 //First, we check to "course_id" exists and create is as necessary
3670 $dest_dir = $CFG->dataroot
."/".$restore->course_id
;
3671 $status = check_dir_exists($dest_dir,true);
3673 //Now, we iterate over "course_files" records to check if that file/dir must be
3674 //copied to the "dest_dir" dir.
3675 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/course_files";
3676 //Check if directory exists
3677 if (is_dir($rootdir)) {
3678 $list = list_directories_and_files ($rootdir);
3682 foreach ($list as $dir) {
3683 //Copy the dir to its new location
3684 //Only if destination file/dir doesn exists
3685 if (!file_exists($dest_dir."/".$dir)) {
3686 $status = backup_copy_file($rootdir."/".$dir,
3687 $dest_dir."/".$dir,true);
3691 if ($counter %
2 == 0) {
3692 if (!defined('RESTORE_SILENTLY')) {
3694 if ($counter %
40 == 0) {
3703 //If status is ok and whe have dirs created, returns counter to inform
3704 if ($status and $counter) {
3711 //This function restores the site files from the temp (site_files) directory to the
3712 //dataroot/SITEID directory
3713 function restore_site_files($restore) {
3721 //First, we check to "course_id" exists and create is as necessary
3723 $dest_dir = $CFG->dataroot
."/".SITEID
;
3724 $status = check_dir_exists($dest_dir,true);
3726 //Now, we iterate over "site_files" files to check if that file/dir must be
3727 //copied to the "dest_dir" dir.
3728 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/site_files";
3729 //Check if directory exists
3730 if (is_dir($rootdir)) {
3731 $list = list_directories_and_files ($rootdir);
3735 foreach ($list as $dir) {
3736 //Copy the dir to its new location
3737 //Only if destination file/dir doesn exists
3738 if (!file_exists($dest_dir."/".$dir)) {
3739 $status = backup_copy_file($rootdir."/".$dir,
3740 $dest_dir."/".$dir,true);
3744 if ($counter %
2 == 0) {
3745 if (!defined('RESTORE_SILENTLY')) {
3747 if ($counter %
40 == 0) {
3756 //If status is ok and whe have dirs created, returns counter to inform
3757 if ($status and $counter) {
3765 //This function creates all the structures for every module in backup file
3766 //Depending what has been selected.
3767 function restore_create_modules($restore,$xml_file) {
3772 if (!file_exists($xml_file)) {
3777 //info will contain the id and modtype of every module
3778 //in backup_ids->info will be the real info (serialized)
3779 $info = restore_read_xml_modules($restore,$xml_file);
3781 //Now, if we have anything in info, we have to restore that mods
3782 //from backup_ids (calling every mod restore function)
3784 if ($info !== true) {
3785 if (!defined('RESTORE_SILENTLY')) {
3788 //Iterate over each module
3789 foreach ($info as $mod) {
3790 if (empty($restore->mods
[$mod->modtype
]->granular
) // We don't care about per instance, i.e. restore all instances.
3791 ||
(array_key_exists($mod->id
,$restore->mods
[$mod->modtype
]->instances
)
3792 && !empty($restore->mods
[$mod->modtype
]->instances
[$mod->id
]->restore
))) {
3793 $modrestore = $mod->modtype
."_restore_mods";
3794 if (function_exists($modrestore)) { //Debug
3795 // we want to restore all mods even when one fails
3796 // incorrect code here ignored any errors during module restore in 1.6-1.8
3797 $status = $status && $modrestore($mod,$restore);
3799 //Something was wrong. Function should exist.
3804 if (!defined('RESTORE_SILENTLY')) {
3814 //This function creates all the structures for every log in backup file
3815 //Depending what has been selected.
3816 function restore_create_logs($restore,$xml_file) {
3820 //Number of records to get in every chunk
3821 $recordset_size = 4;
3822 //Counter, points to current record
3824 //To count all the recods to restore
3829 if (!file_exists($xml_file)) {
3834 //count_logs will contain the number of logs entries to process
3835 //in backup_ids->info will be the real info (serialized)
3836 $count_logs = restore_read_xml_logs($restore,$xml_file);
3839 //Now, if we have records in count_logs, we have to restore that logs
3840 //from backup_ids. This piece of code makes calls to:
3841 // - restore_log_course() if it's a course log
3842 // - restore_log_user() if it's a user log
3843 // - restore_log_module() if it's a module log.
3844 //And all is segmented in chunks to allow large recordsets to be restored !!
3845 if ($count_logs > 0) {
3846 while ($counter < $count_logs) {
3847 //Get a chunk of records
3848 //Take old_id twice to avoid adodb limitation
3849 $logs = get_records_select("backup_ids","table_name = 'log' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
3853 foreach ($logs as $log) {
3854 //Get the full record from backup_ids
3855 $data = backup_getid($restore->backup_unique_code
,"log",$log->old_id
);
3857 //Now get completed xmlized object
3858 $info = $data->info
;
3859 //traverse_xmlize($info); //Debug
3860 //print_object ($GLOBALS['traverse_array']); //Debug
3861 //$GLOBALS['traverse_array']=""; //Debug
3862 //Now build the LOG record structure
3863 $dblog = new object();
3864 $dblog->time
= backup_todb($info['LOG']['#']['TIME']['0']['#']);
3865 $dblog->userid
= backup_todb($info['LOG']['#']['USERID']['0']['#']);
3866 $dblog->ip
= backup_todb($info['LOG']['#']['IP']['0']['#']);
3867 $dblog->course
= $restore->course_id
;
3868 $dblog->module
= backup_todb($info['LOG']['#']['MODULE']['0']['#']);
3869 $dblog->cmid
= backup_todb($info['LOG']['#']['CMID']['0']['#']);
3870 $dblog->action
= backup_todb($info['LOG']['#']['ACTION']['0']['#']);
3871 $dblog->url
= backup_todb($info['LOG']['#']['URL']['0']['#']);
3872 $dblog->info
= backup_todb($info['LOG']['#']['INFO']['0']['#']);
3873 //We have to recode the userid field
3874 $user = backup_getid($restore->backup_unique_code
,"user",$dblog->userid
);
3876 //echo "User ".$dblog->userid." to user ".$user->new_id."<br />"; //Debug
3877 $dblog->userid
= $user->new_id
;
3879 //We have to recode the cmid field (if module isn't "course" or "user")
3880 if ($dblog->module
!= "course" and $dblog->module
!= "user") {
3881 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$dblog->cmid
);
3883 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
3884 $dblog->cmid
= $cm->new_id
;
3889 //print_object ($dblog); //Debug
3890 //Now, we redirect to the needed function to make all the work
3891 if ($dblog->module
== "course") {
3892 //It's a course log,
3893 $stat = restore_log_course($restore,$dblog);
3894 } elseif ($dblog->module
== "user") {
3896 $stat = restore_log_user($restore,$dblog);
3898 //It's a module log,
3899 $stat = restore_log_module($restore,$dblog);
3905 if ($counter %
10 == 0) {
3906 if (!defined('RESTORE_SILENTLY')) {
3908 if ($counter %
200 == 0) {
3916 //We never should arrive here
3917 $counter = $count_logs;
3926 //This function inserts a course log record, calculating the URL field as necessary
3927 function restore_log_course($restore,$log) {
3932 //echo "<hr />Before transformations<br />"; //Debug
3933 //print_object($log); //Debug
3934 //Depending of the action, we recode different things
3935 switch ($log->action
) {
3937 $log->url
= "view.php?id=".$log->course
;
3938 $log->info
= $log->course
;
3942 $log->url
= "view.php?id=".$log->course
;
3946 //recode the info field (it's the user id)
3947 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3949 $log->info
= $user->new_id
;
3950 //Now, extract the mode from the url field
3951 $mode = substr(strrchr($log->url
,"="),1);
3952 $log->url
= "user.php?id=".$log->course
."&user=".$log->info
."&mode=".$mode;
3957 //Extract the course_module from the url field
3958 $cmid = substr(strrchr($log->url
,"="),1);
3959 //recode the course_module to see it it has been restored
3960 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$cmid);
3962 $cmid = $cm->new_id
;
3963 //Extract the module name and the module id from the info field
3964 $modname = strtok($log->info
," ");
3965 $modid = strtok(" ");
3966 //recode the module id to see if it has been restored
3967 $mod = backup_getid($restore->backup_unique_code
,$modname,$modid);
3969 $modid = $mod->new_id
;
3970 //Now I have everything so reconstruct url and info
3971 $log->info
= $modname." ".$modid;
3972 $log->url
= "../mod/".$modname."/view.php?id=".$cmid;
3978 //Extract the course_module from the url field
3979 $cmid = substr(strrchr($log->url
,"="),1);
3980 //recode the course_module to see it it has been restored
3981 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$cmid);
3983 $cmid = $cm->new_id
;
3984 //Extract the module name and the module id from the info field
3985 $modname = strtok($log->info
," ");
3986 $modid = strtok(" ");
3987 //recode the module id to see if it has been restored
3988 $mod = backup_getid($restore->backup_unique_code
,$modname,$modid);
3990 $modid = $mod->new_id
;
3991 //Now I have everything so reconstruct url and info
3992 $log->info
= $modname." ".$modid;
3993 $log->url
= "../mod/".$modname."/view.php?id=".$cmid;
3999 $log->url
= "view.php?id=".$log->course
;
4003 $log->url
= "edit.php?id=".$log->course
;
4008 //recode the info field (it's the user id)
4009 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4011 $log->info
= $user->new_id
;
4012 $log->url
= "view.php?id=".$log->course
;
4017 //recode the info field (it's the user id)
4018 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4020 $log->info
= $user->new_id
;
4021 $log->url
= "view.php?id=".$log->course
;
4026 //Extract the course_section from the url field
4027 $secid = substr(strrchr($log->url
,"="),1);
4028 //recode the course_section to see if it has been restored
4029 $sec = backup_getid($restore->backup_unique_code
,"course_sections",$secid);
4031 $secid = $sec->new_id
;
4032 //Now I have everything so reconstruct url and info
4033 $log->url
= "editsection.php?id=".$secid;
4038 $log->url
= "view.php?id=".$log->course
;
4043 $log->url
= "recent.php?id=".$log->course
;
4048 $log->url
= "report/log/index.php?id=".$log->course
;
4049 $log->info
= $log->course
;
4053 $log->url
= "report/log/live.php?id=".$log->course
;
4054 $log->info
= $log->course
;
4057 case "report outline":
4058 $log->url
= "report/outline/index.php?id=".$log->course
;
4059 $log->info
= $log->course
;
4062 case "report participation":
4063 $log->url
= "report/participation/index.php?id=".$log->course
;
4064 $log->info
= $log->course
;
4067 case "report stats":
4068 $log->url
= "report/stats/index.php?id=".$log->course
;
4069 $log->info
= $log->course
;
4073 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
4077 //echo "After transformations<br />"; //Debug
4078 //print_object($log); //Debug
4080 //Now if $toinsert is set, insert the record
4082 //echo "Inserting record<br />"; //Debug
4083 $status = insert_record("log",$log);
4088 //This function inserts a user log record, calculating the URL field as necessary
4089 function restore_log_user($restore,$log) {
4094 //echo "<hr />Before transformations<br />"; //Debug
4095 //print_object($log); //Debug
4096 //Depending of the action, we recode different things
4097 switch ($log->action
) {
4099 //recode the info field (it's the user id)
4100 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4102 $log->info
= $user->new_id
;
4103 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4107 case "change password":
4108 //recode the info field (it's the user id)
4109 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4111 $log->info
= $user->new_id
;
4112 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4117 //recode the info field (it's the user id)
4118 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4120 $log->info
= $user->new_id
;
4121 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4126 //recode the info field (it's the user id)
4127 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
4129 $log->info
= $user->new_id
;
4130 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
4135 $log->url
= "view.php?id=".$log->course
;
4139 //We split the url by ampersand char
4140 $first_part = strtok($log->url
,"&");
4141 //Get data after the = char. It's the user being updated
4142 $userid = substr(strrchr($first_part,"="),1);
4144 $user = backup_getid($restore->backup_unique_code
,"user",$userid);
4147 $log->url
= "view.php?id=".$user->new_id
."&course=".$log->course
;
4152 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
4156 //echo "After transformations<br />"; //Debug
4157 //print_object($log); //Debug
4159 //Now if $toinsert is set, insert the record
4161 //echo "Inserting record<br />"; //Debug
4162 $status = insert_record("log",$log);
4167 //This function inserts a module log record, calculating the URL field as necessary
4168 function restore_log_module($restore,$log) {
4173 //echo "<hr />Before transformations<br />"; //Debug
4174 //print_object($log); //Debug
4176 //Now we see if the required function in the module exists
4177 $function = $log->module
."_restore_logs";
4178 if (function_exists($function)) {
4180 $log = $function($restore,$log);
4181 //If everything is ok, mark the insert flag
4187 //echo "After transformations<br />"; //Debug
4188 //print_object($log); //Debug
4190 //Now if $toinsert is set, insert the record
4192 //echo "Inserting record<br />"; //Debug
4193 $status = insert_record("log",$log);
4198 //This function adjusts the instance field into course_modules. It's executed after
4199 //modules restore. There, we KNOW the new instance id !!
4200 function restore_check_instances($restore) {
4206 //We are going to iterate over each course_module saved in backup_ids
4207 $course_modules = get_records_sql("SELECT old_id,new_id
4208 FROM {$CFG->prefix}backup_ids
4209 WHERE backup_code = '$restore->backup_unique_code' AND
4210 table_name = 'course_modules'");
4211 if ($course_modules) {
4212 foreach($course_modules as $cm) {
4213 //Get full record, using backup_getids
4214 $cm_module = backup_getid($restore->backup_unique_code
,"course_modules",$cm->old_id
);
4215 //Now we are going to the REAL course_modules to get its type (field module)
4216 $module = get_record("course_modules","id",$cm_module->new_id
);
4218 //We know the module type id. Get the name from modules
4219 $type = get_record("modules","id",$module->module
);
4221 //We know the type name and the old_id. Get its new_id
4222 //from backup_ids. It's the instance !!!
4223 $instance = backup_getid($restore->backup_unique_code
,$type->name
,$cm_module->info
);
4225 //We have the new instance, so update the record in course_modules
4226 $module->instance
= $instance->new_id
;
4227 //print_object ($module); //Debug
4228 $status = update_record("course_modules",$module);
4239 /// Finally, calculate modinfo cache.
4240 rebuild_course_cache($restore->course_id
);
4247 //=====================================================================================
4249 //== XML Functions (SAX) ==
4251 //=====================================================================================
4253 //This is the class used to do all the xml parse
4254 class MoodleParser
{
4256 var $level = 0; //Level we are
4257 var $counter = 0; //Counter
4258 var $tree = array(); //Array of levels we are
4259 var $content = ""; //Content under current level
4260 var $todo = ""; //What we hav to do when parsing
4261 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
4262 var $temp = ""; //Temp storage.
4263 var $preferences = ""; //Preferences about what to load !!
4264 var $finished = false; //Flag to say xml_parse to stop
4266 //This function is used to get the current contents property value
4267 //They are trimed (and converted from utf8 if needed)
4268 function getContents() {
4269 return trim($this->content
);
4272 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4273 function startElementInfo($parser, $tagName, $attrs) {
4274 //Refresh properties
4276 $this->tree
[$this->level
] = $tagName;
4278 //Output something to avoid browser timeouts...
4281 //Check if we are into INFO zone
4282 //if ($this->tree[2] == "INFO") //Debug
4283 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4286 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
4287 function startElementRoles($parser, $tagName, $attrs) {
4288 //Refresh properties
4290 $this->tree
[$this->level
] = $tagName;
4292 //Output something to avoid browser timeouts...
4295 //Check if we are into INFO zone
4296 //if ($this->tree[2] == "INFO") //Debug
4297 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4301 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
4302 function startElementCourseHeader($parser, $tagName, $attrs) {
4303 //Refresh properties
4305 $this->tree
[$this->level
] = $tagName;
4307 //Output something to avoid browser timeouts...
4310 //Check if we are into COURSE_HEADER zone
4311 //if ($this->tree[3] == "HEADER") //Debug
4312 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4315 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
4316 function startElementBlocks($parser, $tagName, $attrs) {
4317 //Refresh properties
4319 $this->tree
[$this->level
] = $tagName;
4321 //Output something to avoid browser timeouts...
4324 //Check if we are into BLOCKS zone
4325 //if ($this->tree[3] == "BLOCKS") //Debug
4326 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4328 //If we are under a BLOCK tag under a BLOCKS zone, accumule it
4329 if (isset($this->tree
[4]) and isset($this->tree
[3])) { //
4330 if ($this->tree
[4] == "BLOCK" and $this->tree
[3] == "BLOCKS") {
4331 if (!isset($this->temp
)) {
4334 $this->temp
.= "<".$tagName.">";
4339 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
4340 function startElementSections($parser, $tagName, $attrs) {
4341 //Refresh properties
4343 $this->tree
[$this->level
] = $tagName;
4345 //Output something to avoid browser timeouts...
4348 //Check if we are into SECTIONS zone
4349 //if ($this->tree[3] == "SECTIONS") //Debug
4350 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4353 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4354 function startElementFormatData($parser, $tagName, $attrs) {
4355 //Refresh properties
4357 $this->tree
[$this->level
] = $tagName;
4359 //Output something to avoid browser timeouts...
4362 //Accumulate all the data inside this tag
4363 if (isset($this->tree
[3]) && $this->tree
[3] == "FORMATDATA") {
4364 if (!isset($this->temp
)) {
4367 $this->temp
.= "<".$tagName.">";
4370 //Check if we are into FORMATDATA zone
4371 //if ($this->tree[3] == "FORMATDATA") //Debug
4372 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4375 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4376 function startElementMetacourse($parser, $tagName, $attrs) {
4378 //Refresh properties
4380 $this->tree
[$this->level
] = $tagName;
4382 //Output something to avoid browser timeouts...
4385 //Check if we are into METACOURSE zone
4386 //if ($this->tree[3] == "METACOURSE") //Debug
4387 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4390 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4391 function startElementGradebook($parser, $tagName, $attrs) {
4393 //Refresh properties
4395 $this->tree
[$this->level
] = $tagName;
4397 //Output something to avoid browser timeouts...
4400 //Check if we are into GRADEBOOK zone
4401 //if ($this->tree[3] == "GRADEBOOK") //Debug
4402 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4404 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4405 if (isset($this->tree
[5]) and isset($this->tree
[3])) {
4406 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")) {
4408 if (!isset($this->temp
)) {
4411 $this->temp
.= "<".$tagName.">";
4416 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4417 function startElementOldGradebook($parser, $tagName, $attrs) {
4419 //Refresh properties
4421 $this->tree
[$this->level
] = $tagName;
4423 //Output something to avoid browser timeouts...
4426 //Check if we are into GRADEBOOK zone
4427 //if ($this->tree[3] == "GRADEBOOK") //Debug
4428 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4430 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4431 if (isset($this->tree
[5]) and isset($this->tree
[3])) {
4432 if (($this->tree
[5] == "GRADE_PREFERENCE" ||
$this->tree
[5] == "GRADE_LETTER" ||
$this->tree
[5] == "GRADE_CATEGORY" ) && ($this->tree
[3] == "GRADEBOOK")) {
4433 if (!isset($this->temp
)) {
4436 $this->temp
.= "<".$tagName.">";
4442 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
4443 function startElementUsers($parser, $tagName, $attrs) {
4444 //Refresh properties
4446 $this->tree
[$this->level
] = $tagName;
4448 //Check if we are into USERS zone
4449 //if ($this->tree[3] == "USERS") //Debug
4450 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4453 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
4454 function startElementMessages($parser, $tagName, $attrs) {
4455 //Refresh properties
4457 $this->tree
[$this->level
] = $tagName;
4459 //Output something to avoid browser timeouts...
4462 //Check if we are into MESSAGES zone
4463 //if ($this->tree[3] == "MESSAGES") //Debug
4464 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4466 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
4467 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4468 if (($this->tree
[4] == "MESSAGE" ||
$this->tree
[5] == "CONTACT" ) and ($this->tree
[3] == "MESSAGES")) {
4469 if (!isset($this->temp
)) {
4472 $this->temp
.= "<".$tagName.">";
4476 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4477 function startElementQuestions($parser, $tagName, $attrs) {
4478 //Refresh properties
4480 $this->tree
[$this->level
] = $tagName;
4482 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
4483 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
4486 //Output something to avoid browser timeouts...
4489 //Check if we are into QUESTION_CATEGORIES zone
4490 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
4491 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4493 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
4494 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4495 if (($this->tree
[4] == "QUESTION_CATEGORY") and ($this->tree
[3] == "QUESTION_CATEGORIES")) {
4496 if (!isset($this->temp
)) {
4499 $this->temp
.= "<".$tagName.">";
4504 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
4505 function startElementScales($parser, $tagName, $attrs) {
4506 //Refresh properties
4508 $this->tree
[$this->level
] = $tagName;
4510 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
4511 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
4514 //Output something to avoid browser timeouts...
4517 //Check if we are into SCALES zone
4518 //if ($this->tree[3] == "SCALES") //Debug
4519 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4521 //If we are under a SCALE tag under a SCALES zone, accumule it
4522 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4523 if (($this->tree
[4] == "SCALE") and ($this->tree
[3] == "SCALES")) {
4524 if (!isset($this->temp
)) {
4527 $this->temp
.= "<".$tagName.">";
4532 function startElementGroups($parser, $tagName, $attrs) {
4533 //Refresh properties
4535 $this->tree
[$this->level
] = $tagName;
4537 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
4538 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
4541 //Output something to avoid browser timeouts...
4544 //Check if we are into GROUPS zone
4545 //if ($this->tree[3] == "GROUPS") //Debug
4546 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4548 //If we are under a GROUP tag under a GROUPS zone, accumule it
4549 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4550 if (($this->tree
[4] == "GROUP") and ($this->tree
[3] == "GROUPS")) {
4551 if (!isset($this->temp
)) {
4554 $this->temp
.= "<".$tagName.">";
4559 function startElementGroupings($parser, $tagName, $attrs) {
4560 //Refresh properties
4562 $this->tree
[$this->level
] = $tagName;
4564 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
4565 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
4568 //Output something to avoid browser timeouts...
4571 //Check if we are into GROUPINGS zone
4572 //if ($this->tree[3] == "GROUPINGS") //Debug
4573 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4575 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
4576 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4577 if (($this->tree
[4] == "GROUPING") and ($this->tree
[3] == "GROUPINGS")) {
4578 if (!isset($this->temp
)) {
4581 $this->temp
.= "<".$tagName.">";
4586 function startElementGroupingsGroups($parser, $tagName, $attrs) {
4587 //Refresh properties
4589 $this->tree
[$this->level
] = $tagName;
4591 //if ($tagName == "GROUPINGGROUP" && $this->tree[3] == "GROUPINGSGROUPS") { //Debug
4592 // echo "<P>GROUPINGSGROUP: ".strftime ("%X",time()),"-"; //Debug
4595 //Output something to avoid browser timeouts...
4598 //Check if we are into GROUPINGSGROUPS zone
4599 //if ($this->tree[3] == "GROUPINGSGROUPS") //Debug
4600 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4602 //If we are under a GROUPINGGROUP tag under a GROUPINGSGROUPS zone, accumule it
4603 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4604 if (($this->tree
[4] == "GROUPINGGROUP") and ($this->tree
[3] == "GROUPINGSGROUPS")) {
4605 if (!isset($this->temp
)) {
4608 $this->temp
.= "<".$tagName.">";
4613 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
4614 function startElementEvents($parser, $tagName, $attrs) {
4615 //Refresh properties
4617 $this->tree
[$this->level
] = $tagName;
4619 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
4620 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
4623 //Output something to avoid browser timeouts...
4626 //Check if we are into EVENTS zone
4627 //if ($this->tree[3] == "EVENTS") //Debug
4628 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4630 //If we are under a EVENT tag under a EVENTS zone, accumule it
4631 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4632 if (($this->tree
[4] == "EVENT") and ($this->tree
[3] == "EVENTS")) {
4633 if (!isset($this->temp
)) {
4636 $this->temp
.= "<".$tagName.">";
4641 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
4642 function startElementModules($parser, $tagName, $attrs) {
4643 //Refresh properties
4645 $this->tree
[$this->level
] = $tagName;
4647 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
4648 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
4651 //Output something to avoid browser timeouts...
4654 //Check if we are into MODULES zone
4655 //if ($this->tree[3] == "MODULES") //Debug
4656 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4658 //If we are under a MOD tag under a MODULES zone, accumule it
4659 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4660 if (($this->tree
[4] == "MOD") and ($this->tree
[3] == "MODULES")) {
4661 if (!isset($this->temp
)) {
4664 $this->temp
.= "<".$tagName.">";
4669 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
4670 function startElementLogs($parser, $tagName, $attrs) {
4671 //Refresh properties
4673 $this->tree
[$this->level
] = $tagName;
4675 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
4676 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
4679 //Output something to avoid browser timeouts...
4682 //Check if we are into LOGS zone
4683 //if ($this->tree[3] == "LOGS") //Debug
4684 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
4686 //If we are under a LOG tag under a LOGS zone, accumule it
4687 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
4688 if (($this->tree
[4] == "LOG") and ($this->tree
[3] == "LOGS")) {
4689 if (!isset($this->temp
)) {
4692 $this->temp
.= "<".$tagName.">";
4697 //This is the startTag default handler we use when todo is undefined
4698 function startElement($parser, $tagName, $attrs) {
4700 $this->tree
[$this->level
] = $tagName;
4702 //Output something to avoid browser timeouts...
4705 echo $this->level
.str_repeat(" ",$this->level
*2)."<".$tagName."><br />\n"; //Debug
4708 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
4709 function endElementInfo($parser, $tagName) {
4710 //Check if we are into INFO zone
4711 if ($this->tree
[2] == "INFO") {
4712 //if (trim($this->content)) //Debug
4713 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4714 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4715 //Dependig of different combinations, do different things
4716 if ($this->level
== 3) {
4719 $this->info
->backup_name
= $this->getContents();
4721 case "MOODLE_VERSION":
4722 $this->info
->backup_moodle_version
= $this->getContents();
4724 case "MOODLE_RELEASE":
4725 $this->info
->backup_moodle_release
= $this->getContents();
4727 case "BACKUP_VERSION":
4728 $this->info
->backup_backup_version
= $this->getContents();
4730 case "BACKUP_RELEASE":
4731 $this->info
->backup_backup_release
= $this->getContents();
4734 $this->info
->backup_date
= $this->getContents();
4736 case "ORIGINAL_WWWROOT":
4737 $this->info
->original_wwwroot
= $this->getContents();
4739 case "MNET_EXTERNALUSERS":
4740 $this->info
->mnet_externalusers
= $this->getContents();
4744 if ($this->tree
[3] == "DETAILS") {
4745 if ($this->level
== 4) {
4748 $this->info
->backup_metacourse
= $this->getContents();
4751 $this->info
->backup_users
= $this->getContents();
4754 $this->info
->backup_logs
= $this->getContents();
4757 $this->info
->backup_user_files
= $this->getContents();
4760 $this->info
->backup_course_files
= $this->getContents();
4763 $this->info
->backup_site_files
= $this->getContents();
4765 case "GRADEBOOKHISTORIES":
4766 $this->info
->gradebook_histories
= $this->getContents();
4769 $this->info
->backup_messages
= $this->getContents();
4772 $this->info
->backup_block_format
= $this->getContents();
4776 if ($this->level
== 5) {
4779 $this->info
->tempName
= $this->getContents();
4782 $this->info
->mods
[$this->info
->tempName
]->backup
= $this->getContents();
4785 $this->info
->mods
[$this->info
->tempName
]->userinfo
= $this->getContents();
4789 if ($this->level
== 7) {
4792 $this->info
->tempId
= $this->getContents();
4793 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->id
= $this->info
->tempId
;
4796 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->name
= $this->getContents();
4799 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->backup
= $this->getContents();
4802 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->userinfo
= $this->getContents();
4809 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
4810 //Speed up a lot (avoid parse all)
4811 if ($tagName == "INFO") {
4812 $this->finished
= true;
4816 $this->tree
[$this->level
] = "";
4818 $this->content
= "";
4822 function endElementRoles($parser, $tagName) {
4823 //Check if we are into INFO zone
4824 if ($this->tree
[2] == "ROLES") {
4826 if ($this->tree
[3] == "ROLE") {
4827 if ($this->level
== 4) {
4830 $this->info
->tempname
= $this->getContents();
4834 $this->info
->tempshortname
= $this->getContents();
4836 case "ID": // this is the old id
4837 $this->info
->tempid
= $this->getContents();
4841 if ($this->level
== 6) {
4844 $this->info
->roles
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4845 $this->info
->roles
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4847 $this->info
->tempcapname
= $this->getContents();
4848 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->name
= $this->getContents();
4851 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->permission
= $this->getContents();
4853 case "TIMEMODIFIED":
4854 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->timemodified
= $this->getContents();
4857 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->modifierid
= $this->getContents();
4864 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
4865 //Speed up a lot (avoid parse all)
4866 if ($tagName == "ROLES") {
4867 $this->finished
= true;
4871 $this->tree
[$this->level
] = "";
4873 $this->content
= "";
4877 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
4878 function endElementCourseHeader($parser, $tagName) {
4879 //Check if we are into COURSE_HEADER zone
4880 if ($this->tree
[3] == "HEADER") {
4881 //if (trim($this->content)) //Debug
4882 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4883 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4884 //Dependig of different combinations, do different things
4885 if ($this->level
== 4) {
4888 $this->info
->course_id
= $this->getContents();
4891 $this->info
->course_password
= $this->getContents();
4894 $this->info
->course_fullname
= $this->getContents();
4897 $this->info
->course_shortname
= $this->getContents();
4900 $this->info
->course_idnumber
= $this->getContents();
4903 $this->info
->course_summary
= $this->getContents();
4906 $this->info
->course_format
= $this->getContents();
4909 $this->info
->course_showgrades
= $this->getContents();
4912 $this->info
->blockinfo
= $this->getContents();
4915 $this->info
->course_newsitems
= $this->getContents();
4918 $this->info
->course_teacher
= $this->getContents();
4921 $this->info
->course_teachers
= $this->getContents();
4924 $this->info
->course_student
= $this->getContents();
4927 $this->info
->course_students
= $this->getContents();
4930 $this->info
->course_guest
= $this->getContents();
4933 $this->info
->course_startdate
= $this->getContents();
4936 $this->info
->course_numsections
= $this->getContents();
4938 //case "SHOWRECENT": INFO: This is out in 1.3
4939 // $this->info->course_showrecent = $this->getContents();
4942 $this->info
->course_maxbytes
= $this->getContents();
4945 $this->info
->course_showreports
= $this->getContents();
4948 $this->info
->course_groupmode
= $this->getContents();
4950 case "GROUPMODEFORCE":
4951 $this->info
->course_groupmodeforce
= $this->getContents();
4953 case "DEFAULTGROUPINGID":
4954 $this->info
->course_defaultgroupingid
= $this->getContents();
4957 $this->info
->course_lang
= $this->getContents();
4960 $this->info
->course_theme
= $this->getContents();
4963 $this->info
->course_cost
= $this->getContents();
4966 $this->info
->course_currency
= $this->getContents();
4969 $this->info
->course_marker
= $this->getContents();
4972 $this->info
->course_visible
= $this->getContents();
4974 case "HIDDENSECTIONS":
4975 $this->info
->course_hiddensections
= $this->getContents();
4978 $this->info
->course_timecreated
= $this->getContents();
4980 case "TIMEMODIFIED":
4981 $this->info
->course_timemodified
= $this->getContents();
4984 $this->info
->course_metacourse
= $this->getContents();
4986 case "EXPIRENOTIFY":
4987 $this->info
->course_expirynotify
= $this->getContents();
4989 case "NOTIFYSTUDENTS":
4990 $this->info
->course_notifystudents
= $this->getContents();
4992 case "EXPIRYTHRESHOLD":
4993 $this->info
->course_expirythreshold
= $this->getContents();
4996 $this->info
->course_enrollable
= $this->getContents();
4998 case "ENROLSTARTDATE":
4999 $this->info
->course_enrolstartdate
= $this->getContents();
5001 case "ENROLENDDATE":
5002 $this->info
->course_enrolenddate
= $this->getContents();
5005 $this->info
->course_enrolperiod
= $this->getContents();
5009 if ($this->tree
[4] == "CATEGORY") {
5010 if ($this->level
== 5) {
5013 $this->info
->category
->id
= $this->getContents();
5016 $this->info
->category
->name
= $this->getContents();
5022 if ($this->tree
[4] == "ROLES_ASSIGNMENTS") {
5023 if ($this->level
== 6) {
5026 $this->info
->tempname
= $this->getContents();
5029 $this->info
->tempshortname
= $this->getContents();
5032 $this->info
->tempid
= $this->getContents();
5037 if ($this->level
== 8) {
5040 $this->info
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5041 $this->info
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5042 $this->info
->tempuser
= $this->getContents();
5043 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
5046 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
5049 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
5052 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
5054 case "TIMEMODIFIED":
5055 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
5058 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
5061 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
5064 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
5069 } /// ends role_assignments
5071 if ($this->tree
[4] == "ROLES_OVERRIDES") {
5072 if ($this->level
== 6) {
5075 $this->info
->tempname
= $this->getContents();
5078 $this->info
->tempshortname
= $this->getContents();
5081 $this->info
->tempid
= $this->getContents();
5086 if ($this->level
== 8) {
5089 $this->info
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5090 $this->info
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5091 $this->info
->tempname
= $this->getContents(); // change to name of capability
5092 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
5095 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
5097 case "TIMEMODIFIED":
5098 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
5101 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5105 } /// ends role_overrides
5108 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
5109 //Speed up a lot (avoid parse all)
5110 if ($tagName == "HEADER") {
5111 $this->finished
= true;
5115 $this->tree
[$this->level
] = "";
5117 $this->content
= "";
5121 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
5122 function endElementBlocks($parser, $tagName) {
5123 //Check if we are into BLOCKS zone
5124 if ($this->tree
[3] == 'BLOCKS') {
5125 //if (trim($this->content)) //Debug
5126 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5127 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5129 // Collect everything into $this->temp
5130 if (!isset($this->temp
)) {
5133 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5135 //Dependig of different combinations, do different things
5136 if ($this->level
== 4) {
5139 //We've finalized a block, get it
5140 $this->info
->instances
[] = $this->info
->tempinstance
;
5141 unset($this->info
->tempinstance
);
5143 //Also, xmlize INSTANCEDATA and save to db
5144 //Prepend XML standard header to info gathered
5145 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5146 //Call to xmlize for this portion of xml data (one BLOCK)
5147 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5148 $data = xmlize($xml_data,0);
5149 //echo strftime ("%X",time())."<p>"; //Debug
5150 //traverse_xmlize($data); //Debug
5151 //print_object ($GLOBALS['traverse_array']); //Debug
5152 //$GLOBALS['traverse_array']=""; //Debug
5153 //Check for instancedata, is exists, then save to DB
5154 if (isset($data['BLOCK']['#']['INSTANCEDATA']['0']['#'])) {
5156 $oldid = $data['BLOCK']['#']['ID']['0']['#'];
5159 if ($data = $data['BLOCK']['#']['INSTANCEDATA']['0']['#']) {
5160 //Restore code calls this multiple times - so might already have the newid
5161 if ($newid = backup_getid($this->preferences
->backup_unique_code
,'block_instance',$oldid)) {
5162 $newid = $newid->new_id
;
5166 //Save to DB, we will use it later
5167 $status = backup_putid($this->preferences
->backup_unique_code
,'block_instance',$oldid,$newid,$data);
5178 if ($this->level
== 5) {
5181 $this->info
->tempinstance
->id
= $this->getContents();
5183 $this->info
->tempinstance
->name
= $this->getContents();
5186 $this->info
->tempinstance
->pageid
= $this->getContents();
5189 $this->info
->tempinstance
->pagetype
= $this->getContents();
5192 $this->info
->tempinstance
->position
= $this->getContents();
5195 $this->info
->tempinstance
->weight
= $this->getContents();
5198 $this->info
->tempinstance
->visible
= $this->getContents();
5201 $this->info
->tempinstance
->configdata
= $this->getContents();
5208 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
5209 if ($this->level
== 7) {
5212 $this->info
->tempname
= $this->getContents();
5215 $this->info
->tempshortname
= $this->getContents();
5218 $this->info
->tempid
= $this->getContents(); // temp roleid
5223 if ($this->level
== 9) {
5227 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5229 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5231 $this->info
->tempuser
= $this->getContents();
5233 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
5236 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
5239 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
5242 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
5244 case "TIMEMODIFIED":
5245 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
5248 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
5251 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
5254 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
5259 } /// ends role_assignments
5261 if ($this->tree
[5] == "ROLES_OVERRIDES") {
5262 if ($this->level
== 7) {
5265 $this->info
->tempname
= $this->getContents();
5268 $this->info
->tempshortname
= $this->getContents();
5271 $this->info
->tempid
= $this->getContents(); // temp roleid
5276 if ($this->level
== 9) {
5280 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5281 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5282 $this->info
->tempname
= $this->getContents(); // change to name of capability
5283 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
5286 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
5288 case "TIMEMODIFIED":
5289 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
5292 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5296 } /// ends role_overrides
5299 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
5300 //Speed up a lot (avoid parse all)
5301 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
5302 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
5303 if ($this->tree
[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
5304 $this->finished
= true;
5308 $this->tree
[$this->level
] = '';
5310 $this->content
= "";
5313 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
5314 function endElementSections($parser, $tagName) {
5315 //Check if we are into SECTIONS zone
5316 if ($this->tree
[3] == "SECTIONS") {
5317 //if (trim($this->content)) //Debug
5318 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5319 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5320 //Dependig of different combinations, do different things
5321 if ($this->level
== 4) {
5324 //We've finalized a section, get it
5325 $this->info
->sections
[$this->info
->tempsection
->id
] = $this->info
->tempsection
;
5326 unset($this->info
->tempsection
);
5329 if ($this->level
== 5) {
5332 $this->info
->tempsection
->id
= $this->getContents();
5335 $this->info
->tempsection
->number
= $this->getContents();
5338 $this->info
->tempsection
->summary
= $this->getContents();
5341 $this->info
->tempsection
->visible
= $this->getContents();
5345 if ($this->level
== 6) {
5348 if (!isset($this->info
->tempmod
->groupmode
)) {
5349 $this->info
->tempmod
->groupmode
= 0;
5351 if (!isset($this->info
->tempmod
->groupingid
)) {
5352 $this->info
->tempmod
->groupingid
= 0;
5354 if (!isset($this->info
->tempmod
->groupmembersonly
)) {
5355 $this->info
->tempmod
->groupmembersonly
= 0;
5357 if (!isset($this->info
->tempmod
->idnumber
)) {
5358 $this->info
->tempmod
->idnumber
= null;
5361 //We've finalized a mod, get it
5362 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->type
=
5363 $this->info
->tempmod
->type
;
5364 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->instance
=
5365 $this->info
->tempmod
->instance
;
5366 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->added
=
5367 $this->info
->tempmod
->added
;
5368 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->score
=
5369 $this->info
->tempmod
->score
;
5370 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->indent
=
5371 $this->info
->tempmod
->indent
;
5372 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->visible
=
5373 $this->info
->tempmod
->visible
;
5374 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupmode
=
5375 $this->info
->tempmod
->groupmode
;
5376 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupingid
=
5377 $this->info
->tempmod
->groupingid
;
5378 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupmembersonly
=
5379 $this->info
->tempmod
->groupmembersonly
;
5380 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->idnumber
=
5381 $this->info
->tempmod
->idnumber
;
5383 unset($this->info
->tempmod
);
5386 if ($this->level
== 7) {
5389 $this->info
->tempmod
->id
= $this->getContents();
5392 $this->info
->tempmod
->type
= $this->getContents();
5395 $this->info
->tempmod
->instance
= $this->getContents();
5398 $this->info
->tempmod
->added
= $this->getContents();
5401 $this->info
->tempmod
->score
= $this->getContents();
5404 $this->info
->tempmod
->indent
= $this->getContents();
5407 $this->info
->tempmod
->visible
= $this->getContents();
5410 $this->info
->tempmod
->groupmode
= $this->getContents();
5413 $this->info
->tempmod
->groupingid
= $this->getContents();
5415 case "GROUPMEMBERSONLY":
5416 $this->info
->tempmod
->groupmembersonly
= $this->getContents();
5418 $this->info
->tempmod
->idnumber
= $this->getContents();
5425 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_ASSIGNMENTS") {
5427 if ($this->level
== 9) {
5430 $this->info
->tempname
= $this->getContents();
5433 $this->info
->tempshortname
= $this->getContents();
5436 $this->info
->tempid
= $this->getContents(); // temp roleid
5441 if ($this->level
== 11) {
5444 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5446 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5448 $this->info
->tempuser
= $this->getContents();
5450 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
5453 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
5456 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
5459 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
5461 case "TIMEMODIFIED":
5462 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
5465 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
5468 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
5471 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
5476 } /// ends role_assignments
5478 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_OVERRIDES") {
5479 if ($this->level
== 9) {
5482 $this->info
->tempname
= $this->getContents();
5485 $this->info
->tempshortname
= $this->getContents();
5488 $this->info
->tempid
= $this->getContents(); // temp roleid
5493 if ($this->level
== 11) {
5497 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
5498 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
5499 $this->info
->tempname
= $this->getContents(); // change to name of capability
5500 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
5503 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
5505 case "TIMEMODIFIED":
5506 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
5509 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5513 } /// ends role_overrides
5517 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
5518 //Speed up a lot (avoid parse all)
5519 if ($tagName == "SECTIONS") {
5520 $this->finished
= true;
5524 $this->tree
[$this->level
] = "";
5526 $this->content
= "";
5530 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
5531 function endElementFormatData($parser, $tagName) {
5532 //Check if we are into FORMATDATA zone
5533 if ($this->tree
[3] == 'FORMATDATA') {
5534 if (!isset($this->temp
)) {
5537 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5540 if($tagName=='FORMATDATA') {
5541 //Did we have any data? If not don't bother
5542 if($this->temp
!='<FORMATDATA></FORMATDATA>') {
5543 //Prepend XML standard header to info gathered
5544 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5547 //Call to xmlize for this portion of xml data (the FORMATDATA block)
5548 $this->info
->format_data
= xmlize($xml_data,0);
5550 //Stop parsing at end of FORMATDATA
5551 $this->finished
=true;
5555 $this->tree
[$this->level
] = "";
5557 $this->content
= "";
5560 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
5561 function endElementMetacourse($parser, $tagName) {
5562 //Check if we are into METACOURSE zone
5563 if ($this->tree
[3] == 'METACOURSE') {
5564 //if (trim($this->content)) //Debug
5565 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5566 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5567 //Dependig of different combinations, do different things
5568 if ($this->level
== 5) {
5571 //We've finalized a child, get it
5572 $this->info
->childs
[] = $this->info
->tempmeta
;
5573 unset($this->info
->tempmeta
);
5576 //We've finalized a parent, get it
5577 $this->info
->parents
[] = $this->info
->tempmeta
;
5578 unset($this->info
->tempmeta
);
5584 if ($this->level
== 6) {
5587 $this->info
->tempmeta
->id
= $this->getContents();
5590 $this->info
->tempmeta
->idnumber
= $this->getContents();
5593 $this->info
->tempmeta
->shortname
= $this->getContents();
5599 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
5600 //Speed up a lot (avoid parse all)
5601 if ($this->tree
[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
5602 $this->finished
= true;
5606 $this->tree
[$this->level
] = '';
5608 $this->content
= "";
5611 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5612 function endElementGradebook($parser, $tagName) {
5613 //Check if we are into GRADEBOOK zone
5614 if ($this->tree
[3] == "GRADEBOOK") {
5615 //if (trim($this->content)) //Debug
5616 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5617 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
5618 //Acumulate data to info (content + close tag)
5619 //Reconvert: strip htmlchars again and trim to generate xml data
5620 if (!isset($this->temp
)) {
5623 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5624 // We have finished outcome, grade_category or grade_item, reset accumulated
5625 // data because they are close tags
5626 if ($this->level
== 4) {
5629 //If we've finished a grade item, xmlize it an save to db
5630 if (($this->level
== 5) and ($tagName == "GRADE_ITEM")) {
5631 //Prepend XML standard header to info gathered
5632 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5633 //Call to xmlize for this portion of xml data (one PREFERENCE)
5634 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5635 $data = xmlize($xml_data,0);
5636 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
5640 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_items', $item_id,
5642 //Create returning info
5643 $this->info
= $this->counter
;
5649 //If we've finished a grade_category, xmlize it an save to db
5650 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORY")) {
5651 //Prepend XML standard header to info gathered
5652 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5653 //Call to xmlize for this portion of xml data (one CATECORY)
5654 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5655 $data = xmlize($xml_data,0);
5656 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5659 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_categories' ,$category_id,
5661 //Create returning info
5662 $this->info
= $this->counter
;
5667 if (($this->level
== 5) and ($tagName == "GRADE_LETTER")) {
5668 //Prepend XML standard header to info gathered
5669 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5670 //Call to xmlize for this portion of xml data (one CATECORY)
5671 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5672 $data = xmlize($xml_data,0);
5673 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
5676 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_letters' ,$letter_id,
5678 //Create returning info
5679 $this->info
= $this->counter
;
5684 //If we've finished a grade_outcome, xmlize it an save to db
5685 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOME")) {
5686 //Prepend XML standard header to info gathered
5687 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5688 //Call to xmlize for this portion of xml data (one CATECORY)
5689 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5690 $data = xmlize($xml_data,0);
5691 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
5694 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes' ,$outcome_id,
5696 //Create returning info
5697 $this->info
= $this->counter
;
5702 //If we've finished a grade_outcomes_course, xmlize it an save to db
5703 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOMES_COURSE")) {
5704 //Prepend XML standard header to info gathered
5705 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5706 //Call to xmlize for this portion of xml data (one CATECORY)
5707 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5708 $data = xmlize($xml_data,0);
5709 $outcomes_course_id = $data["GRADE_OUTCOMES_COURSE"]["#"]["ID"]["0"]["#"];
5712 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes_courses' ,$outcomes_course_id,
5714 //Create returning info
5715 $this->info
= $this->counter
;
5720 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORIES_HISTORY")) {
5721 //Prepend XML standard header to info gathered
5722 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5723 //Call to xmlize for this portion of xml data (one PREFERENCE)
5724 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5725 $data = xmlize($xml_data,0);
5726 $id = $data["GRADE_CATEGORIES_HISTORY"]["#"]["ID"]["0"]["#"];
5730 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_categories_history', $id,
5732 //Create returning info
5733 $this->info
= $this->counter
;
5739 if (($this->level
== 5) and ($tagName == "GRADE_GRADES_HISTORY")) {
5740 //Prepend XML standard header to info gathered
5741 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5742 //Call to xmlize for this portion of xml data (one PREFERENCE)
5743 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5744 $data = xmlize($xml_data,0);
5745 $id = $data["GRADE_GRADES_HISTORY"]["#"]["ID"]["0"]["#"];
5749 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_grades_history', $id,
5751 //Create returning info
5752 $this->info
= $this->counter
;
5758 if (($this->level
== 5) and ($tagName == "GRADE_ITEM_HISTORY")) {
5759 //Prepend XML standard header to info gathered
5760 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5761 //Call to xmlize for this portion of xml data (one PREFERENCE)
5762 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5763 $data = xmlize($xml_data,0);
5764 $id = $data["GRADE_ITEM_HISTORY"]["#"]["ID"]["0"]["#"];
5768 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_items_history', $id,
5770 //Create returning info
5771 $this->info
= $this->counter
;
5777 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOME_HISTORY")) {
5778 //Prepend XML standard header to info gathered
5779 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5780 //Call to xmlize for this portion of xml data (one PREFERENCE)
5781 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5782 $data = xmlize($xml_data,0);
5783 $id = $data["GRADE_OUTCOME_HISTORY"]["#"]["ID"]["0"]["#"];
5787 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes_history', $id,
5789 //Create returning info
5790 $this->info
= $this->counter
;
5797 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
5798 //Speed up a lot (avoid parse all)
5799 if ($tagName == "GRADEBOOK" and $this->level
== 3) {
5800 $this->finished
= true;
5805 $this->tree
[$this->level
] = "";
5807 $this->content
= "";
5811 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5812 function endElementOldGradebook($parser, $tagName) {
5813 //Check if we are into GRADEBOOK zone
5814 if ($this->tree
[3] == "GRADEBOOK") {
5815 //if (trim($this->content)) //Debug
5816 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5817 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
5818 //Acumulate data to info (content + close tag)
5819 //Reconvert: strip htmlchars again and trim to generate xml data
5820 if (!isset($this->temp
)) {
5823 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5824 //We have finished preferences, letters or categories, reset accumulated
5825 //data because they are close tags
5826 if ($this->level
== 4) {
5829 //If we've finished a message, xmlize it an save to db
5830 if (($this->level
== 5) and ($tagName == "GRADE_PREFERENCE")) {
5831 //Prepend XML standard header to info gathered
5832 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5833 //Call to xmlize for this portion of xml data (one PREFERENCE)
5834 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5835 $data = xmlize($xml_data,0);
5836 //echo strftime ("%X",time())."<p>"; //Debug
5837 //traverse_xmlize($data); //Debug
5838 //print_object ($GLOBALS['traverse_array']); //Debug
5839 //$GLOBALS['traverse_array']=""; //Debug
5840 //Now, save data to db. We'll use it later
5841 //Get id and status from data
5842 $preference_id = $data["GRADE_PREFERENCE"]["#"]["ID"]["0"]["#"];
5845 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_preferences', $preference_id,
5847 //Create returning info
5848 $this->info
= $this->counter
;
5852 //If we've finished a grade_letter, xmlize it an save to db
5853 if (($this->level
== 5) and ($tagName == "GRADE_LETTER")) {
5854 //Prepend XML standard header to info gathered
5855 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5856 //Call to xmlize for this portion of xml data (one LETTER)
5857 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5858 $data = xmlize($xml_data,0);
5859 //echo strftime ("%X",time())."<p>"; //Debug
5860 //traverse_xmlize($data); //Debug
5861 //print_object ($GLOBALS['traverse_array']); //Debug
5862 //$GLOBALS['traverse_array']=""; //Debug
5863 //Now, save data to db. We'll use it later
5864 //Get id and status from data
5865 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
5868 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_letter' ,$letter_id,
5870 //Create returning info
5871 $this->info
= $this->counter
;
5876 //If we've finished a grade_category, xmlize it an save to db
5877 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORY")) {
5878 //Prepend XML standard header to info gathered
5879 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5880 //Call to xmlize for this portion of xml data (one CATECORY)
5881 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5882 $data = xmlize($xml_data,0);
5883 //echo strftime ("%X",time())."<p>"; //Debug
5884 //traverse_xmlize($data); //Debug
5885 //print_object ($GLOBALS['traverse_array']); //Debug
5886 //$GLOBALS['traverse_array']=""; //Debug
5887 //Now, save data to db. We'll use it later
5888 //Get id and status from data
5889 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5892 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_category' ,$category_id,
5894 //Create returning info
5895 $this->info
= $this->counter
;
5901 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
5902 //Speed up a lot (avoid parse all)
5903 if ($tagName == "GRADEBOOK" and $this->level
== 3) {
5904 $this->finished
= true;
5909 $this->tree
[$this->level
] = "";
5911 $this->content
= "";
5915 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
5916 function endElementUsers($parser, $tagName) {
5918 //Check if we are into USERS zone
5919 if ($this->tree
[3] == "USERS") {
5920 //if (trim($this->content)) //Debug
5921 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5922 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5923 //Dependig of different combinations, do different things
5924 if ($this->level
== 4) {
5929 //Save to db, only save if record not already exist
5930 // if there already is an new_id for this entry, just use that new_id?
5931 $newuser = backup_getid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
);
5932 if (isset($newuser->new_id
)) {
5933 $newid = $newuser->new_id
;
5938 backup_putid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
,
5939 $newid,$this->info
->tempuser
);
5942 if ($this->counter %
10 == 0) {
5943 if (!defined('RESTORE_SILENTLY')) {
5945 if ($this->counter %
200 == 0) {
5952 //Delete temp obejct
5953 unset($this->info
->tempuser
);
5958 if ($this->level
== 5) {
5961 $this->info
->users
[$this->getContents()] = $this->getContents();
5962 $this->info
->tempuser
->id
= $this->getContents();
5965 $this->info
->tempuser
->auth
= $this->getContents();
5968 $this->info
->tempuser
->confirmed
= $this->getContents();
5970 case "POLICYAGREED":
5971 $this->info
->tempuser
->policyagreed
= $this->getContents();
5974 $this->info
->tempuser
->deleted
= $this->getContents();
5977 $this->info
->tempuser
->username
= $this->getContents();
5980 $this->info
->tempuser
->password
= $this->getContents();
5983 $this->info
->tempuser
->idnumber
= $this->getContents();
5986 $this->info
->tempuser
->firstname
= $this->getContents();
5989 $this->info
->tempuser
->lastname
= $this->getContents();
5992 $this->info
->tempuser
->email
= $this->getContents();
5995 $this->info
->tempuser
->emailstop
= $this->getContents();
5998 $this->info
->tempuser
->icq
= $this->getContents();
6001 $this->info
->tempuser
->skype
= $this->getContents();
6004 $this->info
->tempuser
->aim
= $this->getContents();
6007 $this->info
->tempuser
->yahoo
= $this->getContents();
6010 $this->info
->tempuser
->msn
= $this->getContents();
6013 $this->info
->tempuser
->phone1
= $this->getContents();
6016 $this->info
->tempuser
->phone2
= $this->getContents();
6019 $this->info
->tempuser
->institution
= $this->getContents();
6022 $this->info
->tempuser
->department
= $this->getContents();
6025 $this->info
->tempuser
->address
= $this->getContents();
6028 $this->info
->tempuser
->city
= $this->getContents();
6031 $this->info
->tempuser
->country
= $this->getContents();
6034 $this->info
->tempuser
->lang
= $this->getContents();
6037 $this->info
->tempuser
->theme
= $this->getContents();
6040 $this->info
->tempuser
->timezone
= $this->getContents();
6043 $this->info
->tempuser
->firstaccess
= $this->getContents();
6046 $this->info
->tempuser
->lastaccess
= $this->getContents();
6049 $this->info
->tempuser
->lastlogin
= $this->getContents();
6051 case "CURRENTLOGIN":
6052 $this->info
->tempuser
->currentlogin
= $this->getContents();
6055 $this->info
->tempuser
->lastip
= $this->getContents();
6058 $this->info
->tempuser
->secret
= $this->getContents();
6061 $this->info
->tempuser
->picture
= $this->getContents();
6064 $this->info
->tempuser
->url
= $this->getContents();
6067 $this->info
->tempuser
->description
= $this->getContents();
6070 $this->info
->tempuser
->mailformat
= $this->getContents();
6073 $this->info
->tempuser
->maildigest
= $this->getContents();
6076 $this->info
->tempuser
->maildisplay
= $this->getContents();
6079 $this->info
->tempuser
->htmleditor
= $this->getContents();
6082 $this->info
->tempuser
->ajax
= $this->getContents();
6084 case "AUTOSUBSCRIBE":
6085 $this->info
->tempuser
->autosubscribe
= $this->getContents();
6088 $this->info
->tempuser
->trackforums
= $this->getContents();
6091 $this->info
->tempuser
->mnethosturl
= $this->getContents();
6093 case "TIMEMODIFIED":
6094 $this->info
->tempuser
->timemodified
= $this->getContents();
6101 if ($this->level
== 6 && $this->tree
[5]!="ROLES_ASSIGNMENTS" && $this->tree
[5]!="ROLES_OVERRIDES") {
6104 //We've finalized a role, get it
6105 $this->info
->tempuser
->roles
[$this->info
->temprole
->type
] = $this->info
->temprole
;
6106 unset($this->info
->temprole
);
6108 case "USER_PREFERENCE":
6109 //We've finalized a user_preference, get it
6110 $this->info
->tempuser
->user_preferences
[$this->info
->tempuserpreference
->name
] = $this->info
->tempuserpreference
;
6111 unset($this->info
->tempuserpreference
);
6113 case "USER_CUSTOM_PROFILE_FIELD":
6114 //We've finalized a user_custom_profile_field, get it
6115 $this->info
->tempuser
->user_custom_profile_fields
[] = $this->info
->tempusercustomprofilefield
;
6116 unset($this->info
->tempusercustomprofilefield
);
6119 //We've finalized a user_tag, get it
6120 $this->info
->tempuser
->user_tags
[] = $this->info
->tempusertag
;
6121 unset($this->info
->tempusertag
);
6128 if ($this->level
== 7 && $this->tree
[5]!="ROLES_ASSIGNMENTS" && $this->tree
[5]!="ROLES_OVERRIDES") {
6129 /// If we are reading roles
6130 if($this->tree
[6] == 'ROLE') {
6133 $this->info
->temprole
->type
= $this->getContents();
6136 $this->info
->temprole
->authority
= $this->getContents();
6139 $this->info
->temprole
->tea_role
= $this->getContents();
6142 $this->info
->temprole
->editall
= $this->getContents();
6145 $this->info
->temprole
->timestart
= $this->getContents();
6148 $this->info
->temprole
->timeend
= $this->getContents();
6150 case "TIMEMODIFIED":
6151 $this->info
->temprole
->timemodified
= $this->getContents();
6154 $this->info
->temprole
->timestart
= $this->getContents();
6157 $this->info
->temprole
->timeend
= $this->getContents();
6160 $this->info
->temprole
->time
= $this->getContents();
6163 $this->info
->temprole
->timeaccess
= $this->getContents();
6166 $this->info
->temprole
->enrol
= $this->getContents();
6171 /// If we are reading user_preferences
6172 } else if ($this->tree
[6] == 'USER_PREFERENCE') {
6175 $this->info
->tempuserpreference
->name
= $this->getContents();
6178 $this->info
->tempuserpreference
->value
= $this->getContents();
6183 /// If we are reading user_custom_profile_fields
6184 } else if ($this->tree
[6] == 'USER_CUSTOM_PROFILE_FIELD') {
6187 $this->info
->tempusercustomprofilefield
->field_name
= $this->getContents();
6190 $this->info
->tempusercustomprofilefield
->field_type
= $this->getContents();
6193 $this->info
->tempusercustomprofilefield
->field_data
= $this->getContents();
6198 /// If we are reading user_tags
6199 } else if ($this->tree
[6] == 'USER_TAG') {
6202 $this->info
->tempusertag
->name
= $this->getContents();
6205 $this->info
->tempusertag
->rawname
= $this->getContents();
6213 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
6215 if ($this->level
== 7) {
6218 $this->info
->tempname
= $this->getContents();
6221 $this->info
->tempshortname
= $this->getContents();
6224 $this->info
->tempid
= $this->getContents(); // temp roleid
6229 if ($this->level
== 9) {
6233 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
6235 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
6237 $this->info
->tempuserid
= $this->getContents();
6239 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->userid
= $this->getContents();
6242 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->hidden
= $this->getContents();
6245 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timestart
= $this->getContents();
6248 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timeend
= $this->getContents();
6250 case "TIMEMODIFIED":
6251 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timemodified
= $this->getContents();
6254 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->modifierid
= $this->getContents();
6257 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->enrol
= $this->getContents();
6260 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->sortorder
= $this->getContents();
6265 } /// ends role_assignments
6267 if ($this->tree
[5] == "ROLES_OVERRIDES") {
6268 if ($this->level
== 7) {
6271 $this->info
->tempname
= $this->getContents();
6274 $this->info
->tempshortname
= $this->getContents();
6277 $this->info
->tempid
= $this->getContents(); // temp roleid
6282 if ($this->level
== 9) {
6286 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
6287 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
6288 $this->info
->tempname
= $this->getContents(); // change to name of capability
6289 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
6292 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
6294 case "TIMEMODIFIED":
6295 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
6298 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
6302 } /// ends role_overrides
6304 } // closes if this->tree[3]=="users"
6306 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
6307 //Speed up a lot (avoid parse all)
6308 if ($tagName == "USERS" and $this->level
== 3) {
6309 $this->finished
= true;
6314 $this->tree
[$this->level
] = "";
6316 $this->content
= "";
6320 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
6321 function endElementMessages($parser, $tagName) {
6322 //Check if we are into MESSAGES zone
6323 if ($this->tree
[3] == "MESSAGES") {
6324 //if (trim($this->content)) //Debug
6325 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6326 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
6327 //Acumulate data to info (content + close tag)
6328 //Reconvert: strip htmlchars again and trim to generate xml data
6329 if (!isset($this->temp
)) {
6332 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6333 //If we've finished a message, xmlize it an save to db
6334 if (($this->level
== 4) and ($tagName == "MESSAGE")) {
6335 //Prepend XML standard header to info gathered
6336 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6337 //Call to xmlize for this portion of xml data (one MESSAGE)
6338 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6339 $data = xmlize($xml_data,0);
6340 //echo strftime ("%X",time())."<p>"; //Debug
6341 //traverse_xmlize($data); //Debug
6342 //print_object ($GLOBALS['traverse_array']); //Debug
6343 //$GLOBALS['traverse_array']=""; //Debug
6344 //Now, save data to db. We'll use it later
6345 //Get id and status from data
6346 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
6347 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
6348 if ($message_status == "READ") {
6349 $table = "message_read";
6355 $status = backup_putid($this->preferences
->backup_unique_code
, $table,$message_id,
6357 //Create returning info
6358 $this->info
= $this->counter
;
6362 //If we've finished a contact, xmlize it an save to db
6363 if (($this->level
== 5) and ($tagName == "CONTACT")) {
6364 //Prepend XML standard header to info gathered
6365 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6366 //Call to xmlize for this portion of xml data (one MESSAGE)
6367 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6368 $data = xmlize($xml_data,0);
6369 //echo strftime ("%X",time())."<p>"; //Debug
6370 //traverse_xmlize($data); //Debug
6371 //print_object ($GLOBALS['traverse_array']); //Debug
6372 //$GLOBALS['traverse_array']=""; //Debug
6373 //Now, save data to db. We'll use it later
6374 //Get id and status from data
6375 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
6378 $status = backup_putid($this->preferences
->backup_unique_code
, 'message_contacts' ,$contact_id,
6380 //Create returning info
6381 $this->info
= $this->counter
;
6387 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
6388 //Speed up a lot (avoid parse all)
6389 if ($tagName == "MESSAGES" and $this->level
== 3) {
6390 $this->finished
= true;
6395 $this->tree
[$this->level
] = "";
6397 $this->content
= "";
6401 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
6402 function endElementQuestions($parser, $tagName) {
6403 //Check if we are into QUESTION_CATEGORIES zone
6404 if ($this->tree
[3] == "QUESTION_CATEGORIES") {
6405 //if (trim($this->content)) //Debug
6406 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6407 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6408 //Acumulate data to info (content + close tag)
6409 //Reconvert: strip htmlchars again and trim to generate xml data
6410 if (!isset($this->temp
)) {
6413 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6414 //If we've finished a mod, xmlize it an save to db
6415 if (($this->level
== 4) and ($tagName == "QUESTION_CATEGORY")) {
6416 //Prepend XML standard header to info gathered
6417 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6418 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
6419 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6420 $data = xmlize($xml_data,0);
6421 //echo strftime ("%X",time())."<p>"; //Debug
6422 //traverse_xmlize($data); //Debug
6423 //print_object ($GLOBALS['traverse_array']); //Debug
6424 //$GLOBALS['traverse_array']=""; //Debug
6425 //Now, save data to db. We'll use it later
6427 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
6429 $status = backup_putid($this->preferences
->backup_unique_code
,"question_categories",$category_id,
6431 //Create returning info
6432 $ret_info = new object();
6433 $ret_info->id
= $category_id;
6434 $this->info
[] = $ret_info;
6440 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
6441 //Speed up a lot (avoid parse all)
6442 if ($tagName == "QUESTION_CATEGORIES" and $this->level
== 3) {
6443 $this->finished
= true;
6447 $this->tree
[$this->level
] = "";
6449 $this->content
= "";
6453 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
6454 function endElementScales($parser, $tagName) {
6455 //Check if we are into SCALES zone
6456 if ($this->tree
[3] == "SCALES") {
6457 //if (trim($this->content)) //Debug
6458 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6459 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6460 //Acumulate data to info (content + close tag)
6461 //Reconvert: strip htmlchars again and trim to generate xml data
6462 if (!isset($this->temp
)) {
6465 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6466 //If we've finished a scale, xmlize it an save to db
6467 if (($this->level
== 4) and ($tagName == "SCALE")) {
6468 //Prepend XML standard header to info gathered
6469 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6470 //Call to xmlize for this portion of xml data (one SCALE)
6471 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6472 $data = xmlize($xml_data,0);
6473 //echo strftime ("%X",time())."<p>"; //Debug
6474 //traverse_xmlize($data); //Debug
6475 //print_object ($GLOBALS['traverse_array']); //Debug
6476 //$GLOBALS['traverse_array']=""; //Debug
6477 //Now, save data to db. We'll use it later
6478 //Get id and from data
6479 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
6481 $status = backup_putid($this->preferences
->backup_unique_code
,"scale",$scale_id,
6483 //Create returning info
6484 $ret_info = new object();
6485 $ret_info->id
= $scale_id;
6486 $this->info
[] = $ret_info;
6492 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
6493 //Speed up a lot (avoid parse all)
6494 if ($tagName == "SCALES" and $this->level
== 3) {
6495 $this->finished
= true;
6499 $this->tree
[$this->level
] = "";
6501 $this->content
= "";
6505 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
6506 function endElementGroups($parser, $tagName) {
6507 //Check if we are into GROUPS zone
6508 if ($this->tree
[3] == "GROUPS") {
6509 //if (trim($this->content)) //Debug
6510 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6511 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6512 //Acumulate data to info (content + close tag)
6513 //Reconvert: strip htmlchars again and trim to generate xml data
6514 if (!isset($this->temp
)) {
6517 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6518 //If we've finished a group, xmlize it an save to db
6519 if (($this->level
== 4) and ($tagName == "GROUP")) {
6520 //Prepend XML standard header to info gathered
6521 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6522 //Call to xmlize for this portion of xml data (one GROUP)
6523 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6524 $data = xmlize($xml_data,0);
6525 //echo strftime ("%X",time())."<p>"; //Debug
6526 //traverse_xmlize($data); //Debug
6527 //print_object ($GLOBALS['traverse_array']); //Debug
6528 //$GLOBALS['traverse_array']=""; //Debug
6529 //Now, save data to db. We'll use it later
6530 //Get id and from data
6531 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
6533 $status = backup_putid($this->preferences
->backup_unique_code
,"groups",$group_id,
6535 //Create returning info
6536 $ret_info = new Object();
6537 $ret_info->id
= $group_id;
6538 $this->info
[] = $ret_info;
6544 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
6545 //Speed up a lot (avoid parse all)
6546 if ($tagName == "GROUPS" and $this->level
== 3) {
6547 $this->finished
= true;
6551 $this->tree
[$this->level
] = "";
6553 $this->content
= "";
6557 //This is the endTag handler we use where we are reading the groupings zone (todo="GROUPINGS")
6558 function endElementGroupings($parser, $tagName) {
6559 //Check if we are into GROUPINGS zone
6560 if ($this->tree
[3] == "GROUPINGS") {
6561 //Acumulate data to info (content + close tag)
6562 //Reconvert: strip htmlchars again and trim to generate xml data
6563 if (!isset($this->temp
)) {
6566 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6567 //If we've finished a group, xmlize it an save to db
6568 if (($this->level
== 4) and ($tagName == "GROUPING")) {
6569 //Prepend XML standard header to info gathered
6570 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6571 //Call to xmlize for this portion of xml data (one GROUPING)
6572 $data = xmlize($xml_data,0);
6573 //Now, save data to db. We'll use it later
6574 //Get id and from data
6575 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
6577 $status = backup_putid($this->preferences
->backup_unique_code
,"groupings",$grouping_id,
6579 //Create returning info
6580 $ret_info = new Object();
6581 $ret_info->id
= $grouping_id;
6582 $this->info
[] = $ret_info;
6588 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6589 //Speed up a lot (avoid parse all)
6590 if ($tagName == "GROUPINGS" and $this->level
== 3) {
6591 $this->finished
= true;
6595 $this->tree
[$this->level
] = "";
6597 $this->content
= "";
6601 //This is the endTag handler we use where we are reading the groupingsgroups zone (todo="GROUPINGGROUPS")
6602 function endElementGroupingsGroups($parser, $tagName) {
6603 //Check if we are into GROUPINGSGROUPS zone
6604 if ($this->tree
[3] == "GROUPINGSGROUPS") {
6605 //Acumulate data to info (content + close tag)
6606 //Reconvert: strip htmlchars again and trim to generate xml data
6607 if (!isset($this->temp
)) {
6610 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6611 //If we've finished a group, xmlize it an save to db
6612 if (($this->level
== 4) and ($tagName == "GROUPINGGROUP")) {
6613 //Prepend XML standard header to info gathered
6614 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6615 //Call to xmlize for this portion of xml data (one GROUPING)
6616 $data = xmlize($xml_data,0);
6617 //Now, save data to db. We'll use it later
6618 //Get id and from data
6619 $groupinggroup_id = $data["GROUPINGGROUP"]["#"]["ID"]["0"]["#"];
6621 $status = backup_putid($this->preferences
->backup_unique_code
,"groupingsgroups",$groupinggroup_id,
6623 //Create returning info
6624 $ret_info = new Object();
6625 $ret_info->id
= $groupinggroup_id;
6626 $this->info
[] = $ret_info;
6632 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6633 //Speed up a lot (avoid parse all)
6634 if ($tagName == "GROUPINGSGROUPS" and $this->level
== 3) {
6635 $this->finished
= true;
6639 $this->tree
[$this->level
] = "";
6641 $this->content
= "";
6645 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
6646 function endElementEvents($parser, $tagName) {
6647 //Check if we are into EVENTS zone
6648 if ($this->tree
[3] == "EVENTS") {
6649 //if (trim($this->content)) //Debug
6650 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6651 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6652 //Acumulate data to info (content + close tag)
6653 //Reconvert: strip htmlchars again and trim to generate xml data
6654 if (!isset($this->temp
)) {
6657 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6658 //If we've finished a event, xmlize it an save to db
6659 if (($this->level
== 4) and ($tagName == "EVENT")) {
6660 //Prepend XML standard header to info gathered
6661 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6662 //Call to xmlize for this portion of xml data (one EVENT)
6663 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6664 $data = xmlize($xml_data,0);
6665 //echo strftime ("%X",time())."<p>"; //Debug
6666 //traverse_xmlize($data); //Debug
6667 //print_object ($GLOBALS['traverse_array']); //Debug
6668 //$GLOBALS['traverse_array']=""; //Debug
6669 //Now, save data to db. We'll use it later
6670 //Get id and from data
6671 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
6673 $status = backup_putid($this->preferences
->backup_unique_code
,"event",$event_id,
6675 //Create returning info
6676 $ret_info = new object();
6677 $ret_info->id
= $event_id;
6678 $this->info
[] = $ret_info;
6684 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
6685 //Speed up a lot (avoid parse all)
6686 if ($tagName == "EVENTS" and $this->level
== 3) {
6687 $this->finished
= true;
6691 $this->tree
[$this->level
] = "";
6693 $this->content
= "";
6697 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
6698 function endElementModules($parser, $tagName) {
6699 //Check if we are into MODULES zone
6700 if ($this->tree
[3] == "MODULES") {
6701 //if (trim($this->content)) //Debug
6702 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6703 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6704 //Acumulate data to info (content + close tag)
6705 //Reconvert: strip htmlchars again and trim to generate xml data
6706 if (!isset($this->temp
)) {
6709 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6710 //If we've finished a mod, xmlize it an save to db
6711 if (($this->level
== 4) and ($tagName == "MOD")) {
6712 //Prepend XML standard header to info gathered
6713 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6714 //Call to xmlize for this portion of xml data (one MOD)
6715 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6716 $data = xmlize($xml_data,0);
6717 //echo strftime ("%X",time())."<p>"; //Debug
6718 //traverse_xmlize($data); //Debug
6719 //print_object ($GLOBALS['traverse_array']); //Debug
6720 //$GLOBALS['traverse_array']=""; //Debug
6721 //Now, save data to db. We'll use it later
6722 //Get id and modtype from data
6723 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
6724 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
6725 //Only if we've selected to restore it
6726 if (!empty($this->preferences
->mods
[$mod_type]->restore
)) {
6728 $status = backup_putid($this->preferences
->backup_unique_code
,$mod_type,$mod_id,
6730 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6731 //Create returning info
6732 $ret_info = new object();
6733 $ret_info->id
= $mod_id;
6734 $ret_info->modtype
= $mod_type;
6735 $this->info
[] = $ret_info;
6744 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
6745 //Speed up a lot (avoid parse all)
6746 if ($tagName == "MODULES" and $this->level
== 3) {
6747 $this->finished
= true;
6751 $this->tree
[$this->level
] = "";
6753 $this->content
= "";
6757 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
6758 function endElementLogs($parser, $tagName) {
6759 //Check if we are into LOGS zone
6760 if ($this->tree
[3] == "LOGS") {
6761 //if (trim($this->content)) //Debug
6762 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6763 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
6764 //Acumulate data to info (content + close tag)
6765 //Reconvert: strip htmlchars again and trim to generate xml data
6766 if (!isset($this->temp
)) {
6769 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
6770 //If we've finished a log, xmlize it an save to db
6771 if (($this->level
== 4) and ($tagName == "LOG")) {
6772 //Prepend XML standard header to info gathered
6773 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
6774 //Call to xmlize for this portion of xml data (one LOG)
6775 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6776 $data = xmlize($xml_data,0);
6777 //echo strftime ("%X",time())."<p>"; //Debug
6778 //traverse_xmlize($data); //Debug
6779 //print_object ($GLOBALS['traverse_array']); //Debug
6780 //$GLOBALS['traverse_array']=""; //Debug
6781 //Now, save data to db. We'll use it later
6782 //Get id and modtype from data
6783 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
6784 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
6785 //We only save log entries from backup file if they are:
6788 // - Module logs about one restored module
6789 if ($log_module == "course" or
6790 $log_module == "user" or
6791 $this->preferences
->mods
[$log_module]->restore
) {
6795 $status = backup_putid($this->preferences
->backup_unique_code
,"log",$log_id,
6797 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6798 //Create returning info
6799 $this->info
= $this->counter
;
6806 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
6807 //Speed up a lot (avoid parse all)
6808 if ($tagName == "LOGS" and $this->level
== 3) {
6809 $this->finished
= true;
6814 $this->tree
[$this->level
] = "";
6816 $this->content
= "";
6820 //This is the endTag default handler we use when todo is undefined
6821 function endElement($parser, $tagName) {
6822 if (trim($this->content
)) //Debug
6823 echo "C".str_repeat(" ",($this->level+
2)*2).$this->getContents()."<br />\n"; //Debug
6824 echo $this->level
.str_repeat(" ",$this->level
*2)."</".$tagName."><br />\n"; //Debug
6827 $this->tree
[$this->level
] = "";
6829 $this->content
= "";
6832 //This is the handler to read data contents (simple accumule it)
6833 function characterData($parser, $data) {
6834 $this->content
.= $data;
6838 //This function executes the MoodleParser
6839 function restore_read_xml ($xml_file,$todo,$preferences) {
6843 $xml_parser = xml_parser_create('UTF-8');
6844 $moodle_parser = new MoodleParser();
6845 $moodle_parser->todo
= $todo;
6846 $moodle_parser->preferences
= $preferences;
6847 xml_set_object($xml_parser,$moodle_parser);
6848 //Depending of the todo we use some element_handler or another
6849 if ($todo == "INFO") {
6850 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
6851 } else if ($todo == "ROLES") {
6852 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
6853 } else if ($todo == "COURSE_HEADER") {
6854 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
6855 } else if ($todo == 'BLOCKS') {
6856 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
6857 } else if ($todo == "SECTIONS") {
6858 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
6859 } else if ($todo == 'FORMATDATA') {
6860 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
6861 } else if ($todo == "METACOURSE") {
6862 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
6863 } else if ($todo == "GRADEBOOK") {
6864 if ($preferences->backup_version
> 2007090500) {
6865 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
6867 xml_set_element_handler($xml_parser, "startElementOldGradebook", "endElementOldGradebook");
6869 } else if ($todo == "USERS") {
6870 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
6871 } else if ($todo == "MESSAGES") {
6872 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
6873 } else if ($todo == "QUESTIONS") {
6874 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
6875 } else if ($todo == "SCALES") {
6876 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
6877 } else if ($todo == "GROUPS") {
6878 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
6879 } else if ($todo == "GROUPINGS") {
6880 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
6881 } else if ($todo == "GROUPINGSGROUPS") {
6882 xml_set_element_handler($xml_parser, "startElementGroupingsGroups", "endElementGroupingsGroups");
6883 } else if ($todo == "EVENTS") {
6884 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
6885 } else if ($todo == "MODULES") {
6886 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
6887 } else if ($todo == "LOGS") {
6888 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
6890 //Define default handlers (must no be invoked when everything become finished)
6891 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
6893 xml_set_character_data_handler($xml_parser, "characterData");
6894 $fp = fopen($xml_file,"r")
6897 // MDL-9290 performance improvement on reading large xml
6898 $lasttime = time(); // crmas
6899 while ($data = fread($fp, 4096) and !$moodle_parser->finished
) {
6901 if ((time() - $lasttime) > 5) {
6906 xml_parse($xml_parser, $data, feof($fp))
6907 or die(sprintf("XML error: %s at line %d",
6908 xml_error_string(xml_get_error_code($xml_parser)),
6909 xml_get_current_line_number($xml_parser)));
6913 //Get info from parser
6914 $info = $moodle_parser->info
;
6917 xml_parser_free($xml_parser);
6919 if ($status && !empty($info)) {
6927 * @param string $errorstr passed by reference, if silent is true,
6928 * errorstr will be populated and this function will return false rather than calling error() or notify()
6929 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
6930 * redirect to the next step in the restore process, instead will return $backup_unique_code
6932 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
6934 global $CFG, $SESSION;
6936 //Prepend dataroot to variable to have the absolute path
6937 $file = $CFG->dataroot
."/".$file;
6939 if (!defined('RESTORE_SILENTLY')) {
6940 //Start the main table
6941 echo "<table cellpadding=\"5\">";
6948 //Check the file exists
6949 if (!is_file($file)) {
6950 if (!defined('RESTORE_SILENTLY')) {
6951 error ("File not exists ($file)");
6953 $errorstr = "File not exists ($file)";
6958 //Check the file name ends with .zip
6959 if (!substr($file,-4) == ".zip") {
6960 if (!defined('RESTORE_SILENTLY')) {
6961 error ("File has an incorrect extension");
6963 $errorstr = 'File has an incorrect extension';
6968 //Now calculate the unique_code for this restore
6969 $backup_unique_code = time();
6971 //Now check and create the backup dir (if it doesn't exist)
6972 if (!defined('RESTORE_SILENTLY')) {
6973 echo "<li>".get_string("creatingtemporarystructures").'</li>';
6975 $status = check_and_create_backup_dir($backup_unique_code);
6978 $status = clear_backup_dir($backup_unique_code);
6981 //Now delete old data and directories under dataroot/temp/backup
6983 if (!defined('RESTORE_SILENTLY')) {
6984 echo "<li>".get_string("deletingolddata").'</li>';
6986 $status = backup_delete_old_data();
6989 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
6991 if (!defined('RESTORE_SILENTLY')) {
6992 echo "<li>".get_string("copyingzipfile").'</li>';
6994 if (! $status = backup_copy_file($file,$CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
6995 if (!defined('RESTORE_SILENTLY')) {
6996 notify("Error copying backup file. Invalid name or bad perms.");
6998 $errorstr = "Error copying backup file. Invalid name or bad perms";
7004 //Now unzip the file
7006 if (!defined('RESTORE_SILENTLY')) {
7007 echo "<li>".get_string("unzippingbackup").'</li>';
7009 if (! $status = restore_unzip ($CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
7010 if (!defined('RESTORE_SILENTLY')) {
7011 notify("Error unzipping backup file. Invalid zip file.");
7013 $errorstr = "Error unzipping backup file. Invalid zip file.";
7019 //Check for Blackboard backups and convert
7021 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
7022 if (!defined('RESTORE_SILENTLY')) {
7023 echo "<li>".get_string("checkingforbbexport").'</li>';
7025 $status = blackboard_convert($CFG->dataroot
."/temp/backup/".$backup_unique_code);
7028 //Now check for the moodle.xml file
7030 $xml_file = $CFG->dataroot
."/temp/backup/".$backup_unique_code."/moodle.xml";
7031 if (!defined('RESTORE_SILENTLY')) {
7032 echo "<li>".get_string("checkingbackup").'</li>';
7034 if (! $status = restore_check_moodle_file ($xml_file)) {
7035 if (!is_file($xml_file)) {
7036 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
7038 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
7040 if (!defined('RESTORE_SILENTLY')) {
7049 $course_header = "";
7051 //Now read the info tag (all)
7053 if (!defined('RESTORE_SILENTLY')) {
7054 echo "<li>".get_string("readinginfofrombackup").'</li>';
7056 //Reading info from file
7057 $info = restore_read_xml_info ($xml_file);
7058 //Reading course_header from file
7059 $course_header = restore_read_xml_course_header ($xml_file);
7061 if(!is_object($course_header)){
7062 // ensure we fail if there is no course header
7063 $course_header = false;
7067 if (!defined('RESTORE_SILENTLY')) {
7071 //End the main table
7076 //We compare Moodle's versions
7077 if ($CFG->version
< $info->backup_moodle_version
&& $status) {
7078 $message = new message();
7079 $message->serverversion
= $CFG->version
;
7080 $message->serverrelease
= $CFG->release
;
7081 $message->backupversion
= $info->backup_moodle_version
;
7082 $message->backuprelease
= $info->backup_moodle_release
;
7083 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
7087 //Now we print in other table, the backup and the course it contains info
7088 if ($info and $course_header and $status) {
7089 //First, the course info
7090 if (!defined('RESTORE_SILENTLY')) {
7091 $status = restore_print_course_header($course_header);
7093 //Now, the backup info
7095 if (!defined('RESTORE_SILENTLY')) {
7096 $status = restore_print_info($info);
7101 //Save course header and info into php session
7103 $SESSION->info
= $info;
7104 $SESSION->course_header
= $course_header;
7107 //Finally, a little form to continue
7108 //with some hidden fields
7110 if (!defined('RESTORE_SILENTLY')) {
7111 echo "<br /><div style='text-align:center'>";
7112 $hidden["backup_unique_code"] = $backup_unique_code;
7113 $hidden["launch"] = "form";
7114 $hidden["file"] = $file;
7115 $hidden["id"] = $id;
7116 print_single_button("restore.php", $hidden, get_string("continue"),"post");
7120 if (empty($noredirect)) {
7121 redirect($CFG->wwwroot
.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
7123 return $backup_unique_code;
7129 if (!defined('RESTORE_SILENTLY')) {
7130 error ("An error has ocurred");
7132 $errorstr = "An error has occured"; // helpful! :P
7139 function restore_setup_for_check(&$restore,$backup_unique_code) {
7141 $restore->backup_unique_code
=$backup_unique_code;
7142 $restore->users
= 2; // yuk
7143 $restore->course_files
= $SESSION->restore
->restore_course_files
;
7144 $restore->site_files
= $SESSION->restore
->restore_site_files
;
7145 if ($allmods = get_records("modules")) {
7146 foreach ($allmods as $mod) {
7147 $modname = $mod->name
;
7148 $var = "restore_".$modname;
7149 //Now check that we have that module info in the backup file
7150 if (isset($SESSION->info
->mods
[$modname]) && $SESSION->info
->mods
[$modname]->backup
== "true") {
7158 function backup_to_restore_array($backup,$k=0) {
7159 if (is_array($backup) ) {
7160 foreach ($backup as $key => $value) {
7161 $newkey = str_replace('backup','restore',$key);
7162 $restore[$newkey] = backup_to_restore_array($value,$key);
7165 else if (is_object($backup)) {
7166 $tmp = get_object_vars($backup);
7167 foreach ($tmp as $key => $value) {
7168 $newkey = str_replace('backup','restore',$key);
7169 $restore->$newkey = backup_to_restore_array($value,$key);
7173 $newkey = str_replace('backup','restore',$k);
7180 * compatibility function
7181 * checks for per-instance backups AND
7182 * older per-module backups
7183 * and returns whether userdata has been selected.
7185 function restore_userdata_selected($restore,$modname,$modid) {
7186 // check first for per instance array
7187 if (!empty($restore->mods
[$modname]->granular
)) { // supports per instance
7188 return array_key_exists($modid,$restore->mods
[$modname]->instances
)
7189 && !empty($restore->mods
[$modname]->instances
[$modid]->userinfo
);
7192 //print_object($restore->mods[$modname]);
7193 return !empty($restore->mods
[$modname]->userinfo
);
7196 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
7201 //Checks for the required files/functions to restore every module
7203 if ($allmods = get_records("modules") ) {
7204 foreach ($allmods as $mod) {
7205 $modname = $mod->name
;
7206 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
7207 //If file exists and we have selected to restore that type of module
7208 if ((file_exists($modfile)) and !empty($restore->mods
[$modname]) and ($restore->mods
[$modname]->restore
)) {
7209 include_once($modfile);
7214 if (!defined('RESTORE_SILENTLY')) {
7215 //Start the main table
7216 echo "<table cellpadding=\"5\">";
7223 //Localtion of the xml file
7224 $xml_file = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/moodle.xml";
7226 //If we've selected to restore into new course
7227 //create it (course)
7228 //Saving conversion id variables into backup_tables
7229 if ($restore->restoreto
== 2) {
7230 if (!defined('RESTORE_SILENTLY')) {
7231 echo '<li>'.get_string('creatingnewcourse') . '</li>';
7233 $oldidnumber = $course_header->course_idnumber
;
7234 if (!$status = restore_create_new_course($restore,$course_header)) {
7235 if (!defined('RESTORE_SILENTLY')) {
7236 notify("Error while creating the new empty course.");
7238 $errorstr = "Error while creating the new empty course.";
7243 //Print course fullname and shortname and category
7245 if (!defined('RESTORE_SILENTLY')) {
7247 echo "<li>".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
7248 echo "<li>".get_string("category").": ".$course_header->category
->name
.'</li>';
7249 if (!empty($oldidnumber)) {
7250 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
7253 //Put the destination course_id
7255 $restore->course_id
= $course_header->course_id
;
7258 if ($status = restore_open_html($restore,$course_header)){
7259 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
7263 $course = get_record("course","id",$restore->course_id
);
7265 if (!defined('RESTORE_SILENTLY')) {
7266 echo "<li>".get_string("usingexistingcourse");
7268 echo "<li>".get_string("from").": ".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
7269 echo "<li>".get_string("to").": ". format_string($course->fullname
) ." (".format_string($course->shortname
).")".'</li>';
7270 if (($restore->deleting
)) {
7271 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
7273 echo "<li>".get_string("addingdatatoexisting").'</li>';
7277 //If we have selected to restore deleting, we do it now.
7278 if ($restore->deleting
) {
7279 if (!defined('RESTORE_SILENTLY')) {
7280 echo "<li>".get_string("deletingolddata").'</li>';
7282 $status = remove_course_contents($restore->course_id
,false) and
7283 delete_dir_contents($CFG->dataroot
."/".$restore->course_id
,"backupdata");
7285 //Now , this situation is equivalent to the "restore to new course" one (we
7286 //have a course record and nothing more), so define it as "to new course"
7287 $restore->restoreto
= 2;
7289 if (!defined('RESTORE_SILENTLY')) {
7290 notify("An error occurred while deleting some of the course contents.");
7292 $errrostr = "An error occurred while deleting some of the course contents.";
7298 if (!defined('RESTORE_SILENTLY')) {
7299 notify("Error opening existing course.");
7302 $errorstr = "Error opening existing course.";
7308 //Now create users as needed
7309 if ($status and ($restore->users
== 0 or $restore->users
== 1)) {
7310 if (!defined('RESTORE_SILENTLY')) {
7311 echo "<li>".get_string("creatingusers")."<br />";
7313 if (!$status = restore_create_users($restore,$xml_file)) {
7314 if (!defined('RESTORE_SILENTLY')) {
7315 notify("Could not restore users.");
7317 $errorstr = "Could not restore users.";
7322 //Now print info about the work done
7324 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
7325 where backup_code = '$restore->backup_unique_code' and
7326 table_name = 'user'");
7334 //Iterate, filling counters
7335 foreach ($recs as $rec) {
7336 //Get full record, using backup_getids
7337 $record = backup_getid($restore->backup_unique_code
,"user",$rec->old_id
);
7338 if (strpos($record->info
,"new") !== false) {
7341 if (strpos($record->info
,"exists") !== false) {
7344 if (strpos($record->info
,"student") !== false) {
7346 } else if (strpos($record->info
,"teacher") !== false) {
7351 if ($counter %
10 == 0) {
7352 if (!defined('RESTORE_SILENTLY')) {
7354 if ($counter %
200 == 0) {
7361 if (!defined('RESTORE_SILENTLY')) {
7362 //Now print information gathered
7363 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
7365 echo "<li>".get_string("students").": ".$student_count.'</li>';
7366 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
7370 if (!defined('RESTORE_SILENTLY')) {
7371 notify("No users were found!");
7372 } // no need to return false here, it's recoverable.
7376 if (!defined('RESTORE_SILENTLY')) {
7382 //Now create groups as needed
7383 if ($status and ($restore->groups
== RESTORE_GROUPS_ONLY
or $restore->groups
== RESTORE_GROUPS_GROUPINGS
)) {
7384 if (!defined('RESTORE_SILENTLY')) {
7385 echo "<li>".get_string("creatinggroups");
7387 if (!$status = restore_create_groups($restore,$xml_file)) {
7388 if (!defined('RESTORE_SILENTLY')) {
7389 notify("Could not restore groups!");
7391 $errorstr = "Could not restore groups!";
7395 if (!defined('RESTORE_SILENTLY')) {
7400 //Now create groupings as needed
7401 if ($status and ($restore->groups
== RESTORE_GROUPINGS_ONLY
or $restore->groups
== RESTORE_GROUPS_GROUPINGS
)) {
7402 if (!defined('RESTORE_SILENTLY')) {
7403 echo "<li>".get_string("creatinggroupings");
7405 if (!$status = restore_create_groupings($restore,$xml_file)) {
7406 if (!defined('RESTORE_SILENTLY')) {
7407 notify("Could not restore groupings!");
7409 $errorstr = "Could not restore groupings!";
7413 if (!defined('RESTORE_SILENTLY')) {
7418 //Now create groupingsgroups as needed
7419 if ($status and $restore->groups
== RESTORE_GROUPS_GROUPINGS
) {
7420 if (!defined('RESTORE_SILENTLY')) {
7421 echo "<li>".get_string("creatinggroupingsgroups");
7423 if (!$status = restore_create_groupings_groups($restore,$xml_file)) {
7424 if (!defined('RESTORE_SILENTLY')) {
7425 notify("Could not restore groups in groupings!");
7427 $errorstr = "Could not restore groups in groupings!";
7431 if (!defined('RESTORE_SILENTLY')) {
7437 //Now create the course_sections and their associated course_modules
7438 //we have to do this after groups and groupings are restored, because we need the new groupings id
7441 if ($restore->restoreto
== 2) {
7442 if (!defined('RESTORE_SILENTLY')) {
7443 echo "<li>".get_string("creatingsections");
7445 if (!$status = restore_create_sections($restore,$xml_file)) {
7446 if (!defined('RESTORE_SILENTLY')) {
7447 notify("Error creating sections in the existing course.");
7449 $errorstr = "Error creating sections in the existing course.";
7453 if (!defined('RESTORE_SILENTLY')) {
7456 //Into existing course
7457 } else if ($restore->restoreto
== 0 or $restore->restoreto
== 1) {
7458 if (!defined('RESTORE_SILENTLY')) {
7459 echo "<li>".get_string("checkingsections");
7461 if (!$status = restore_create_sections($restore,$xml_file)) {
7462 if (!defined('RESTORE_SILENTLY')) {
7463 notify("Error creating sections in the existing course.");
7465 $errorstr = "Error creating sections in the existing course.";
7469 if (!defined('RESTORE_SILENTLY')) {
7474 if (!defined('RESTORE_SILENTLY')) {
7475 notify("Neither a new course or an existing one was specified.");
7478 $errorstr = "Neither a new course or an existing one was specified.";
7484 //Now create metacourse info
7485 if ($status and $restore->metacourse
) {
7486 //Only to new courses!
7487 if ($restore->restoreto
== 2) {
7488 if (!defined('RESTORE_SILENTLY')) {
7489 echo "<li>".get_string("creatingmetacoursedata");
7491 if (!$status = restore_create_metacourse($restore,$xml_file)) {
7492 if (!defined('RESTORE_SILENTLY')) {
7493 notify("Error creating metacourse in the course.");
7495 $errorstr = "Error creating metacourse in the course.";
7499 if (!defined('RESTORE_SILENTLY')) {
7506 //Now create categories and questions as needed
7508 include_once("$CFG->dirroot/question/restorelib.php");
7509 if (!defined('RESTORE_SILENTLY')) {
7510 echo "<li>".get_string("creatingcategoriesandquestions");
7513 if (!$status = restore_create_questions($restore,$xml_file)) {
7514 if (!defined('RESTORE_SILENTLY')) {
7515 notify("Could not restore categories and questions!");
7517 $errorstr = "Could not restore categories and questions!";
7521 if (!defined('RESTORE_SILENTLY')) {
7526 //Now create user_files as needed
7527 if ($status and ($restore->user_files
)) {
7528 if (!defined('RESTORE_SILENTLY')) {
7529 echo "<li>".get_string("copyinguserfiles");
7531 if (!$status = restore_user_files($restore)) {
7532 if (!defined('RESTORE_SILENTLY')) {
7533 notify("Could not restore user files!");
7535 $errorstr = "Could not restore user files!";
7539 //If all is ok (and we have a counter)
7540 if ($status and ($status !== true)) {
7541 //Inform about user dirs created from backup
7542 if (!defined('RESTORE_SILENTLY')) {
7544 echo "<li>".get_string("userzones").": ".$status;
7548 if (!defined('RESTORE_SILENTLY')) {
7553 //Now create course files as needed
7554 if ($status and ($restore->course_files
)) {
7555 if (!defined('RESTORE_SILENTLY')) {
7556 echo "<li>".get_string("copyingcoursefiles");
7558 if (!$status = restore_course_files($restore)) {
7559 if (empty($status)) {
7560 notify("Could not restore course files!");
7562 $errorstr = "Could not restore course files!";
7566 //If all is ok (and we have a counter)
7567 if ($status and ($status !== true)) {
7568 //Inform about user dirs created from backup
7569 if (!defined('RESTORE_SILENTLY')) {
7571 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7575 if (!defined('RESTORE_SILENTLY')) {
7581 //Now create site files as needed
7582 if ($status and ($restore->site_files
)) {
7583 if (!defined('RESTORE_SILENTLY')) {
7584 echo "<li>".get_string('copyingsitefiles');
7586 if (!$status = restore_site_files($restore)) {
7587 if (empty($status)) {
7588 notify("Could not restore site files!");
7590 $errorstr = "Could not restore site files!";
7594 //If all is ok (and we have a counter)
7595 if ($status and ($status !== true)) {
7596 //Inform about user dirs created from backup
7597 if (!defined('RESTORE_SILENTLY')) {
7599 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7603 if (!defined('RESTORE_SILENTLY')) {
7608 //Now create messages as needed
7609 if ($status and ($restore->messages
)) {
7610 if (!defined('RESTORE_SILENTLY')) {
7611 echo "<li>".get_string("creatingmessagesinfo");
7613 if (!$status = restore_create_messages($restore,$xml_file)) {
7614 if (!defined('RESTORE_SILENTLY')) {
7615 notify("Could not restore messages!");
7617 $errorstr = "Could not restore messages!";
7621 if (!defined('RESTORE_SILENTLY')) {
7626 //Now create scales as needed
7628 if (!defined('RESTORE_SILENTLY')) {
7629 echo "<li>".get_string("creatingscales");
7631 if (!$status = restore_create_scales($restore,$xml_file)) {
7632 if (!defined('RESTORE_SILENTLY')) {
7633 notify("Could not restore custom scales!");
7635 $errorstr = "Could not restore custom scales!";
7639 if (!defined('RESTORE_SILENTLY')) {
7644 //Now create events as needed
7646 if (!defined('RESTORE_SILENTLY')) {
7647 echo "<li>".get_string("creatingevents");
7649 if (!$status = restore_create_events($restore,$xml_file)) {
7650 if (!defined('RESTORE_SILENTLY')) {
7651 notify("Could not restore course events!");
7653 $errorstr = "Could not restore course events!";
7657 if (!defined('RESTORE_SILENTLY')) {
7662 //Now create course modules as needed
7664 if (!defined('RESTORE_SILENTLY')) {
7665 echo "<li>".get_string("creatingcoursemodules");
7667 if (!$status = restore_create_modules($restore,$xml_file)) {
7668 if (!defined('RESTORE_SILENTLY')) {
7669 notify("Could not restore modules!");
7671 $errorstr = "Could not restore modules!";
7675 if (!defined('RESTORE_SILENTLY')) {
7680 //Bring back the course blocks -- do it AFTER the modules!!!
7682 //If we are deleting and bringing into a course or making a new course, same situation
7683 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
7684 if (!defined('RESTORE_SILENTLY')) {
7685 echo '<li>'.get_string('creatingblocks');
7687 $course_header->blockinfo
= !empty($course_header->blockinfo
) ?
$course_header->blockinfo
: NULL;
7688 if (!$status = restore_create_blocks($restore, $info->backup_block_format
, $course_header->blockinfo
, $xml_file)) {
7689 if (!defined('RESTORE_SILENTLY')) {
7690 notify('Error while creating the course blocks');
7692 $errorstr = "Error while creating the course blocks";
7696 if (!defined('RESTORE_SILENTLY')) {
7703 //If we are deleting and bringing into a course or making a new course, same situation
7704 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
7705 if (!defined('RESTORE_SILENTLY')) {
7706 echo '<li>'.get_string('courseformatdata');
7708 if (!$status = restore_set_format_data($restore, $xml_file)) {
7709 $error = "Error while setting the course format data";
7710 if (!defined('RESTORE_SILENTLY')) {
7717 if (!defined('RESTORE_SILENTLY')) {
7723 //Now create log entries as needed
7724 if ($status and ($restore->logs
)) {
7725 if (!defined('RESTORE_SILENTLY')) {
7726 echo "<li>".get_string("creatinglogentries");
7728 if (!$status = restore_create_logs($restore,$xml_file)) {
7729 if (!defined('RESTORE_SILENTLY')) {
7730 notify("Could not restore logs!");
7732 $errorstr = "Could not restore logs!";
7736 if (!defined('RESTORE_SILENTLY')) {
7741 //Now, if all is OK, adjust the instance field in course_modules !!
7742 //this also calculates the final modinfo information so, after this,
7743 //code needing it can be used (like role_assignments. MDL-13740)
7745 if (!defined('RESTORE_SILENTLY')) {
7746 echo "<li>".get_string("checkinginstances");
7748 if (!$status = restore_check_instances($restore)) {
7749 if (!defined('RESTORE_SILENTLY')) {
7750 notify("Could not adjust instances in course_modules!");
7752 $errorstr = "Could not adjust instances in course_modules!";
7756 if (!defined('RESTORE_SILENTLY')) {
7761 //Now, if all is OK, adjust activity events
7763 if (!defined('RESTORE_SILENTLY')) {
7764 echo "<li>".get_string("refreshingevents");
7766 if (!$status = restore_refresh_events($restore)) {
7767 if (!defined('RESTORE_SILENTLY')) {
7768 notify("Could not refresh events for activities!");
7770 $errorstr = "Could not refresh events for activities!";
7774 if (!defined('RESTORE_SILENTLY')) {
7779 //Now, if all is OK, adjust inter-activity links
7781 if (!defined('RESTORE_SILENTLY')) {
7782 echo "<li>".get_string("decodinginternallinks");
7784 if (!$status = restore_decode_content_links($restore)) {
7785 if (!defined('RESTORE_SILENTLY')) {
7786 notify("Could not decode content links!");
7788 $errorstr = "Could not decode content links!";
7792 if (!defined('RESTORE_SILENTLY')) {
7797 //Now, with backup files prior to version 2005041100,
7798 //convert all the wiki texts in the course to markdown
7799 if ($status && $restore->backup_version
< 2005041100) {
7800 if (!defined('RESTORE_SILENTLY')) {
7801 echo "<li>".get_string("convertingwikitomarkdown");
7803 if (!$status = restore_convert_wiki2markdown($restore)) {
7804 if (!defined('RESTORE_SILENTLY')) {
7805 notify("Could not convert wiki texts to markdown!");
7807 $errorstr = "Could not convert wiki texts to markdown!";
7811 if (!defined('RESTORE_SILENTLY')) {
7816 //Now create gradebook as needed -- AFTER modules and blocks!!!
7818 if ($restore->backup_version
> 2007090500) {
7819 if (!defined('RESTORE_SILENTLY')) {
7820 echo "<li>".get_string("creatinggradebook");
7822 if (!$status = restore_create_gradebook($restore,$xml_file)) {
7823 if (!defined('RESTORE_SILENTLY')) {
7824 notify("Could not restore gradebook!");
7826 $errorstr = "Could not restore gradebook!";
7831 if (!defined('RESTORE_SILENTLY')) {
7836 // for moodle versions before 1.9, those grades need to be converted to use the new gradebook
7837 // this code needs to execute *after* the course_modules are sorted out
7838 if (!defined('RESTORE_SILENTLY')) {
7839 echo "<li>".get_string("migratinggrades");
7842 /// force full refresh of grading data before migration == crete all items first
7843 if (!$status = restore_migrate_old_gradebook($restore,$xml_file)) {
7844 if (!defined('RESTORE_SILENTLY')) {
7845 notify("Could not migrate gradebook!");
7847 $errorstr = "Could not migrade gradebook!";
7851 if (!defined('RESTORE_SILENTLY')) {
7855 /// force full refresh of grading data after all items are created
7856 grade_force_full_regrading($restore->course_id
);
7857 grade_grab_course_grades($restore->course_id
);
7860 /*******************************************************************************
7861 ************* Restore of Roles and Capabilities happens here ******************
7862 *******************************************************************************/
7863 // try to restore roles even when restore is going to fail - teachers might have
7864 // at least some role assigned - this is not correct though
7865 $status = restore_create_roles($restore, $xml_file) && $status;
7866 $status = restore_roles_settings($restore, $xml_file) && $status;
7868 //Now if all is OK, update:
7869 // - course modinfo field
7870 // - categories table
7871 // - add user as teacher
7873 if (!defined('RESTORE_SILENTLY')) {
7874 echo "<li>".get_string("checkingcourse");
7877 $course = get_record("course","id",$restore->course_id
);
7878 fix_course_sortorder();
7879 // Check if the user has course update capability in the newly restored course
7880 // there is no need to load his capabilities again, because restore_roles_settings
7881 // would have loaded it anyway, if there is any assignments.
7883 $newcontext = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
7884 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
7885 // fix for MDL-9065, use the new config setting if exists
7886 if ($CFG->creatornewroleid
) {
7887 role_assign($CFG->creatornewroleid
, $USER->id
, 0, $newcontext->id
);
7889 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW
, get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
7890 if ($legacyteacher = array_shift($legacyteachers)) {
7891 role_assign($legacyteacher->id
, $USER->id
, 0, $newcontext->id
);
7894 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
7898 if (!defined('RESTORE_SILENTLY')) {
7903 //Cleanup temps (files and db)
7905 if (!defined('RESTORE_SILENTLY')) {
7906 echo "<li>".get_string("cleaningtempdata");
7908 if (!$status = clean_temp_data ($restore)) {
7909 if (!defined('RESTORE_SILENTLY')) {
7910 notify("Could not clean up temporary data from files and database");
7912 $errorstr = "Could not clean up temporary data from files and database";
7916 if (!defined('RESTORE_SILENTLY')) {
7921 // this is not a critical check - the result can be ignored
7922 if (restore_close_html($restore)){
7923 if (!defined('RESTORE_SILENTLY')) {
7924 echo '<li>Closing the Restorelog.html file.</li>';
7928 if (!defined('RESTORE_SILENTLY')) {
7929 notify("Could not close the restorelog.html file");
7933 if (!defined('RESTORE_SILENTLY')) {
7937 //End the main table
7944 //Create, open and write header of the html log file
7945 function restore_open_html($restore,$course_header) {
7951 //Open file for writing
7952 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
7953 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
7954 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
7956 $status = check_dir_exists($dest_dir,true);
7957 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
7958 //Add the stylesheet
7959 $stylesheetshtml = '';
7960 foreach ($CFG->stylesheets
as $stylesheet) {
7961 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
7963 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
7964 $languagehtml = get_html_lang($dir=true);
7966 //Write the header in the new logging file
7967 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
7968 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
7969 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
7970 fwrite ($restorelog_file,"<head>");
7971 fwrite ($restorelog_file,$stylesheetshtml);
7972 fwrite ($restorelog_file,"<title>".$course_header->course_shortname
." Restored </title>");
7973 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
7974 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname
." The FullName is now - ".$course_header->course_fullname
."<br/><br/>");
7975 $startdate = addslashes($course_header->course_startdate
);
7976 $date = usergetdate($startdate);
7977 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
7978 $startdate +
= $restore->course_startdateoffset
;
7979 $date = usergetdate($startdate);
7980 fwrite ($restorelog_file," This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
7983 return $restorelog_file;
7988 //Create & close footer of the html log file
7989 function restore_close_html($restore) {
7995 //Open file for writing
7996 //First, check that course_id/backupdata folder exists in CFG->dataroot
7997 $dest_dir = $CFG->dataroot
."/".$restore->course_id
."/backupdata";
7998 $status = check_dir_exists($dest_dir, true, true);
7999 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
8000 //Write the footer to close the logging file
8001 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
8002 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
8005 return $restorelog_file;
8011 /********************** Roles and Capabilities Related Functions *******************************/
8013 /* Yu: Note recovering of role assignments/overrides need to take place after
8014 users have been recovered, i.e. after we get their new_id, and after all
8015 roles have been recreated or mapped. Contexts can be created on the fly.
8016 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
8017 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
8018 once roles and users have been restored.
8022 * This function restores all the needed roles for this course
8023 * i.e. roles with an assignment in any of the mods or blocks,
8024 * roles assigned on any user (e.g. parent role) and roles
8025 * assigned at course levle
8026 * This function should check for duplicate roles first
8027 * It isn't now, just overwriting
8029 function restore_create_roles($restore, $xmlfile) {
8030 if (!defined('RESTORE_SILENTLY')) {
8031 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
8033 $info = restore_read_xml_roles($xmlfile);
8035 $sitecontext = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
8037 // the following code creates new roles
8038 // but we could use more intelligent detection, and role mapping
8039 // get role mapping info from $restore
8040 $rolemappings = array();
8042 if (!empty($restore->rolesmapping
)) {
8043 $rolemappings = $restore->rolesmapping
;
8045 // $info->roles will be empty for backups pre 1.7
8046 if (isset($info->roles
) && $info->roles
) {
8048 foreach ($info->roles
as $oldroleid=>$roledata) {
8049 if (empty($restore->rolesmapping
)) {
8050 // if this is empty altogether, we came from import or there's no roles used in course at all
8051 // in this case, write the same oldid as this is the same site
8052 // no need to do mapping
8053 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
8054 $oldroleid); // adding a new id
8055 continue; // do not create additonal roles;
8057 // first we check if the roles are in the mappings
8058 // if so, we just do a mapping i.e. update oldids table
8059 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
8060 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
8061 $rolemappings[$oldroleid]); // adding a new id
8065 // code to make new role name/short name if same role name or shortname exists
8066 $fullname = $roledata->name
;
8067 $shortname = $roledata->shortname
;
8068 $currentfullname = "";
8069 $currentshortname = "";
8074 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
8075 $suffixshort = "_".$counter;
8080 $currentfullname = $fullname.$suffixfull;
8081 // Limit the size of shortname - database column accepts <= 100 chars
8082 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
8083 $coursefull = get_record("role","name",addslashes($currentfullname));
8084 $courseshort = get_record("role","shortname",addslashes($currentshortname));
8086 } while ($coursefull ||
$courseshort);
8088 $roledata->name
= $currentfullname;
8089 $roledata->shortname
= $currentshortname;
8091 // done finding a unique name
8093 $newroleid = create_role(addslashes($roledata->name
),addslashes($roledata->shortname
),'');
8094 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
8095 $newroleid); // adding a new id
8096 foreach ($roledata->capabilities
as $capability) {
8098 $roleinfo = new object();
8099 $roleinfo = (object)$capability;
8100 $roleinfo->contextid
= $sitecontext->id
;
8101 $roleinfo->capability
= $capability->name
;
8102 $roleinfo->roleid
= $newroleid;
8104 insert_record('role_capabilities', $roleinfo);
8113 * this function restores role assignments and role overrides
8114 * in course/user/block/mod level, it passed through
8115 * the xml file again
8117 function restore_roles_settings($restore, $xmlfile) {
8118 // data pulls from course, mod, user, and blocks
8120 /*******************************************************
8121 * Restoring from course level assignments *
8122 *******************************************************/
8123 if (!defined('RESTORE_SILENTLY')) {
8124 echo "<li>".get_string("creatingcourseroles").'</li>';
8126 $course = restore_read_xml_course_header($xmlfile);
8128 if (!isset($restore->rolesmapping
)) {
8129 $isimport = true; // course import from another course, or course with no role assignments
8131 $isimport = false; // course restore with role assignments
8134 if (!empty($course->roleassignments
) && !$isimport) {
8135 $courseassignments = $course->roleassignments
;
8137 foreach ($courseassignments as $oldroleid => $courseassignment) {
8138 restore_write_roleassignments($restore, $courseassignment->assignments
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
8141 /*****************************************************
8142 * Restoring from course level overrides *
8143 *****************************************************/
8145 if (!empty($course->roleoverrides
) && !$isimport) {
8146 $courseoverrides = $course->roleoverrides
;
8147 foreach ($courseoverrides as $oldroleid => $courseoverride) {
8148 // if not importing into exiting course, or creating new role, we are ok
8149 // local course overrides to be respected (i.e. restored course overrides ignored)
8150 if ($restore->restoreto
!= 1 ||
empty($restore->rolesmapping
[$oldroleid])) {
8151 restore_write_roleoverrides($restore, $courseoverride->overrides
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
8156 /*******************************************************
8157 * Restoring role assignments/overrdies *
8158 * from module level assignments *
8159 *******************************************************/
8161 if (!defined('RESTORE_SILENTLY')) {
8162 echo "<li>".get_string("creatingmodroles").'</li>';
8164 $sections = restore_read_xml_sections($xmlfile);
8165 $secs = $sections->sections
;
8167 foreach ($secs as $section) {
8168 if (isset($section->mods
)) {
8169 foreach ($section->mods
as $modid=>$mod) {
8170 if (isset($mod->roleassignments
) && !$isimport) {
8171 foreach ($mod->roleassignments
as $oldroleid=>$modassignment) {
8172 restore_write_roleassignments($restore, $modassignment->assignments
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
8175 // role overrides always applies, in import or backup/restore
8176 if (isset($mod->roleoverrides
)) {
8177 foreach ($mod->roleoverrides
as $oldroleid=>$modoverride) {
8178 restore_write_roleoverrides($restore, $modoverride->overrides
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
8185 /*************************************************
8186 * Restoring assignments from blocks level *
8187 * role assignments/overrides *
8188 *************************************************/
8190 if ($restore->restoreto
!= 1) { // skip altogether if restoring to exisitng course by adding
8191 if (!defined('RESTORE_SILENTLY')) {
8192 echo "<li>".get_string("creatingblocksroles").'</li>';
8194 $blocks = restore_read_xml_blocks($restore, $xmlfile);
8195 if (isset($blocks->instances
)) {
8196 foreach ($blocks->instances
as $instance) {
8197 if (isset($instance->roleassignments
) && !$isimport) {
8198 foreach ($instance->roleassignments
as $oldroleid=>$blockassignment) {
8199 restore_write_roleassignments($restore, $blockassignment->assignments
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
8203 // likewise block overrides should always be restored like mods
8204 if (isset($instance->roleoverrides
)) {
8205 foreach ($instance->roleoverrides
as $oldroleid=>$blockoverride) {
8206 restore_write_roleoverrides($restore, $blockoverride->overrides
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
8212 /************************************************
8213 * Restoring assignments from userid level *
8214 * role assignments/overrides *
8215 ************************************************/
8216 if (!defined('RESTORE_SILENTLY')) {
8217 echo "<li>".get_string("creatinguserroles").'</li>';
8219 $info = restore_read_xml_users($restore, $xmlfile);
8220 if (!empty($info->users
) && !$isimport) { // no need to restore user assignments for imports (same course)
8221 //For each user, take its info from backup_ids
8222 foreach ($info->users
as $userid) {
8223 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
8224 if (isset($rec->info
->roleassignments
)) {
8225 foreach ($rec->info
->roleassignments
as $oldroleid=>$userassignment) {
8226 restore_write_roleassignments($restore, $userassignment->assignments
, "user", CONTEXT_USER
, $userid, $oldroleid);
8229 if (isset($rec->info
->roleoverrides
)) {
8230 foreach ($rec->info
->roleoverrides
as $oldroleid=>$useroverride) {
8231 restore_write_roleoverrides($restore, $useroverride->overrides
, "user", CONTEXT_USER
, $userid, $oldroleid);
8240 // auxillary function to write role assignments read from xml to db
8241 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
8243 $role = backup_getid($restore->backup_unique_code
, "role", $oldroleid);
8245 foreach ($assignments as $assignment) {
8247 $olduser = backup_getid($restore->backup_unique_code
,"user",$assignment->userid
);
8248 //Oh dear, $olduser... can be an object, $obj->string or bool!
8249 if (!$olduser ||
(is_string($olduser->info
) && $olduser->info
== "notincourse")) { // it's possible that user is not in the course
8252 $assignment->userid
= $olduser->new_id
; // new userid here
8253 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$assignment->modifierid
);
8254 $assignment->modifierid
= !empty($oldmodifier->new_id
) ?
$oldmodifier->new_id
: 0; // new modifier id here
8255 $assignment->roleid
= $role->new_id
; // restored new role id
8257 // hack to make the correct contextid for course level imports
8258 if ($contextlevel == CONTEXT_COURSE
) {
8259 $oldinstance->new_id
= $restore->course_id
;
8261 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
8264 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
8265 $assignment->contextid
= $newcontext->id
; // new context id
8266 // might already have same assignment
8267 role_assign($assignment->roleid
, $assignment->userid
, 0, $assignment->contextid
, $assignment->timestart
, $assignment->timeend
, $assignment->hidden
, $assignment->enrol
, $assignment->timemodified
);
8272 // auxillary function to write role assignments read from xml to db
8273 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
8275 // it is possible to have an override not relevant to this course context.
8276 // should be ignored(?)
8277 if (!$role = backup_getid($restore->backup_unique_code
, "role", $oldroleid)) {
8281 foreach ($overrides as $override) {
8282 $override->capability
= $override->name
;
8283 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$override->modifierid
);
8284 $override->modifierid
= !empty($oldmodifier->new_id
)?
$oldmodifier->new_id
:0; // new modifier id here
8285 $override->roleid
= $role->new_id
; // restored new role id
8287 // hack to make the correct contextid for course level imports
8288 if ($contextlevel == CONTEXT_COURSE
) {
8289 $oldinstance->new_id
= $restore->course_id
;
8291 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
8294 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
8295 $override->contextid
= $newcontext->id
; // new context id
8296 // use assign capability instead so we can add context to context_rel
8297 assign_capability($override->capability
, $override->permission
, $override->roleid
, $override->contextid
);
8300 //write activity date changes to the html log file, and update date values in the the xml array
8301 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
8306 // loop through time fields in $TAGS
8307 foreach ($TAGS as $TAG) {
8309 // check $TAG has a sensible value
8310 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
8312 if ($openlog==false) {
8313 $openlog = true; // only come through here once
8315 // open file for writing
8316 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
8317 check_dir_exists($course_dir, true);
8318 $restorelog = fopen("$course_dir/restorelog.html", "a");
8320 // start output for this record
8321 $msg = new stdClass();
8322 $msg->recordtype
= $recordtype;
8323 $msg->recordname
= $xml[$NAMETAG][0]['#'];
8324 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
8327 // write old date to $restorelog
8328 $value = $xml[$TAG][0]['#'];
8329 $date = usergetdate($value);
8331 $msg = new stdClass();
8333 $msg->weekday
= $date['weekday'];
8334 $msg->mday
= $date['mday'];
8335 $msg->month
= $date['month'];
8336 $msg->year
= $date['year'];
8337 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
8339 // write new date to $restorelog
8340 $value +
= $restore->course_startdateoffset
;
8341 $date = usergetdate($value);
8343 $msg = new stdClass();
8345 $msg->weekday
= $date['weekday'];
8346 $msg->mday
= $date['mday'];
8347 $msg->month
= $date['month'];
8348 $msg->year
= $date['year'];
8349 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
8351 // update $value in $xml tree for calling module
8352 $xml[$TAG][0]['#'] = "$value";
8355 // close the restore log, if it was opened
8357 fclose($restorelog);