2 //Functions used in restore
4 //This function unzips a zip file in the same directory that it is
5 //It automatically uses pclzip or command line unzip
6 function restore_unzip ($file) {
8 return unzip_file($file, '', false);
12 //This function checks if moodle.xml seems to be a valid xml file
13 //(exists, has an xml header and a course main tag
14 function restore_check_moodle_file ($file) {
19 if ($status = is_file($file)) {
20 //Open it and read the first 200 bytes (chars)
21 $handle = fopen ($file, "r");
22 $first_chars = fread($handle,200);
23 $status = fclose ($handle);
24 //Chek if it has the requires strings
26 $status = strpos($first_chars,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
27 if ($status !== false) {
28 $status = strpos($first_chars,"<MOODLE_BACKUP>");
36 //This function iterates over all modules in backup file, searching for a
37 //MODNAME_refresh_events() to execute. Perhaps it should ve moved to central Moodle...
38 function restore_refresh_events($restore) {
43 //Take all modules in backup
44 $modules = $restore->mods
;
46 foreach($modules as $name => $module) {
47 //Only if the module is being restored
48 if (isset($module->restore
) && $module->restore
== 1) {
49 //Include module library
50 include_once("$CFG->dirroot/mod/$name/lib.php");
51 //If module_refresh_events exists
52 $function_name = $name."_refresh_events";
53 if (function_exists($function_name)) {
54 $status = $function_name($restore->course_id
);
61 //This function makes all the necessary calls to xxxx_decode_content_links_caller()
62 //function in each module, passing them the desired contents to be decoded
63 //from backup format to destination site/course in order to mantain inter-activities
64 //working in the backup/restore process
65 function restore_decode_content_links($restore) {
70 if (!defined('RESTORE_SILENTLY')) {
74 // Restore links in modules.
75 foreach ($restore->mods
as $name => $info) {
76 //If the module is being restored
77 if (isset($info->restore
) && $info->restore
== 1) {
78 //Check if the xxxx_decode_content_links_caller exists
79 include_once("$CFG->dirroot/mod/$name/restorelib.php");
80 $function_name = $name."_decode_content_links_caller";
81 if (function_exists($function_name)) {
82 if (!defined('RESTORE_SILENTLY')) {
83 echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
85 $status = $function_name($restore);
86 if (!defined('RESTORE_SILENTLY')) {
93 // TODO: process all html text also in blocks too
95 // Restore links in questions.
96 require_once("$CFG->dirroot/question/restorelib.php");
97 if (!defined('RESTORE_SILENTLY')) {
98 echo '<li>' . get_string('from') . ' ' . get_string('questions', 'quiz');
100 $status = question_decode_content_links_caller($restore);
101 if (!defined('RESTORE_SILENTLY')) {
105 if (!defined('RESTORE_SILENTLY')) {
112 //This function is called from all xxxx_decode_content_links_caller(),
113 //its task is to ask all modules (maybe other linkable objects) to restore
115 function restore_decode_content_links_worker($content,$restore) {
116 foreach($restore->mods
as $name => $info) {
117 $function_name = $name."_decode_content_links";
118 if (function_exists($function_name)) {
119 $content = $function_name($content,$restore);
125 //This function converts all the wiki texts in the restored course
126 //to the Markdown format. Used only for backup files prior 2005041100.
127 //It calls every module xxxx_convert_wiki2markdown function
128 function restore_convert_wiki2markdown($restore) {
132 if (!defined('RESTORE_SILENTLY')) {
135 foreach ($restore->mods
as $name => $info) {
136 //If the module is being restored
137 if ($info->restore
== 1) {
138 //Check if the xxxx_restore_wiki2markdown exists
139 $function_name = $name."_restore_wiki2markdown";
140 if (function_exists($function_name)) {
141 $status = $function_name($restore);
142 if (!defined('RESTORE_SILENTLY')) {
143 echo "<li>".get_string("modulenameplural",$name);
149 if (!defined('RESTORE_SILENTLY')) {
155 //This function receives a wiki text in the restore process and
156 //return it with every link to modules " modulename:moduleid"
157 //converted if possible. See the space before modulename!!
158 function restore_decode_wiki_content($content,$restore) {
164 $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
166 preg_match_all($searchstring,$content,$foundset);
167 //If found, then we are going to look for its new id (in backup tables)
169 //print_object($foundset); //Debug
170 //Iterate over foundset[2]. They are the old_ids
171 foreach($foundset[2] as $old_id) {
172 //We get the needed variables here (course id)
173 $rec = backup_getid($restore->backup_unique_code
,"course_modules",$old_id);
174 //Personalize the searchstring
175 $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/';
176 //If it is a link to this course, update the link to its new location
179 $result= preg_replace($searchstring,' $1:'.$rec->new_id
.'($2)',$result);
181 //It's a foreign link so redirect it to its original URL
182 $result= preg_replace($searchstring,$restore->original_wwwroot
.'/mod/$1/view.php?id='.$old_id.'($2)',$result);
190 //This function read the xml file and store it data from the info zone in an object
191 function restore_read_xml_info ($xml_file) {
193 //We call the main read_xml function, with todo = INFO
194 $info = restore_read_xml ($xml_file,"INFO",false);
199 //This function read the xml file and store it data from the course header zone in an object
200 function restore_read_xml_course_header ($xml_file) {
202 //We call the main read_xml function, with todo = COURSE_HEADER
203 $info = restore_read_xml ($xml_file,"COURSE_HEADER",false);
208 //This function read the xml file and store its data from the blocks in a object
209 function restore_read_xml_blocks ($xml_file) {
211 //We call the main read_xml function, with todo = BLOCKS
212 $info = restore_read_xml ($xml_file,'BLOCKS',false);
217 //This function read the xml file and store its data from the sections in a object
218 function restore_read_xml_sections ($xml_file) {
220 //We call the main read_xml function, with todo = SECTIONS
221 $info = restore_read_xml ($xml_file,"SECTIONS",false);
226 //This function read the xml file and store its data from the course format in an object
227 function restore_read_xml_formatdata ($xml_file) {
229 //We call the main read_xml function, with todo = FORMATDATA
230 $info = restore_read_xml ($xml_file,'FORMATDATA',false);
235 //This function read the xml file and store its data from the metacourse in a object
236 function restore_read_xml_metacourse ($xml_file) {
238 //We call the main read_xml function, with todo = METACOURSE
239 $info = restore_read_xml ($xml_file,"METACOURSE",false);
244 //This function read the xml file and store its data from the gradebook in a object
245 function restore_read_xml_gradebook ($restore, $xml_file) {
247 //We call the main read_xml function, with todo = GRADEBOOK
248 $info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
253 //This function read the xml file and store its data from the users in
254 //backup_ids->info db (and user's id in $info)
255 function restore_read_xml_users ($restore,$xml_file) {
257 //We call the main read_xml function, with todo = USERS
258 $info = restore_read_xml ($xml_file,"USERS",$restore);
263 //This function read the xml file and store its data from the messages in
264 //backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
265 function restore_read_xml_messages ($restore,$xml_file) {
267 //We call the main read_xml function, with todo = MESSAGES
268 $info = restore_read_xml ($xml_file,"MESSAGES",$restore);
274 //This function read the xml file and store its data from the questions in
275 //backup_ids->info db (and category's id in $info)
276 function restore_read_xml_questions ($restore,$xml_file) {
278 //We call the main read_xml function, with todo = QUESTIONS
279 $info = restore_read_xml ($xml_file,"QUESTIONS",$restore);
284 //This function read the xml file and store its data from the scales in
285 //backup_ids->info db (and scale's id in $info)
286 function restore_read_xml_scales ($restore,$xml_file) {
288 //We call the main read_xml function, with todo = SCALES
289 $info = restore_read_xml ($xml_file,"SCALES",$restore);
294 //This function read the xml file and store its data from the groups in
295 //backup_ids->info db (and group's id in $info)
296 function restore_read_xml_groups ($restore,$xml_file) {
298 //We call the main read_xml function, with todo = GROUPS
299 $info = restore_read_xml ($xml_file,"GROUPS",$restore);
304 //This function read the xml file and store its data from the groupings in
305 //backup_ids->info db (and grouping's id in $info)
306 function restore_read_xml_groupings ($restore,$xml_file) {
308 //We call the main read_xml function, with todo = GROUPINGS
309 $info = restore_read_xml ($xml_file,"GROUPINGS",$restore);
314 //This function read the xml file and store its data from the events (course) in
315 //backup_ids->info db (and event's id in $info)
316 function restore_read_xml_events ($restore,$xml_file) {
318 //We call the main read_xml function, with todo = EVENTS
319 $info = restore_read_xml ($xml_file,"EVENTS",$restore);
324 //This function read the xml file and store its data from the modules in
326 function restore_read_xml_modules ($restore,$xml_file) {
328 //We call the main read_xml function, with todo = MODULES
329 $info = restore_read_xml ($xml_file,"MODULES",$restore);
334 //This function read the xml file and store its data from the logs in
336 function restore_read_xml_logs ($restore,$xml_file) {
338 //We call the main read_xml function, with todo = LOGS
339 $info = restore_read_xml ($xml_file,"LOGS",$restore);
344 function restore_read_xml_roles ($xml_file) {
345 //We call the main read_xml function, with todo = ROLES
346 $info = restore_read_xml ($xml_file,"ROLES",false);
351 //This function prints the contents from the info parammeter passed
352 function restore_print_info ($info) {
358 //This is tha align to every ingo table
359 $table->align
= array ("right","left");
360 //This is the nowrap clause
361 $table->wrap
= array ("","nowrap");
363 $table->width
= "70%";
364 //Put interesting info in table
365 //The backup original name
366 $tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
367 $tab[0][1] = $info->backup_name
;
369 $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
370 $tab[1][1] = $info->backup_moodle_release
." (".$info->backup_moodle_version
.")";
372 $tab[2][0] = "<b>".get_string("backupversion").":</b>";
373 $tab[2][1] = $info->backup_backup_release
." (".$info->backup_backup_version
.")";
375 $tab[3][0] = "<b>".get_string("backupdate").":</b>";
376 $tab[3][1] = userdate($info->backup_date
);
378 print_heading(get_string("backup").":");
380 //Print backup general info
383 if ($info->backup_backup_version
<= 2005070500) {
384 notify(get_string('backupnonisowarning')); // Message informing that this backup may not work!
387 //Now backup contents in another table
392 foreach ($mods as $key => $mod) {
393 $tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
394 if ($mod->backup
== "false") {
395 $tab[$elem][1] = get_string("notincluded");
397 if ($mod->userinfo
== "true") {
398 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
400 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
402 if (isset($mod->instances
) && is_array($mod->instances
) && count($mod->instances
)) {
403 foreach ($mod->instances
as $instance) {
404 if ($instance->backup
) {
406 $tab[$elem][0] = $instance->name
;
407 if ($instance->userinfo
== 'true') {
408 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
410 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
419 $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
420 if ($info->backup_metacourse
== "true") {
421 $tab[$elem][1] = get_string("yes");
423 $tab[$elem][1] = get_string("no");
427 $tab[$elem][0] = "<b>".get_string("users").":</b>";
428 $tab[$elem][1] = get_string($info->backup_users
);
431 $tab[$elem][0] = "<b>".get_string("logs").":</b>";
432 if ($info->backup_logs
== "true") {
433 $tab[$elem][1] = get_string("yes");
435 $tab[$elem][1] = get_string("no");
439 $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
440 if ($info->backup_user_files
== "true") {
441 $tab[$elem][1] = get_string("yes");
443 $tab[$elem][1] = get_string("no");
447 $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
448 if ($info->backup_course_files
== "true") {
449 $tab[$elem][1] = get_string("yes");
451 $tab[$elem][1] = get_string("no");
454 //Messages info (only showed if present)
455 if ($info->backup_messages
== 'true') {
456 $tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
457 $tab[$elem][1] = get_string('yes');
464 print_heading(get_string("backupdetails").":");
465 //Print backup general info
474 //This function prints the contents from the course_header parammeter passed
475 function restore_print_course_header ($course_header) {
478 if ($course_header) {
479 //This is tha align to every ingo table
480 $table->align
= array ("right","left");
482 $table->width
= "70%";
483 //Put interesting course header in table
485 $tab[0][0] = "<b>".get_string("name").":</b>";
486 $tab[0][1] = $course_header->course_fullname
." (".$course_header->course_shortname
.")";
488 $tab[1][0] = "<b>".get_string("summary").":</b>";
489 $tab[1][1] = $course_header->course_summary
;
492 print_heading(get_string("course").":");
493 //Print backup course header info
501 //This function create a new course record.
502 //When finished, course_header contains the id of the new course
503 function restore_create_new_course($restore,&$course_header) {
509 $fullname = $course_header->course_fullname
;
510 $shortname = $course_header->course_shortname
;
511 $currentfullname = "";
512 $currentshortname = "";
514 //Iteratere while the name exists
517 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
518 $suffixshort = "_".$counter;
523 $currentfullname = $fullname.$suffixfull;
524 // Limit the size of shortname - database column accepts <= 15 chars
525 $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
526 $coursefull = get_record("course","fullname",addslashes($currentfullname));
527 $courseshort = get_record("course","shortname",addslashes($currentshortname));
529 } while ($coursefull ||
$courseshort);
531 //New name = currentname
532 $course_header->course_fullname
= $currentfullname;
533 $course_header->course_shortname
= $currentshortname;
535 // first try to get it from restore
536 if ($restore->restore_restorecatto
) {
537 $category = get_record('course_categories', 'id', $restore->restore_restorecatto
);
540 // else we try to get it from the xml file
541 //Now calculate the category
543 $category = get_record("course_categories","id",$course_header->category
->id
,
544 "name",addslashes($course_header->category
->name
));
547 //If no exists, try by name only
549 $category = get_record("course_categories","name",addslashes($course_header->category
->name
));
552 //If no exists, get category id 1
554 $category = get_record("course_categories","id","1");
557 //If category 1 doesn'exists, lets create the course category (get it from backup file)
559 $ins_category->name
= addslashes($course_header->category
->name
);
560 $ins_category->parent
= 0;
561 $ins_category->sortorder
= 0;
562 $ins_category->coursecount
= 0;
563 $ins_category->visible
= 0; //To avoid interferences with the rest of the site
564 $ins_category->timemodified
= time();
565 $newid = insert_record("course_categories",$ins_category);
566 $category->id
= $newid;
567 $category->name
= $course_header->category
->name
;
569 //If exists, put new category id
571 $course_header->category
->id
= $category->id
;
572 $course_header->category
->name
= $category->name
;
573 //Error, cannot locate category
575 $course_header->category
->id
= 0;
576 $course_header->category
->name
= get_string("unknowncategory");
580 //Create the course_object
582 $course->category
= addslashes($course_header->category
->id
);
583 $course->password
= addslashes($course_header->course_password
);
584 $course->fullname
= addslashes($course_header->course_fullname
);
585 $course->shortname
= addslashes($course_header->course_shortname
);
586 $course->idnumber
= addslashes($course_header->course_idnumber
);
587 $course->idnumber
= ''; //addslashes($course_header->course_idnumber); // we don't want this at all.
588 $course->summary
= restore_decode_absolute_links(addslashes($course_header->course_summary
));
589 $course->format
= addslashes($course_header->course_format
);
590 $course->showgrades
= addslashes($course_header->course_showgrades
);
591 $course->newsitems
= addslashes($course_header->course_newsitems
);
592 $course->teacher
= addslashes($course_header->course_teacher
);
593 $course->teachers
= addslashes($course_header->course_teachers
);
594 $course->student
= addslashes($course_header->course_student
);
595 $course->students
= addslashes($course_header->course_students
);
596 $course->guest
= addslashes($course_header->course_guest
);
597 $course->startdate
= addslashes($course_header->course_startdate
);
598 $course->startdate +
= $restore->course_startdateoffset
;
599 $course->enrolperiod
= addslashes($course_header->course_enrolperiod
);
600 $course->numsections
= addslashes($course_header->course_numsections
);
601 //$course->showrecent = addslashes($course_header->course_showrecent); INFO: This is out in 1.3
602 $course->maxbytes
= addslashes($course_header->course_maxbytes
);
603 $course->showreports
= addslashes($course_header->course_showreports
);
604 if (isset($course_header->course_groupmode
)) {
605 $course->groupmode
= addslashes($course_header->course_groupmode
);
607 if (isset($course_header->course_groupmodeforce
)) {
608 $course->groupmodeforce
= addslashes($course_header->course_groupmodeforce
);
610 $course->lang
= addslashes($course_header->course_lang
);
611 $course->theme
= addslashes($course_header->course_theme
);
612 $course->cost
= addslashes($course_header->course_cost
);
613 $course->currency
= isset($course_header->course_currency
)?
addslashes($course_header->course_currency
):'';
614 $course->marker
= addslashes($course_header->course_marker
);
615 $course->visible
= addslashes($course_header->course_visible
);
616 $course->hiddensections
= addslashes($course_header->course_hiddensections
);
617 $course->timecreated
= addslashes($course_header->course_timecreated
);
618 $course->timemodified
= addslashes($course_header->course_timemodified
);
619 $course->metacourse
= addslashes($course_header->course_metacourse
);
620 //Calculate sortorder field
621 $sortmax = get_record_sql('SELECT MAX(sortorder) AS max
622 FROM ' . $CFG->prefix
. 'course
623 WHERE category=' . $course->category
);
624 if (!empty($sortmax->max
)) {
625 $course->sortorder
= $sortmax->max +
1;
628 $course->sortorder
= 100;
631 //Now, recode some languages (Moodle 1.5)
632 if ($course->lang
== 'ma_nt') {
633 $course->lang
= 'mi_nt';
636 //Disable course->metacourse if avoided in restore config
637 if (!$restore->metacourse
) {
638 $course->metacourse
= 0;
641 //Check if the theme exists in destination server
642 $themes = get_list_of_themes();
643 if (!in_array($course->theme
, $themes)) {
647 //Now insert the record
648 $newid = insert_record("course",$course);
650 //save old and new course id
651 backup_putid ($restore->backup_unique_code
,"course",$course_header->course_id
,$newid);
652 //Replace old course_id in course_header
653 $course_header->course_id
= $newid;
663 * Returns the best question category (id) found to restore one
664 * question category from a backup file. Works by stamp (since Moodle 1.1)
665 * or by name (for older versions).
667 * @param object $cat the question_categories record to be searched
668 * @param integer $courseid the course where we are restoring
669 * @return integer the id of a existing question_category or 0 (not found)
671 function restore_get_best_question_category($cat, $courseid) {
675 //Decide how to work (by stamp or name)
677 $searchfield = 'stamp';
678 $searchvalue = $cat->stamp
;
680 $searchfield = 'name';
681 $searchvalue = $cat->name
;
684 //First shot. Try to get the category from the course being restored
685 if ($fcat = get_record('question_categories','course',$courseid,$searchfield,$searchvalue)) {
687 //Second shot. Try to obtain any concordant category and check its publish status and editing rights
688 } else if ($fcats = get_records('question_categories', $searchfield, $searchvalue, 'id', 'id, publish, course')) {
689 foreach ($fcats as $fcat) {
690 if ($fcat->publish
== 1 && has_capability('moodle/site:restore', get_context_instance(CONTEXT_COURSE
, $fcat->course
))) {
700 //This function creates all the block stuff when restoring courses
701 //It calls selectively to restore_create_block_instances() for 1.5
702 //and above backups. Upwards compatible with old blocks.
703 function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) {
707 delete_records('block_instance', 'pageid', $restore->course_id
, 'pagetype', PAGE_COURSE_VIEW
);
708 if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5
709 if (empty($blockinfo)) {
710 // Looks like it's from Moodle < 1.3. Let's give the course default blocks...
711 $newpage = page_create_object(PAGE_COURSE_VIEW
, $restore->course_id
);
712 blocks_repopulate_page($newpage);
714 // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup
715 $blockrecords = get_records_select('block', '', '', 'name, id');
716 $temp_blocks_l = array();
717 $temp_blocks_r = array();
718 @list
($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo);
719 $temp_blocks = array(BLOCK_POS_LEFT
=> explode(',', $temp_blocks_l), BLOCK_POS_RIGHT
=> explode(',', $temp_blocks_r));
720 foreach($temp_blocks as $blockposition => $blocks) {
722 foreach($blocks as $blockname) {
723 if(!isset($blockrecords[$blockname])) {
724 // We don't know anything about this block!
727 $blockinstance = new stdClass
;
728 // Remove any - prefix before doing the name-to-id mapping
729 if(substr($blockname, 0, 1) == '-') {
730 $blockname = substr($blockname, 1);
731 $blockinstance->visible
= 0;
733 $blockinstance->visible
= 1;
735 $blockinstance->blockid
= $blockrecords[$blockname]->id
;
736 $blockinstance->pageid
= $restore->course_id
;
737 $blockinstance->pagetype
= PAGE_COURSE_VIEW
;
738 $blockinstance->position
= $blockposition;
739 $blockinstance->weight
= $blockweight;
740 if(!$status = insert_record('block_instance', $blockinstance)) {
747 } else if($backup_block_format == 'instances') {
748 $status = restore_create_block_instances($restore,$xml_file);
755 //This function creates all the block_instances from xml when restoring in a
757 function restore_create_block_instances($restore,$xml_file) {
761 if (!file_exists($xml_file)) {
766 $info = restore_read_xml_blocks($xml_file);
769 if(empty($info->instances
)) {
773 // First of all, iterate over the blocks to see which distinct pages we have
774 // in our hands and arrange the blocks accordingly.
775 $pageinstances = array();
776 foreach($info->instances
as $instance) {
778 //pagetype and pageid black magic, we have to handle the case of blocks for the
779 //course, blocks from other pages in that course etc etc etc.
781 if($instance->pagetype
== PAGE_COURSE_VIEW
) {
782 // This one's easy...
783 $instance->pageid
= $restore->course_id
;
786 $parts = explode('-', $instance->pagetype
);
787 if($parts[0] == 'mod') {
788 if(!$restore->mods
[$parts[1]]->restore
) {
791 $getid = backup_getid($restore->backup_unique_code
, $parts[1], $instance->pageid
);
792 $instance->pageid
= $getid->new_id
;
795 // Not invented here ;-)
800 if(!isset($pageinstances[$instance->pagetype
])) {
801 $pageinstances[$instance->pagetype
] = array();
803 if(!isset($pageinstances[$instance->pagetype
][$instance->pageid
])) {
804 $pageinstances[$instance->pagetype
][$instance->pageid
] = array();
807 $pageinstances[$instance->pagetype
][$instance->pageid
][] = $instance;
810 $blocks = get_records_select('block', '', '', 'name, id, multiple');
812 // For each type of page we have restored
813 foreach($pageinstances as $thistypeinstances) {
815 // For each page id of that type
816 foreach($thistypeinstances as $thisidinstances) {
818 $addedblocks = array();
819 $maxweights = array();
821 // For each block instance in that page
822 foreach($thisidinstances as $instance) {
824 if(!isset($blocks[$instance->name
])) {
825 //We are trying to restore a block we don't have...
829 //If we have already added this block once and multiples aren't allowed, disregard it
830 if(!$blocks[$instance->name
]->multiple
&& isset($addedblocks[$instance->name
])) {
834 //If its the first block we add to a new position, start weight counter equal to 0.
835 if(empty($maxweights[$instance->position
])) {
836 $maxweights[$instance->position
] = 0;
839 //If the instance weight is greater than the weight counter (we skipped some earlier
840 //blocks most probably), bring it back in line.
841 if($instance->weight
> $maxweights[$instance->position
]) {
842 $instance->weight
= $maxweights[$instance->position
];
846 $instance->blockid
= $blocks[$instance->name
]->id
;
848 if ($newid = insert_record('block_instance', $instance)) {
849 if (!empty($instance->id
)) { // this will only be set if we come from 1.7 and above backups
850 backup_putid ($restore->backup_unique_code
,"block_instance",$instance->id
,$newid);
857 //Get an object for the block and tell it it's been restored so it can update dates
859 $blockobj=block_instance($instance->name
,$instance);
860 $blockobj->after_restore($restore);
862 //Now we can increment the weight counter
863 ++
$maxweights[$instance->position
];
865 //Keep track of block types we have already added
866 $addedblocks[$instance->name
] = true;
875 //This function creates all the course_sections and course_modules from xml
876 //when restoring in a new course or simply checks sections and create records
877 //in backup_ids when restoring in a existing course
878 function restore_create_sections(&$restore, $xml_file) {
884 if (!file_exists($xml_file)) {
889 $info = restore_read_xml_sections($xml_file);
891 //Put the info in the DB, recoding ids and saving the in backup tables
896 //For each, section, save it to db
897 foreach ($info->sections
as $key => $sect) {
899 $section->course
= $restore->course_id
;
900 $section->section
= $sect->number
;
901 $section->summary
= restore_decode_absolute_links(addslashes($sect->summary
));
902 $section->visible
= $sect->visible
;
903 $section->sequence
= "";
904 //Now calculate the section's newid
906 if ($restore->restoreto
== 2) {
907 //Save it to db (only if restoring to new course)
908 $newid = insert_record("course_sections",$section);
910 //Get section id when restoring in existing course
911 $rec = get_record("course_sections","course",$restore->course_id
,
912 "section",$section->section
);
913 //If that section doesn't exist, get section 0 (every mod will be
916 $rec = get_record("course_sections","course",$restore->course_id
,
919 //New check. If section 0 doesn't exist, insert it here !!
920 //Teorically this never should happen but, in practice, some users
921 //have reported this issue.
923 $zero_sec->course
= $restore->course_id
;
924 $zero_sec->section
= 0;
925 $zero_sec->summary
= "";
926 $zero_sec->sequence
= "";
927 $newid = insert_record("course_sections",$zero_sec);
932 $sequence = $rec->sequence
;
935 //save old and new section id
936 backup_putid ($restore->backup_unique_code
,"course_sections",$key,$newid);
940 //If all is OK, go with associated mods
942 //If we have mods in the section
943 if (!empty($sect->mods
)) {
944 //For each mod inside section
945 foreach ($sect->mods
as $keym => $mod) {
946 // Yu: This part is called repeatedly for every instance,
947 // so it is necessary to set the granular flag and check isset()
948 // when the first instance of this type of mod is processed.
950 //if (!isset($restore->mods[$mod->type]->granular) && isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) {
952 if (!isset($restore->mods
[$mod->type
]->granular
)) {
953 if (isset($restore->mods
[$mod->type
]->instances
) && is_array($restore->mods
[$mod->type
]->instances
)) {
954 // This defines whether we want to restore specific
955 // instances of the modules (granular restore), or
956 // whether we don't care and just want to restore
957 // all module instances (non-granular).
958 $restore->mods
[$mod->type
]->granular
= true;
960 $restore->mods
[$mod->type
]->granular
= false;
964 //Check if we've to restore this module (and instance)
965 if (!empty($restore->mods
[$mod->type
]->restore
)) {
966 if (empty($restore->mods
[$mod->type
]->granular
) // we don't care about per instance
967 ||
(array_key_exists($mod->instance
,$restore->mods
[$mod->type
]->instances
)
968 && !empty($restore->mods
[$mod->type
]->instances
[$mod->instance
]->restore
))) {
970 //Get the module id from modules
971 $module = get_record("modules","name",$mod->type
);
973 $course_module->course
= $restore->course_id
;
974 $course_module->module
= $module->id
;
975 $course_module->section
= $newid;
976 $course_module->added
= $mod->added
;
977 $course_module->score
= $mod->score
;
978 $course_module->indent
= $mod->indent
;
979 $course_module->visible
= $mod->visible
;
980 if (isset($mod->groupmode
)) {
981 $course_module->groupmode
= $mod->groupmode
;
983 $course_module->instance
= 0;
984 //NOTE: The instance (new) is calculated and updated in db in the
985 // final step of the restore. We don't know it yet.
986 //print_object($course_module); //Debug
989 $newidmod = insert_record("course_modules",$course_module);
991 //save old and new module id
992 //In the info field, we save the original instance of the module
994 backup_putid ($restore->backup_unique_code
,"course_modules",
995 $keym,$newidmod,$mod->instance
);
997 $restore->mods
[$mod->type
]->instances
[$mod->instance
]->restored_as_course_module
= $newidmod;
1001 //Now, calculate the sequence field
1004 $sequence .= ",".$newidmod;
1006 $sequence = $newidmod;
1017 //If all is OK, update sequence field in course_sections
1019 if (isset($sequence)) {
1020 $update_rec->id
= $newid;
1021 $update_rec->sequence
= $sequence;
1022 $status = update_record("course_sections",$update_rec);
1032 //Called to set up any course-format specific data that may be in the file
1033 function restore_set_format_data($restore,$xml_file) {
1038 if (!file_exists($xml_file)) {
1041 //Load data from XML to info
1042 if(!($info = restore_read_xml_formatdata($xml_file))) {
1046 //Process format data if there is any
1047 if (isset($info->format_data
)) {
1048 if(!$format=get_field('course','format','id',$restore->course_id
)) {
1051 // If there was any data then it must have a restore method
1052 $file=$CFG->dirroot
."/course/format/$format/restorelib.php";
1053 if(!file_exists($file)) {
1056 require_once($file);
1057 $function=$format.'_restore_format_data';
1058 if(!function_exists($function)) {
1061 return $function($restore,$info->format_data
);
1064 // If we got here then there's no data, but that's cool
1068 //This function creates all the metacourse data from xml, notifying
1069 //about each incidence
1070 function restore_create_metacourse($restore,$xml_file) {
1076 if (!file_exists($xml_file)) {
1081 //Load data from XML to info
1082 $info = restore_read_xml_metacourse($xml_file);
1085 //Process info about metacourse
1086 if ($status and $info) {
1087 //Process child records
1088 if (!empty($info->childs
)) {
1089 foreach ($info->childs
as $child) {
1091 $dbmetacourse = false;
1092 //Check if child course exists in destination server
1093 //(by id in the same server or by idnumber and shortname in other server)
1094 if ($restore->original_wwwroot
== $CFG->wwwroot
) {
1095 //Same server, lets see by id
1096 $dbcourse = get_record('course','id',$child->id
);
1098 //Different server, lets see by idnumber and shortname, and only ONE record
1099 $dbcount = count_records('course','idnumber',$child->idnumber
,'shortname',$child->shortname
);
1100 if ($dbcount == 1) {
1101 $dbcourse = get_record('course','idnumber',$child->idnumber
,'shortname',$child->shortname
);
1104 //If child course has been found, insert data
1106 $dbmetacourse->child_course
= $dbcourse->id
;
1107 $dbmetacourse->parent_course
= $restore->course_id
;
1108 $status = insert_record ('course_meta',$dbmetacourse);
1110 //Child course not found, notice!
1111 if (!defined('RESTORE_SILENTLY')) {
1112 echo '<ul><li>'.get_string ('childcoursenotfound').' ('.$child->id
.'/'.$child->idnumber
.'/'.$child->shortname
.')</li></ul>';
1116 //Now, recreate student enrolments...
1117 sync_metacourse($restore->course_id
);
1119 //Process parent records
1120 if (!empty($info->parents
)) {
1121 foreach ($info->parents
as $parent) {
1123 $dbmetacourse = false;
1124 //Check if parent course exists in destination server
1125 //(by id in the same server or by idnumber and shortname in other server)
1126 if ($restore->original_wwwroot
== $CFG->wwwroot
) {
1127 //Same server, lets see by id
1128 $dbcourse = get_record('course','id',$parent->id
);
1130 //Different server, lets see by idnumber and shortname, and only ONE record
1131 $dbcount = count_records('course','idnumber',$parent->idnumber
,'shortname',$parent->shortname
);
1132 if ($dbcount == 1) {
1133 $dbcourse = get_record('course','idnumber',$parent->idnumber
,'shortname',$parent->shortname
);
1136 //If parent course has been found, insert data if it is a metacourse
1138 if ($dbcourse->metacourse
) {
1139 $dbmetacourse->parent_course
= $dbcourse->id
;
1140 $dbmetacourse->child_course
= $restore->course_id
;
1141 $status = insert_record ('course_meta',$dbmetacourse);
1142 //Now, recreate student enrolments in parent course
1143 sync_metacourse($dbcourse->id
);
1145 //Parent course isn't metacourse, notice!
1146 if (!defined('RESTORE_SILENTLY')) {
1147 echo '<ul><li>'.get_string ('parentcoursenotmetacourse').' ('.$parent->id
.'/'.$parent->idnumber
.'/'.$parent->shortname
.')</li></ul>';
1151 //Parent course not found, notice!
1152 if (!defined('RESTORE_SILENTLY')) {
1153 echo '<ul><li>'.get_string ('parentcoursenotfound').' ('.$parent->id
.'/'.$parent->idnumber
.'/'.$parent->shortname
.')</li></ul>';
1163 //This function creates all the gradebook data from xml, notifying
1164 //about each incidence
1165 function restore_create_gradebook($restore,$xml_file) {
1171 if (!file_exists($xml_file)) {
1175 // Get info from xml
1176 // info will contain the number of record to process
1177 $info = restore_read_xml_gradebook($restore, $xml_file);
1179 // If we have info, then process
1184 // Count how many we have
1185 $categoriescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_categories');
1186 $itemscount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_items');
1187 $outcomecount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_outcomes');
1189 // we need to know if all grade items that were backed up are being restored
1190 // if that is not the case, we do not restore grade categories nor gradeitems of category type
1191 // i.e. the aggregated grades of that category
1193 $restoreall = true; // set to false if any grade_item is not selected/restored
1195 if ($recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'", "old_id", "old_id, old_id")) {
1196 foreach ($recs as $rec) {
1199 if ($data = backup_getid($restore->backup_unique_code
,'grade_items',$rec->old_id
)) {
1201 $info = $data->info
;
1202 // do not restore if this grade_item is a mod, and
1203 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1206 if ($itemtype == 'mod') {
1208 $iteminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1209 $itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1210 if (!restore_userdata_selected($restore, $itemmodule, $iteminstance)) {
1211 // module instance not selected when restored using granular
1212 // we are not restoring all grade items, set flag to false
1213 // so that we do not process grade categories and related grade items/grades
1214 $restoreall = false;
1222 // return if nothing to restore
1223 if (!$itemscount && !$categoriescount && !outcomecount
) {
1228 if (!defined('RESTORE_SILENTLY')) {
1231 // Number of records to get in every chunk
1232 $recordset_size = 2;
1233 // Flag to mark if we must continue
1236 // Process categories
1237 if ($categoriescount && $continue && $restoreall) {
1238 if (!defined('RESTORE_SILENTLY')) {
1239 echo '<li>'.get_string('gradecategories','grades').'</li>';
1242 while ($counter < $categoriescount) {
1243 // Fetch recordset_size records in each iteration
1244 $recs = get_records_select("backup_ids","table_name = 'grade_categories' AND backup_code = '$restore->backup_unique_code'",
1250 foreach ($recs as $rec) {
1251 // Get the full record from backup_ids
1252 $data = backup_getid($restore->backup_unique_code
,'grade_categories',$rec->old_id
);
1254 // Now get completed xmlized object
1255 $info = $data->info
;
1256 //traverse_xmlize($info); //Debug
1257 //print_object ($GLOBALS['traverse_array']); //Debug
1258 //$GLOBALS['traverse_array']=""; //Debug
1259 //Now build the GRADE_PREFERENCES record structure
1261 $dbrec->courseid
= $restore->course_id
;
1263 // get the new grade category parent
1264 if (!empty($info['GRADE_CATEGORY']['#']['PARENT']['0']['#'])) {
1265 $parent = backup_getid($restore->backup_unique_code
,'grade_categories',backup_todb($info['GRADE_CATEGORY']['#']['PARENT']['0']['#']));
1266 $dbrec->parent
= $parent->new_id
;
1269 $dbrec->fullname
= backup_todb($info['GRADE_CATEGORY']['#']['FULLNAME']['0']['#']);
1270 $dbrec->aggregation
= backup_todb($info['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#']);
1271 $dbrec->keephigh
= backup_todb($info['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#']);
1272 $dbrec->droplow
= backup_todb($info['GRADE_CATEGORY']['#']['DROPLOW']['0']['#']);
1273 $dbrec->hidden
= backup_todb($info['GRADE_CATEGORY']['#']['HIDDEN']['0']['#']);
1275 //Structure is equal to db, insert record
1276 //if the fullname doesn't exist
1277 if (!$prerec = get_record('grade_categories','courseid',$dbrec->courseid
,'fullname',$dbrec->fullname
)) {
1278 $newid = insert_record('grade_categories',$dbrec);
1279 $status = backup_putid($restore->backup_unique_code
,'grade_categories',$rec->old_id
,$newid);
1280 // update this record so we can put in the right paths
1281 // this can only be done after we got the new id
1282 $dbrec->id
= $newid;
1283 include_once($CFG->dirroot
.'/lib/grade/grade_category.php');
1284 // rebuild the path, we need only parents info
1285 // the order of restoring should ensure that the parent and grandparent(s)
1286 // are already restored
1287 $dbrec->path
= grade_category
::build_path($dbrec);
1288 // this is not needed in the xml because
1289 // given this parent and grandparent(s) we can recalculate the depth
1290 $dbrec->depth
= substr_count($dbrec->path
, '/');
1291 update_record('grade_categories', $dbrec);
1293 // if fullname already exists, we should keep the current grade category
1294 $status = backup_putid($restore->backup_unique_code
,'grade_categories',$rec->old_id
,$rec->oldid
);
1297 //Increment counters
1300 if ($counter %
1 == 0) {
1301 if (!defined('RESTORE_SILENTLY')) {
1303 if ($counter %
20 == 0) {
1315 if ($outcomecount && $continue) {
1316 if (!defined('RESTORE_SILENTLY')) {
1317 echo '<li>'.get_string('gradeoutcomes','grades').'</li>';
1320 while ($counter < $outcomecount) {
1321 //Fetch recordset_size records in each iteration
1322 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes' AND backup_code = '$restore->backup_unique_code'",
1328 foreach ($recs as $rec) {
1329 //Get the full record from backup_ids
1330 $data = backup_getid($restore->backup_unique_code
,'grade_outcomes',$rec->old_id
);
1332 //Now get completed xmlized object
1333 $info = $data->info
;
1334 //traverse_xmlize($info); //Debug
1335 //print_object ($GLOBALS['traverse_array']); //Debug
1336 //$GLOBALS['traverse_array']=""; //Debug
1337 //Now build the GRADE_PREFERENCES record structure
1339 $dbrec->courseid
= $restore->course_id
;
1340 $dbrec->shortname
= backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']);
1341 $dbrec->fullname
= backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#']);
1343 if ($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#']) {
1344 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#']));
1345 $derec->scaleid
= $scale->new_id
;
1348 $modifier = backup_getid($restore->backup_unique_code
,"user", backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#']));
1349 $derec->usermodified
= $modifier->new_id
;
1351 // Structure is equal to db, insert record
1352 // If the shortname doesn't exist
1353 if (!$prerec = get_record('grade_outcomes','courseid',$dbrec->courseid
,'shortname',$dbrec->shortname
)) {
1354 $status = insert_record('grade_outcomes',$dbrec);
1357 //Increment counters
1360 if ($counter %
1 == 0) {
1361 if (!defined('RESTORE_SILENTLY')) {
1363 if ($counter %
20 == 0) {
1374 // Process grade items (grade_raw, grade_final, and grade_text)
1375 if ($itemscount && $continue) {
1376 if (!defined('RESTORE_SILENTLY')) {
1377 echo '<li>'.get_string('gradeitems','grades').'</li>';
1381 while ($counteritems < $itemscount) {
1383 //Fetch recordset_size records in each iteration
1384 $recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'",
1390 foreach ($recs as $rec) {
1391 //Get the full record from backup_ids
1392 $data = backup_getid($restore->backup_unique_code
,'grade_items',$rec->old_id
);
1395 //Now get completed xmlized object
1396 $info = $data->info
;
1397 //traverse_xmlize($info); //Debug
1398 //print_object ($GLOBALS['traverse_array']); //Debug
1399 //$GLOBALS['traverse_array']=""; //Debug
1401 $dbrec->courseid
= $restore->course_id
;
1403 if (!empty($info['GRADE_ITEM']['#']['CATEGORYID']['0']['#'])) {
1405 $category = backup_getid($restore->backup_unique_code
,'grade_categories',backup_todb($info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']));
1406 $dbrec->categoryid
= $category->new_id
;
1409 $dbrec->itemname
= backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#']);
1410 $dbrec->itemtype
= backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1411 $dbrec->itemmodule
= backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1412 /// this needs to point to either the new mod id
1413 /// or the category id
1414 $iteminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1416 // do not restore if this grade_item is a mod, and
1417 if ($dbrec->itemtype
== 'mod') {
1419 if (!restore_userdata_selected($restore, $dbrec->itemmodule
, $iteminstance)) {
1420 // module instance not selected when restored using granular
1426 // iteminstance should point to new mod
1428 $cm = backup_getid($restore->backup_unique_code
,'course_modules', $iteminstance);
1429 $dbrec->iteminstance
= $cm->new_id
;
1431 } else if ($dbrec->itemtype
== 'category') {
1432 // the item instance should point to the new grade category
1434 // only proceed if we are restoring all grade items
1436 $category = backup_getid($restore->backup_unique_code
,'grade_categories', $iteminstance);
1437 $dbrec->iteminstance
= $category->new_id
;
1439 // otherwise we can safely ignore this grade item and subsequent
1440 // grade_raws, grade_finals etc
1445 $dbrec->itemnumber
= backup_todb($info['GRADE_ITEM']['#']['ITEMNUMBER']['0']['#']);
1446 $dbrec->iteminfo
= backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#']);
1447 $dbrec->idnumber
= backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#']);
1448 $dbrec->calculation
= backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#']);
1449 $dbrec->grademax
= backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#']);
1450 $dbrec->grademin
= backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#']);
1451 /// needs to be restored first
1453 if ($info['GRADE_ITEM']['#']['SCALEID']['0']['#']) {
1454 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#']));
1455 $derec->scaleid
= $scale->new_id
;
1458 /// needs to be restored first
1459 $dbrec->outcomeid
= backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#']);
1460 $dbrec->gradepass
= backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#']);
1461 $dbrec->multfactor
= backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#']);
1462 $dbrec->plusfactor
= backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#']);
1463 $dbrec->hidden
= backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#']);
1464 $dbrec->locked
= backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#']);
1465 $dbrec->locktime
= backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#']);
1467 /// if thesse 5 all match then we know this item is already in db
1470 $itemex = get_record_sql('SELECT id,id FROM grade_items
1471 WHERE courseid = '.$dbrec->courseid.'
1472 AND itemtype = '.$dbrec->itemtype.'
1473 AND itemmodule = '.$dbrec->itemmodule.'
1474 AND iteminstance = '.$dbrec->iteminstance.'
1475 AND itemnumber = '.$dbrec->itemnumber);
1478 //Structure is equal to db, insert record
1479 $itemid = insert_record('grade_items',$dbrec);
1481 //Simply remap category
1482 $itemid = $itemex->id;
1486 // always insert, since modules restored to existing courses are always inserted
1488 // get the current sortorder, add 1 to it and use that
1490 if ($lastitem = get_record_sql("SELECT sortorder, id FROM {$CFG->prefix}grade_items
1491 WHERE courseid = $restore->course_id
1492 ORDER BY sortorder DESC ", true)) {
1494 // we just need the first one
1495 $dbrec->sortorder
= $lastitem->sortorder +
1;
1497 // this is the first grade_item
1498 $dbrec->sortorder
= 0;
1501 $itemid = insert_record('grade_items',$dbrec);
1503 /// now, restore grade_grades, grade_text
1504 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']) && ($grades = $info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'])) {
1505 //Iterate over items
1506 for($i = 0; $i < sizeof($grades); $i++
) {
1507 $ite_info = $grades[$i];
1508 //traverse_xmlize($ite_info);
1510 //print_object ($GLOBALS['traverse_array']); //Debug
1511 //$GLOBALS['traverse_array']=""; //Debug
1512 //Now build the GRADE_ITEM record structure
1513 $grade = new object();
1514 $grade->itemid
= $itemid;
1515 $user = backup_getid($restore->backup_unique_code
,"user", backup_todb($ite_info['#']['USERID']['0']['#']));
1516 $grade->userid
= $user->new_id
;
1517 $grade->rawgrade
= backup_todb($ite_info['#']['RAWGRADE']['0']['#']);
1518 $grade->rawgrademax
= backup_todb($ite_info['#']['RAWGRADEMAX']['0']['#']);
1519 $grade->rawgrademin
= backup_todb($ite_info['#']['RAWGRADEMIN']['0']['#']);
1520 // need to find scaleid
1521 if ($ite_info['#']['RAWSCALEID']['0']['#']) {
1522 $scale = backup_getid($restore->backup_unique_code
,"scale",backup_todb($ite_info['#']['RAWSCALEID']['0']['#']));
1523 $grade->rawscaleid
= $scale->new_id
;
1525 $grade->finalgrade
= backup_todb($ite_info['#']['FINALGRADE']['0']['#']);
1526 $grade->hidden
= backup_todb($ite_info['#']['HIDDEN']['0']['#']);
1527 $grade->locked
= backup_todb($ite_info['#']['LOCKED']['0']['#']);
1528 $grade->locktime
= backup_todb($ite_info['#']['LOCKTIME']['0']['#']);
1529 $grade->exported
= backup_todb($ite_info['#']['EXPORTED']['0']['#']);
1531 insert_record('grade_grades', $grade);
1534 if ($counter %
20 == 0) {
1535 if (!defined('RESTORE_SILENTLY')) {
1537 if ($counter %
400 == 0) {
1547 /// processing grade_grades_text
1548 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES_TEXT']['0']['#']) && ($texts = $info['GRADE_ITEM']['#']['GRADE_GRADES_TEXT']['0']['#']['GRADE_TEXT'])) {
1549 //Iterate over items
1550 for($i = 0; $i < sizeof($texts); $i++
) {
1551 $ite_info = $texts[$i];
1552 //traverse_xmlize($ite_info); //Debug
1553 //print_object ($GLOBALS['traverse_array']); //Debug
1554 //$GLOBALS['traverse_array']=""; //Debug
1555 $grade = backup_getid($restore->backup_unique_code
,"grade_grades", backup_todb($ite_info['#']['GRADEID']['0']['#']));
1556 $text->gradeid
= $grade->new_id
;
1557 $text->information
= backup_todb($ite_info['#']['INFORMATION']['0']['#']);
1558 $text->informationformat
= backup_todb($ite_info['#']['INFORMATIONFORMAT']['0']['#']);
1559 $text->feedback
= backup_todb($ite_info['#']['FEEDBACK']['0']['#']);
1560 $text->feedbackformat
= backup_todb($ite_info['#']['FEEDBACKFORMAT']['0']['#']);
1562 insert_record('grade_grades_text', $text);
1565 if ($counter %
20 == 0) {
1566 if (!defined('RESTORE_SILENTLY')) {
1568 if ($counter %
400 == 0) {
1577 $counteritems++
; // increment item count
1584 if (!defined('RESTORE_SILENTLY')) {
1591 //This function creates all the user, user_students, user_teachers
1592 //user_course_creators and user_admins from xml
1593 function restore_create_users($restore,$xml_file) {
1599 if (!file_exists($xml_file)) {
1604 //info will contain the old_id of every user
1605 //in backup_ids->info will be the real info (serialized)
1606 $info = restore_read_xml_users($restore,$xml_file);
1609 //Now, get evey user_id from $info and user data from $backup_ids
1610 //and create the necessary records (users, user_students, user_teachers
1611 //user_course_creators and user_admins
1612 if (!empty($info->users
)) {
1613 // Grab mnethosts keyed by wwwroot, to map to id
1614 $mnethosts = get_records('mnet_host', '', '',
1615 'wwwroot', 'wwwroot, id');
1617 $languages = get_list_of_languages();
1619 foreach ($info->users
as $userid) {
1620 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
1623 //Now, recode some languages (Moodle 1.5)
1624 if ($user->lang
== 'ma_nt') {
1625 $user->lang
= 'mi_nt';
1629 //If language does not exist here - use site default
1630 if (!array_key_exists($user->lang
, $languages)) {
1631 $user->lang
= $CFG->lang
;
1634 //Check if it's admin and coursecreator
1635 $is_admin = !empty($user->roles
['admin']);
1636 $is_coursecreator = !empty($user->roles
['coursecreator']);
1638 //Check if it's teacher and student
1639 $is_teacher = !empty($user->roles
['teacher']);
1640 $is_student = !empty($user->roles
['student']);
1642 //Check if it's needed
1643 $is_needed = !empty($user->roles
['needed']);
1645 //Calculate if it is a course user
1646 //Has role teacher or student or needed
1647 $is_course_user = ($is_teacher or $is_student or $is_needed);
1649 //Calculate mnethostid
1650 if (empty($user->mnethosturl
) ||
$user->mnethosturl
===$CFG->wwwroot
) {
1651 $user->mnethostid
= $CFG->mnet_localhost_id
;
1653 // fast url-to-id lookups
1654 if (isset($mnethosts[$user->mnethosturl
])) {
1655 $user->mnethostid
= $mnethosts[$user->mnethosturl
]->id
;
1657 // should not happen, as we check in restore_chech.php
1658 // but handle the error if it does
1659 error("This backup file contains external Moodle Network Hosts that are not configured locally.");
1662 unset($user->mnethosturl
);
1664 //To store new ids created
1666 //check if it exists (by username) and get its id
1667 $user_exists = true;
1668 $user_data = get_record("user","username",addslashes($user->username
),
1669 'mnethostid', $user->mnethostid
);
1671 $user_exists = false;
1673 $newid = $user_data->id
;
1675 //Flags to see if we have to create the user, roles and preferences
1676 $create_user = true;
1677 $create_roles = true;
1678 $create_preferences = true;
1680 //If we are restoring course users and it isn't a course user
1681 if ($restore->users
== 1 and !$is_course_user) {
1682 //If only restoring course_users and user isn't a course_user, inform to $backup_ids
1683 $status = backup_putid($restore->backup_unique_code
,"user",$userid,null,'notincourse');
1684 $create_user = false;
1685 $create_roles = false;
1686 $create_preferences = false;
1689 if ($user_exists and $create_user) {
1690 //If user exists mark its newid in backup_ids (the same than old)
1691 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,'exists');
1692 $create_user = false;
1695 //Here, if create_user, do it
1697 //Unset the id because it's going to be inserted with a new one
1699 //We addslashes to necessary fields
1700 $user->username
= addslashes($user->username
);
1701 $user->firstname
= addslashes($user->firstname
);
1702 $user->lastname
= addslashes($user->lastname
);
1703 $user->email
= addslashes($user->email
);
1704 $user->institution
= addslashes($user->institution
);
1705 $user->department
= addslashes($user->department
);
1706 $user->address
= addslashes($user->address
);
1707 $user->city
= addslashes($user->city
);
1708 $user->url
= addslashes($user->url
);
1709 $user->description
= restore_decode_absolute_links(addslashes($user->description
));
1711 //We need to analyse the AUTH field to recode it:
1712 // - if the field isn't set, we are in a pre 1.4 backup and we'll
1715 if (empty($user->auth
)) {
1716 if ($CFG->registerauth
== 'email') {
1717 $user->auth
= 'email';
1719 $user->auth
= 'manual';
1723 //We need to process the POLICYAGREED field to recalculate it:
1724 // - if the destination site is different (by wwwroot) reset it.
1725 // - if the destination site is the same (by wwwroot), leave it unmodified
1727 if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
1728 $user->policyagreed
= 0;
1730 //Nothing to do, we are in the same server
1733 //Check if the theme exists in destination server
1734 $themes = get_list_of_themes();
1735 if (!in_array($user->theme
, $themes)) {
1739 //We are going to create the user
1740 //The structure is exactly as we need
1741 $newid = insert_record ("user",$user);
1743 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,"new");
1746 //Here, if create_roles, do it as necessary
1747 if ($create_roles) {
1748 //Get the newid and current info from backup_ids
1749 $data = backup_getid($restore->backup_unique_code
,"user",$userid);
1750 $newid = $data->new_id
;
1751 $currinfo = $data->info
.",";
1753 //Now, depending of the role, create records in user_studentes and user_teacher
1754 //and/or mark it in backup_ids
1757 //If the record (user_admins) doesn't exists
1758 //Only put status in backup_ids
1759 $currinfo = $currinfo."admin,";
1760 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1762 if ($is_coursecreator) {
1763 //If the record (user_coursecreators) doesn't exists
1764 //Only put status in backup_ids
1765 $currinfo = $currinfo."coursecreator,";
1766 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1769 //Only put status in backup_ids
1770 $currinfo = $currinfo."needed,";
1771 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1774 //If the record (teacher) doesn't exists
1775 //Put status in backup_ids
1776 $currinfo = $currinfo."teacher,";
1777 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1778 //Set course and user
1779 $user->roles
['teacher']->course
= $restore->course_id
;
1780 $user->roles
['teacher']->userid
= $newid;
1782 //Need to analyse the enrol field
1783 // - if it isn't set, set it to $CFG->enrol
1784 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
1785 // - if we are in the same server (by wwwroot), maintain it unmodified.
1786 if (empty($user->roles
['teacher']->enrol
)) {
1787 $user->roles
['teacher']->enrol
= $CFG->enrol
;
1788 } else if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
1789 $user->roles
['teacher']->enrol
= $CFG->enrol
;
1791 //Nothing to do. Leave it unmodified
1794 $rolesmapping = $restore->rolesmapping
;
1795 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
1796 if ($user->roles
['teacher']->editall
) {
1797 role_assign($rolesmapping['defaultteacheredit'],
1801 $user->roles
['teacher']->timestart
,
1802 $user->roles
['teacher']->timeend
,
1804 $user->roles
['teacher']->enrol
);
1808 // non editting teacher
1809 role_assign($rolesmapping['defaultteacher'],
1813 $user->roles
['teacher']->timestart
,
1814 $user->roles
['teacher']->timeend
,
1816 $user->roles
['teacher']->enrol
);
1821 //Put status in backup_ids
1822 $currinfo = $currinfo."student,";
1823 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1824 //Set course and user
1825 $user->roles
['student']->course
= $restore->course_id
;
1826 $user->roles
['student']->userid
= $newid;
1828 //Need to analyse the enrol field
1829 // - if it isn't set, set it to $CFG->enrol
1830 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
1831 // - if we are in the same server (by wwwroot), maintain it unmodified.
1832 if (empty($user->roles
['student']->enrol
)) {
1833 $user->roles
['student']->enrol
= $CFG->enrol
;
1834 } else if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
1835 $user->roles
['student']->enrol
= $CFG->enrol
;
1837 //Nothing to do. Leave it unmodified
1839 $rolesmapping = $restore->rolesmapping
;
1840 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
1842 role_assign($rolesmapping['defaultstudent'],
1846 $user->roles
['student']->timestart
,
1847 $user->roles
['student']->timeend
,
1849 $user->roles
['student']->enrol
);
1852 if (!$is_course_user) {
1853 //If the record (user) doesn't exists
1854 if (!record_exists("user","id",$newid)) {
1855 //Put status in backup_ids
1856 $currinfo = $currinfo."user,";
1857 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1862 //Here, if create_preferences, do it as necessary
1863 if ($create_preferences) {
1864 //echo "Checking for preferences of user ".$user->username."<br />"; //Debug
1865 //Get user new id from backup_ids
1866 $data = backup_getid($restore->backup_unique_code
,"user",$userid);
1867 $newid = $data->new_id
;
1868 if (isset($user->user_preferences
)) {
1869 //echo "Preferences exist in backup file<br />"; //Debug
1870 foreach($user->user_preferences
as $user_preference) {
1871 //echo $user_preference->name." = ".$user_preference->value."<br />"; //Debug
1872 //We check if that user_preference exists in DB
1873 if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name
)) {
1874 //echo "Creating it<br />"; //Debug
1875 //Prepare the record and insert it
1876 $user_preference->userid
= $newid;
1877 $status = insert_record("user_preferences",$user_preference);
1888 //This function creates all the structures messages and contacts
1889 function restore_create_messages($restore,$xml_file) {
1895 if (!file_exists($xml_file)) {
1900 //info will contain the id and name of every table
1901 //(message, message_read and message_contacts)
1902 //in backup_ids->info will be the real info (serialized)
1903 $info = restore_read_xml_messages($restore,$xml_file);
1905 //If we have info, then process messages & contacts
1907 //Count how many we have
1908 $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message');
1909 $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message_read');
1910 $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message_contacts');
1911 if ($unreadcount ||
$readcount ||
$contactcount) {
1913 if (!defined('RESTORE_SILENTLY')) {
1916 //Number of records to get in every chunk
1917 $recordset_size = 4;
1921 if (!defined('RESTORE_SILENTLY')) {
1922 echo '<li>'.get_string('unreadmessages','message').'</li>';
1925 while ($counter < $unreadcount) {
1926 //Fetch recordset_size records in each iteration
1927 $recs = get_records_select("backup_ids","table_name = 'message' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
1929 foreach ($recs as $rec) {
1930 //Get the full record from backup_ids
1931 $data = backup_getid($restore->backup_unique_code
,"message",$rec->old_id
);
1933 //Now get completed xmlized object
1934 $info = $data->info
;
1935 //traverse_xmlize($info); //Debug
1936 //print_object ($GLOBALS['traverse_array']); //Debug
1937 //$GLOBALS['traverse_array']=""; //Debug
1938 //Now build the MESSAGE record structure
1939 $dbrec->useridfrom
= backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
1940 $dbrec->useridto
= backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
1941 $dbrec->message
= backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
1942 $dbrec->format
= backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
1943 $dbrec->timecreated
= backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
1944 $dbrec->messagetype
= backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
1945 //We have to recode the useridfrom field
1946 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridfrom
);
1948 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
1949 $dbrec->useridfrom
= $user->new_id
;
1951 //We have to recode the useridto field
1952 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridto
);
1954 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
1955 $dbrec->useridto
= $user->new_id
;
1957 //Check if the record doesn't exist in DB!
1958 $exist = get_record('message','useridfrom',$dbrec->useridfrom
,
1959 'useridto', $dbrec->useridto
,
1960 'timecreated',$dbrec->timecreated
);
1963 $status = insert_record('message',$dbrec);
1965 //Duplicate. Do nothing
1970 if ($counter %
10 == 0) {
1971 if (!defined('RESTORE_SILENTLY')) {
1973 if ($counter %
200 == 0) {
1986 if (!defined('RESTORE_SILENTLY')) {
1987 echo '<li>'.get_string('readmessages','message').'</li>';
1990 while ($counter < $readcount) {
1991 //Fetch recordset_size records in each iteration
1992 $recs = get_records_select("backup_ids","table_name = 'message_read' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
1994 foreach ($recs as $rec) {
1995 //Get the full record from backup_ids
1996 $data = backup_getid($restore->backup_unique_code
,"message_read",$rec->old_id
);
1998 //Now get completed xmlized object
1999 $info = $data->info
;
2000 //traverse_xmlize($info); //Debug
2001 //print_object ($GLOBALS['traverse_array']); //Debug
2002 //$GLOBALS['traverse_array']=""; //Debug
2003 //Now build the MESSAGE_READ record structure
2004 $dbrec->useridfrom
= backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2005 $dbrec->useridto
= backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2006 $dbrec->message
= backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2007 $dbrec->format
= backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2008 $dbrec->timecreated
= backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2009 $dbrec->messagetype
= backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2010 $dbrec->timeread
= backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
2011 $dbrec->mailed
= backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
2012 //We have to recode the useridfrom field
2013 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridfrom
);
2015 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2016 $dbrec->useridfrom
= $user->new_id
;
2018 //We have to recode the useridto field
2019 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridto
);
2021 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2022 $dbrec->useridto
= $user->new_id
;
2024 //Check if the record doesn't exist in DB!
2025 $exist = get_record('message_read','useridfrom',$dbrec->useridfrom
,
2026 'useridto', $dbrec->useridto
,
2027 'timecreated',$dbrec->timecreated
);
2030 $status = insert_record('message_read',$dbrec);
2032 //Duplicate. Do nothing
2037 if ($counter %
10 == 0) {
2038 if (!defined('RESTORE_SILENTLY')) {
2040 if ($counter %
200 == 0) {
2052 if ($contactcount) {
2053 if (!defined('RESTORE_SILENTLY')) {
2054 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
2057 while ($counter < $contactcount) {
2058 //Fetch recordset_size records in each iteration
2059 $recs = get_records_select("backup_ids","table_name = 'message_contacts' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
2061 foreach ($recs as $rec) {
2062 //Get the full record from backup_ids
2063 $data = backup_getid($restore->backup_unique_code
,"message_contacts",$rec->old_id
);
2065 //Now get completed xmlized object
2066 $info = $data->info
;
2067 //traverse_xmlize($info); //Debug
2068 //print_object ($GLOBALS['traverse_array']); //Debug
2069 //$GLOBALS['traverse_array']=""; //Debug
2070 //Now build the MESSAGE_CONTACTS record structure
2071 $dbrec->userid
= backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
2072 $dbrec->contactid
= backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
2073 $dbrec->blocked
= backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
2074 //We have to recode the userid field
2075 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->userid
);
2077 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
2078 $dbrec->userid
= $user->new_id
;
2080 //We have to recode the contactid field
2081 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->contactid
);
2083 //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />"; //Debug
2084 $dbrec->contactid
= $user->new_id
;
2086 //Check if the record doesn't exist in DB!
2087 $exist = get_record('message_contacts','userid',$dbrec->userid
,
2088 'contactid', $dbrec->contactid
);
2091 $status = insert_record('message_contacts',$dbrec);
2093 //Duplicate. Do nothing
2098 if ($counter %
10 == 0) {
2099 if (!defined('RESTORE_SILENTLY')) {
2101 if ($counter %
200 == 0) {
2111 if (!defined('RESTORE_SILENTLY')) {
2122 //This function creates all the categories and questions
2124 function restore_create_questions($restore,$xml_file) {
2130 if (!file_exists($xml_file)) {
2135 //info will contain the old_id of every category
2136 //in backup_ids->info will be the real info (serialized)
2137 $info = restore_read_xml_questions($restore,$xml_file);
2139 //Now, if we have anything in info, we have to restore that
2140 //categories/questions
2142 if ($info !== true) {
2143 //Iterate over each category
2144 foreach ($info as $category) {
2145 //Skip empty categories (some backups can contain them)
2146 if (!empty($category->id
)) {
2147 $status = restore_question_categories($category,$restore);
2151 //Now we have to recode the parent field of each restored category
2152 $categories = get_records_sql("SELECT old_id, new_id
2153 FROM {$CFG->prefix}backup_ids
2154 WHERE backup_code = $restore->backup_unique_code AND
2155 table_name = 'question_categories'");
2157 foreach ($categories as $category) {
2158 $restoredcategory = get_record('question_categories','id',$category->new_id
);
2159 $restoredcategory = addslashes_object($restoredcategory);
2160 if ($restoredcategory->parent
!= 0) {
2161 $idcat = backup_getid($restore->backup_unique_code
,'question_categories',$restoredcategory->parent
);
2162 if ($idcat->new_id
) {
2163 $restoredcategory->parent
= $idcat->new_id
;
2165 $restoredcategory->parent
= 0;
2167 update_record('question_categories', $restoredcategory);
2178 //This function creates all the scales
2179 function restore_create_scales($restore,$xml_file) {
2185 if (!file_exists($xml_file)) {
2190 //scales will contain the old_id of every scale
2191 //in backup_ids->info will be the real info (serialized)
2192 $scales = restore_read_xml_scales($restore,$xml_file);
2194 //Now, if we have anything in scales, we have to restore that
2197 //Get admin->id for later use
2198 $admin = get_admin();
2199 $adminid = $admin->id
;
2200 if ($scales !== true) {
2201 //Iterate over each scale
2202 foreach ($scales as $scale) {
2203 //Get record from backup_ids
2204 $data = backup_getid($restore->backup_unique_code
,"scale",$scale->id
);
2206 $create_scale = false;
2209 //Now get completed xmlized object
2210 $info = $data->info
;
2211 //traverse_xmlize($info); //Debug
2212 //print_object ($GLOBALS['traverse_array']); //Debug
2213 //$GLOBALS['traverse_array']=""; //Debug
2215 //Now build the SCALE record structure
2216 $sca->courseid
= backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
2217 $sca->userid
= backup_todb($info['SCALE']['#']['USERID']['0']['#']);
2218 $sca->name
= backup_todb($info['SCALE']['#']['NAME']['0']['#']);
2219 $sca->scale
= backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
2220 $sca->description
= backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
2221 $sca->timemodified
= backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);
2223 //Now search if that scale exists (by scale field) in course 0 (Standar scale)
2224 //or in restore->course_id course (Personal scale)
2225 if ($sca->courseid
== 0) {
2226 $course_to_search = 0;
2228 $course_to_search = $restore->course_id
;
2230 $sca_db = get_record("scale","scale",$sca->scale
,"courseid",$course_to_search);
2231 //If it doesn't exist, create
2233 $create_scale = true;
2235 //If we must create the scale
2236 if ($create_scale) {
2237 //Me must recode the courseid if it's <> 0 (common scale)
2238 if ($sca->courseid
!= 0) {
2239 $sca->courseid
= $restore->course_id
;
2241 //We must recode the userid
2242 $user = backup_getid($restore->backup_unique_code
,"user",$sca->userid
);
2244 $sca->userid
= $user->new_id
;
2246 //Assign it to admin
2247 $sca->userid
= $adminid;
2249 //The structure is equal to the db, so insert the scale
2250 $newid = insert_record ("scale",$sca);
2252 //get current scale id
2253 $newid = $sca_db->id
;
2256 //We have the newid, update backup_ids
2257 backup_putid($restore->backup_unique_code
,"scale",
2258 $scale->id
, $newid);
2269 //This function creates all the groups
2270 function restore_create_groups($restore,$xml_file) {
2277 if (!file_exists($xml_file)) {
2282 //groups will contain the old_id of every group
2283 //in backup_ids->info will be the real info (serialized)
2284 $groups = restore_read_xml_groups($restore,$xml_file);
2286 //Now, if we have anything in groups, we have to restore that
2289 if ($groups !== true) {
2290 //Iterate over each group
2291 foreach ($groups as $group) {
2292 //Get record from backup_ids
2293 $data = backup_getid($restore->backup_unique_code
,"groups",$group->id
);
2295 $create_group = false;
2298 //Now get completed xmlized object
2299 $info = $data->info
;
2300 //traverse_xmlize($info); //Debug
2301 //print_object ($GLOBALS['traverse_array']); //Debug
2302 //$GLOBALS['traverse_array']=""; //Debug
2303 //Now build the GROUP record structure
2304 $gro = new Object();
2305 ///$gro->courseid = backup_todb($info['GROUP']['#']['COURSEID']['0']['#']);
2306 $gro->name
= backup_todb($info['GROUP']['#']['NAME']['0']['#']);
2307 $gro->description
= backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
2308 if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) {
2309 $gro->enrolmentkey
= backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']);
2310 } else { //if (! isset($gro->enrolment)) {
2311 $gro->enrolmentkey
= backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
2313 $gro->lang
= backup_todb($info['GROUP']['#']['LANG']['0']['#']);
2314 $gro->theme
= backup_todb($info['GROUP']['#']['THEME']['0']['#']);
2315 $gro->picture
= backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
2316 $gro->hidepicture
= backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
2317 $gro->timecreated
= backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
2318 $gro->timemodified
= backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
2320 //Now search if that group exists (by name and description field) in
2321 //restore->course_id course
2322 $gro_db = groups_group_matches($restore->course_id
, $gro->name
, $gro->description
);
2323 //If it doesn't exist, create
2325 $create_group = true;
2327 //If we must create the group
2328 if ($create_group) {
2329 //Me must recode the courseid to the restore->course_id
2330 $gro->courseid
= $restore->course_id
;
2332 //Check if the theme exists in destination server
2333 $themes = get_list_of_themes();
2334 if (!in_array($gro->theme
, $themes)) {
2338 //The structure is equal to the db, so insert the group
2339 $newid = groups_restore_group($restore->course_id
, $gro);
2341 //get current group id
2342 $newid = $gro_db->id
;
2345 //We have the newid, update backup_ids
2346 backup_putid($restore->backup_unique_code
,"groups",
2347 $group->id
, $newid);
2349 //Now restore members in the groups_members, only if
2350 //users are included
2351 if ($restore->users
!= 2) {
2352 $status2 = restore_create_groups_members($newid,$info,$restore);
2356 //Now, restore group_files
2357 if ($status && $status2) {
2358 $status2 = restore_group_files($restore);
2364 return ($status && $status2);
2367 //This function restores the groups_members
2368 function restore_create_groups_members($group_id,$info,$restore) {
2374 if (! isset($info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'])) {
2375 //OK, some groups have no members.
2378 //Get the members array
2379 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
2381 //Iterate over members
2382 for($i = 0; $i < sizeof($members); $i++
) {
2383 $mem_info = $members[$i];
2384 //traverse_xmlize($mem_info); //Debug
2385 //print_object ($GLOBALS['traverse_array']); //Debug
2386 //$GLOBALS['traverse_array']=""; //Debug
2388 //Now, build the GROUPS_MEMBERS record structure
2389 $group_member = new Object();
2390 $group_member->groupid
= $group_id;
2391 $group_member->userid
= backup_todb($mem_info['#']['USERID']['0']['#']);
2392 $group_member->timeadded
= backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
2394 //We have to recode the userid field
2395 $user = backup_getid($restore->backup_unique_code
,"user",$group_member->userid
);
2397 $group_member->userid
= $user->new_id
;
2400 //The structure is equal to the db, so insert the groups_members
2401 $newid = groups_restore_member($group_member);
2403 if (($i+
1) %
50 == 0) {
2404 if (!defined('RESTORE_SILENTLY')) {
2406 if (($i+
1) %
1000 == 0) {
2421 //This function creates all the groupings
2422 function restore_create_groupings($restore,$xml_file) {
2429 if (!file_exists($xml_file)) {
2434 //groupings will contain the old_id of every group
2435 //in backup_ids->info will be the real info (serialized)
2436 $groupings = restore_read_xml_groupings($restore,$xml_file);
2438 //Now, if we have anything in groupings, we have to restore that grouping
2440 if ($groupings !== true) {
2441 //Iterate over each group
2442 foreach ($groupings as $grouping) {
2443 //Get record from backup_ids
2444 $data = backup_getid($restore->backup_unique_code
,"groupings",$grouping->id
);
2446 $create_grouping = false;
2449 //Now get completed xmlized object
2450 $info = $data->info
;
2451 //Now build the GROUPING record structure
2452 $gro = new Object();
2453 ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']);
2454 $gro->name
= backup_todb($info['GROUPING']['#']['NAME']['0']['#']);
2455 $gro->description
= backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']);
2456 $gro->timecreated
= backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']);
2458 //Now search if that group exists (by name and description field) in
2459 //restore->course_id course
2460 $gro_db = groups_grouping_matches($restore->course_id
, $gro->name
, $gro->description
);
2461 //If it doesn't exist, create
2463 $create_grouping = true;
2465 //If we must create the group
2466 if ($create_grouping) {
2468 //The structure is equal to the db, so insert the grouping TODO: RESTORE.
2469 $newid = groups_create_grouping($restore->course_id
, $gro);
2471 //get current group id
2472 $newid = $gro_db->id
;
2475 //We have the newid, update backup_ids
2476 backup_putid($restore->backup_unique_code
,"groupings",
2477 $grouping->id
, $newid);
2479 //Now restore links from groupings to groups
2480 $status2 = restore_create_groupings_groups($newid,$info,$restore);
2483 //(Now, restore grouping_files)
2488 return ($status && $status2);
2491 //This function restores the groups_members
2492 function restore_create_groupings_groups($grouping_id,$info,$restore) {
2498 //Get the members array
2499 $members = $info['GROUPING']['#']['GROUPS']['0']['#']['GROUP'];
2501 //Iterate over members
2502 for($i = 0; $i < sizeof($members); $i++
) {
2503 $mem_info = $members[$i];
2504 //Now, build the GROUPINGS_GROUPS record structure
2505 $gro_member = new Object();
2506 $gro_member->groupingid
= $grouping_id;
2507 $gro_member->groupid
= backup_todb($mem_info['#']['GROUPID']['0']['#']);
2508 $gro_member->timeadded
= backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
2510 //We have to recode the userid field
2511 ///$user = backup_getid($restore->backup_unique_code,"user",$group_member->userid);
2512 $group = backup_getid($restore->backup_unique_code
,"group",$gro_member->groupid
);
2514 $gro_member->groupid
= $group->new_id
;
2517 //The structure is equal to the db, so link the groups to the groupings. TODO: RESTORE.
2518 $newid = groups_add_group_to_grouping($gro_member->groupid
, $gro_member->groupingid
);
2520 if (($i+
1) %
50 == 0) {
2521 if (!defined('RESTORE_SILENTLY')) {
2523 if (($i+
1) %
1000 == 0) {
2538 //This function creates all the course events
2539 function restore_create_events($restore,$xml_file) {
2545 if (!file_exists($xml_file)) {
2550 //events will contain the old_id of every event
2551 //in backup_ids->info will be the real info (serialized)
2552 $events = restore_read_xml_events($restore,$xml_file);
2555 //Get admin->id for later use
2556 $admin = get_admin();
2557 $adminid = $admin->id
;
2559 //Now, if we have anything in events, we have to restore that
2562 if ($events !== true) {
2563 //Iterate over each event
2564 foreach ($events as $event) {
2565 //Get record from backup_ids
2566 $data = backup_getid($restore->backup_unique_code
,"event",$event->id
);
2568 $create_event = false;
2571 //Now get completed xmlized object
2572 $info = $data->info
;
2573 //traverse_xmlize($info); //Debug
2574 //print_object ($GLOBALS['traverse_array']); //Debug
2575 //$GLOBALS['traverse_array']=""; //Debug
2577 //if necessary, write to restorelog and adjust date/time fields
2578 if ($restore->course_startdateoffset
) {
2579 restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
2582 //Now build the EVENT record structure
2583 $eve->name
= backup_todb($info['EVENT']['#']['NAME']['0']['#']);
2584 $eve->description
= backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
2585 $eve->format
= backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
2586 $eve->courseid
= $restore->course_id
;
2587 $eve->groupid
= backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
2588 $eve->userid
= backup_todb($info['EVENT']['#']['USERID']['0']['#']);
2589 $eve->repeatid
= backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
2590 $eve->modulename
= "";
2592 $eve->eventtype
= backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
2593 $eve->timestart
= backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
2594 $eve->timeduration
= backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
2595 $eve->visible
= backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
2596 $eve->timemodified
= backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
2598 //Now search if that event exists (by name, description, timestart fields) in
2599 //restore->course_id course
2600 $eve_db = get_record_select("event",
2601 "courseid={$eve->courseid} AND name='{$eve->name}' AND description='{$eve->description}' AND timestart=$eve->timestart");
2602 //If it doesn't exist, create
2604 $create_event = true;
2606 //If we must create the event
2607 if ($create_event) {
2609 //We must recode the userid
2610 $user = backup_getid($restore->backup_unique_code
,"user",$eve->userid
);
2612 $eve->userid
= $user->new_id
;
2614 //Assign it to admin
2615 $eve->userid
= $adminid;
2618 //We must recode the repeatid if the event has it
2619 if (!empty($eve->repeatid
)) {
2620 $repeat_rec = backup_getid($restore->backup_unique_code
,"event_repeatid",$eve->repeatid
);
2621 if ($repeat_rec) { //Exists, so use it...
2622 $eve->repeatid
= $repeat_rec->new_id
;
2623 } else { //Doesn't exists, calculate the next and save it
2624 $oldrepeatid = $eve->repeatid
;
2625 $max_rec = get_record_sql('SELECT 1, MAX(repeatid) AS repeatid FROM '.$CFG->prefix
.'event');
2626 $eve->repeatid
= empty($max_rec) ?
1 : $max_rec->repeatid +
1;
2627 backup_putid($restore->backup_unique_code
,"event_repeatid", $oldrepeatid, $eve->repeatid
);
2631 //We have to recode the groupid field
2632 $group = backup_getid($restore->backup_unique_code
,"groups",$eve->groupid
);
2634 $eve->groupid
= $group->new_id
;
2636 //Assign it to group 0
2640 //The structure is equal to the db, so insert the event
2641 $newid = insert_record ("event",$eve);
2643 //get current event id
2644 $newid = $eve_db->id
;
2647 //We have the newid, update backup_ids
2648 backup_putid($restore->backup_unique_code
,"event",
2649 $event->id
, $newid);
2660 //This function decode things to make restore multi-site fully functional
2661 //It does this conversions:
2662 // - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
2663 // |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
2665 //Note: Inter-activities linking is being implemented as a final
2666 //step in the restore execution, because we need to have it
2667 //finished to know all the oldid, newid equivaleces
2668 function restore_decode_absolute_links($content) {
2670 global $CFG,$restore;
2672 //Now decode wwwroot and file.php calls
2673 $search = array ("$@FILEPHP@$");
2675 //Check for the status of the slasharguments config variable
2676 $slash = $CFG->slasharguments
;
2678 //Build the replace string as needed
2680 $replace = array ($CFG->wwwroot
."/file.php/".$restore->course_id
);
2682 $replace = array ($CFG->wwwroot
."/file.php?file=/".$restore->course_id
);
2685 $result = str_replace($search,$replace,$content);
2687 if ($result != $content && debugging()) { //Debug
2688 if (!defined('RESTORE_SILENTLY')) {
2689 echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />'; //Debug
2696 //This function restores the userfiles from the temp (user_files) directory to the
2697 //dataroot/users directory
2698 function restore_user_files($restore) {
2706 //First, we check to "users" exists and create is as necessary
2708 $dest_dir = $CFG->dataroot
."/users";
2709 $status = check_dir_exists($dest_dir,true);
2711 //Now, we iterate over "user_files" records to check if that user dir must be
2712 //copied (and renamed) to the "users" dir.
2713 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/user_files";
2714 //Check if directory exists
2715 if (is_dir($rootdir)) {
2716 $list = list_directories ($rootdir);
2720 foreach ($list as $dir) {
2721 //Look for dir like username in backup_ids
2722 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code
,
2723 "table_name","user",
2725 //If thar user exists in backup_ids
2727 //Only it user has been created now
2728 //or if it existed previously, but he hasn't image (see bug 1123)
2729 if ((strpos($data->info
,"new") !== false) or
2730 (!check_dir_exists($dest_dir."/".$data->new_id
,false))) {
2731 //Copy the old_dir to its new location (and name) !!
2732 //Only if destination doesn't exists
2733 if (!file_exists($dest_dir."/".$data->new_id
)) {
2734 $status = backup_copy_file($rootdir."/".$dir,
2735 $dest_dir."/".$data->new_id
,true);
2739 if ($counter %
2 == 0) {
2740 if (!defined('RESTORE_SILENTLY')) {
2742 if ($counter %
40 == 0) {
2753 //If status is ok and whe have dirs created, returns counter to inform
2754 if ($status and $counter) {
2761 //This function restores the groupfiles from the temp (group_files) directory to the
2762 //dataroot/groups directory
2763 function restore_group_files($restore) {
2771 //First, we check to "groups" exists and create is as necessary
2773 $dest_dir = $CFG->dataroot
.'/groups';
2774 $status = check_dir_exists($dest_dir,true);
2776 //Now, we iterate over "group_files" records to check if that user dir must be
2777 //copied (and renamed) to the "groups" dir.
2778 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/group_files";
2779 //Check if directory exists
2780 if (is_dir($rootdir)) {
2781 $list = list_directories ($rootdir);
2785 foreach ($list as $dir) {
2786 //Look for dir like groupid in backup_ids
2787 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code
,
2788 "table_name","groups",
2790 //If that group exists in backup_ids
2792 if (!file_exists($dest_dir."/".$data->new_id
)) {
2793 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id
,true);
2797 if ($counter %
2 == 0) {
2798 if (!defined('RESTORE_SILENTLY')) {
2800 if ($counter %
40 == 0) {
2810 //If status is ok and whe have dirs created, returns counter to inform
2811 if ($status and $counter) {
2818 //This function restores the course files from the temp (course_files) directory to the
2819 //dataroot/course_id directory
2820 function restore_course_files($restore) {
2828 //First, we check to "course_id" exists and create is as necessary
2830 $dest_dir = $CFG->dataroot
."/".$restore->course_id
;
2831 $status = check_dir_exists($dest_dir,true);
2833 //Now, we iterate over "course_files" records to check if that file/dir must be
2834 //copied to the "dest_dir" dir.
2835 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/course_files";
2836 //Check if directory exists
2837 if (is_dir($rootdir)) {
2838 $list = list_directories_and_files ($rootdir);
2842 foreach ($list as $dir) {
2843 //Copy the dir to its new location
2844 //Only if destination file/dir doesn exists
2845 if (!file_exists($dest_dir."/".$dir)) {
2846 $status = backup_copy_file($rootdir."/".$dir,
2847 $dest_dir."/".$dir,true);
2851 if ($counter %
2 == 0) {
2852 if (!defined('RESTORE_SILENTLY')) {
2854 if ($counter %
40 == 0) {
2863 //If status is ok and whe have dirs created, returns counter to inform
2864 if ($status and $counter) {
2872 //This function creates all the structures for every module in backup file
2873 //Depending what has been selected.
2874 function restore_create_modules($restore,$xml_file) {
2879 if (!file_exists($xml_file)) {
2884 //info will contain the id and modtype of every module
2885 //in backup_ids->info will be the real info (serialized)
2886 $info = restore_read_xml_modules($restore,$xml_file);
2888 //Now, if we have anything in info, we have to restore that mods
2889 //from backup_ids (calling every mod restore function)
2891 if ($info !== true) {
2892 if (!defined('RESTORE_SILENTLY')) {
2895 //Iterate over each module
2896 foreach ($info as $mod) {
2897 if (empty($restore->mods
[$mod->modtype
]->granular
) // We don't care about per instance, i.e. restore all instances.
2898 ||
(array_key_exists($mod->id
,$restore->mods
[$mod->modtype
]->instances
)
2899 && !empty($restore->mods
[$mod->modtype
]->instances
[$mod->id
]->restore
))) {
2900 $modrestore = $mod->modtype
."_restore_mods";
2901 if (function_exists($modrestore)) { //Debug
2902 $status = $status and $modrestore($mod,$restore); //bit operator & not reliable here!
2904 //Something was wrong. Function should exist.
2909 if (!defined('RESTORE_SILENTLY')) {
2919 //This function creates all the structures for every log in backup file
2920 //Depending what has been selected.
2921 function restore_create_logs($restore,$xml_file) {
2925 //Number of records to get in every chunk
2926 $recordset_size = 4;
2927 //Counter, points to current record
2929 //To count all the recods to restore
2934 if (!file_exists($xml_file)) {
2939 //count_logs will contain the number of logs entries to process
2940 //in backup_ids->info will be the real info (serialized)
2941 $count_logs = restore_read_xml_logs($restore,$xml_file);
2944 //Now, if we have records in count_logs, we have to restore that logs
2945 //from backup_ids. This piece of code makes calls to:
2946 // - restore_log_course() if it's a course log
2947 // - restore_log_user() if it's a user log
2948 // - restore_log_module() if it's a module log.
2949 //And all is segmented in chunks to allow large recordsets to be restored !!
2950 if ($count_logs > 0) {
2951 while ($counter < $count_logs) {
2952 //Get a chunk of records
2953 //Take old_id twice to avoid adodb limitation
2954 $logs = get_records_select("backup_ids","table_name = 'log' AND backup_code = '$restore->backup_unique_code'","old_id","old_id,old_id",$counter,$recordset_size);
2958 foreach ($logs as $log) {
2959 //Get the full record from backup_ids
2960 $data = backup_getid($restore->backup_unique_code
,"log",$log->old_id
);
2962 //Now get completed xmlized object
2963 $info = $data->info
;
2964 //traverse_xmlize($info); //Debug
2965 //print_object ($GLOBALS['traverse_array']); //Debug
2966 //$GLOBALS['traverse_array']=""; //Debug
2967 //Now build the LOG record structure
2968 $dblog->time
= backup_todb($info['LOG']['#']['TIME']['0']['#']);
2969 $dblog->userid
= backup_todb($info['LOG']['#']['USERID']['0']['#']);
2970 $dblog->ip
= backup_todb($info['LOG']['#']['IP']['0']['#']);
2971 $dblog->course
= $restore->course_id
;
2972 $dblog->module
= backup_todb($info['LOG']['#']['MODULE']['0']['#']);
2973 $dblog->cmid
= backup_todb($info['LOG']['#']['CMID']['0']['#']);
2974 $dblog->action
= backup_todb($info['LOG']['#']['ACTION']['0']['#']);
2975 $dblog->url
= backup_todb($info['LOG']['#']['URL']['0']['#']);
2976 $dblog->info
= backup_todb($info['LOG']['#']['INFO']['0']['#']);
2977 //We have to recode the userid field
2978 $user = backup_getid($restore->backup_unique_code
,"user",$dblog->userid
);
2980 //echo "User ".$dblog->userid." to user ".$user->new_id."<br />"; //Debug
2981 $dblog->userid
= $user->new_id
;
2983 //We have to recode the cmid field (if module isn't "course" or "user")
2984 if ($dblog->module
!= "course" and $dblog->module
!= "user") {
2985 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$dblog->cmid
);
2987 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
2988 $dblog->cmid
= $cm->new_id
;
2993 //print_object ($dblog); //Debug
2994 //Now, we redirect to the needed function to make all the work
2995 if ($dblog->module
== "course") {
2996 //It's a course log,
2997 $stat = restore_log_course($restore,$dblog);
2998 } elseif ($dblog->module
== "user") {
3000 $stat = restore_log_user($restore,$dblog);
3002 //It's a module log,
3003 $stat = restore_log_module($restore,$dblog);
3009 if ($counter %
10 == 0) {
3010 if (!defined('RESTORE_SILENTLY')) {
3012 if ($counter %
200 == 0) {
3020 //We never should arrive here
3021 $counter = $count_logs;
3030 //This function inserts a course log record, calculating the URL field as necessary
3031 function restore_log_course($restore,$log) {
3036 //echo "<hr />Before transformations<br />"; //Debug
3037 //print_object($log); //Debug
3038 //Depending of the action, we recode different things
3039 switch ($log->action
) {
3041 $log->url
= "view.php?id=".$log->course
;
3042 $log->info
= $log->course
;
3046 $log->url
= "view.php?id=".$log->course
;
3050 //recode the info field (it's the user id)
3051 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3053 $log->info
= $user->new_id
;
3054 //Now, extract the mode from the url field
3055 $mode = substr(strrchr($log->url
,"="),1);
3056 $log->url
= "user.php?id=".$log->course
."&user=".$log->info
."&mode=".$mode;
3061 //Extract the course_module from the url field
3062 $cmid = substr(strrchr($log->url
,"="),1);
3063 //recode the course_module to see it it has been restored
3064 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$cmid);
3066 $cmid = $cm->new_id
;
3067 //Extract the module name and the module id from the info field
3068 $modname = strtok($log->info
," ");
3069 $modid = strtok(" ");
3070 //recode the module id to see if it has been restored
3071 $mod = backup_getid($restore->backup_unique_code
,$modname,$modid);
3073 $modid = $mod->new_id
;
3074 //Now I have everything so reconstruct url and info
3075 $log->info
= $modname." ".$modid;
3076 $log->url
= "../mod/".$modname."/view.php?id=".$cmid;
3082 //Extract the course_module from the url field
3083 $cmid = substr(strrchr($log->url
,"="),1);
3084 //recode the course_module to see it it has been restored
3085 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$cmid);
3087 $cmid = $cm->new_id
;
3088 //Extract the module name and the module id from the info field
3089 $modname = strtok($log->info
," ");
3090 $modid = strtok(" ");
3091 //recode the module id to see if it has been restored
3092 $mod = backup_getid($restore->backup_unique_code
,$modname,$modid);
3094 $modid = $mod->new_id
;
3095 //Now I have everything so reconstruct url and info
3096 $log->info
= $modname." ".$modid;
3097 $log->url
= "../mod/".$modname."/view.php?id=".$cmid;
3103 $log->url
= "view.php?id=".$log->course
;
3107 $log->url
= "edit.php?id=".$log->course
;
3112 //recode the info field (it's the user id)
3113 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3115 $log->info
= $user->new_id
;
3116 $log->url
= "view.php?id=".$log->course
;
3121 //recode the info field (it's the user id)
3122 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3124 $log->info
= $user->new_id
;
3125 $log->url
= "view.php?id=".$log->course
;
3130 //Extract the course_section from the url field
3131 $secid = substr(strrchr($log->url
,"="),1);
3132 //recode the course_section to see if it has been restored
3133 $sec = backup_getid($restore->backup_unique_code
,"course_sections",$secid);
3135 $secid = $sec->new_id
;
3136 //Now I have everything so reconstruct url and info
3137 $log->url
= "editsection.php?id=".$secid;
3142 $log->url
= "view.php?id=".$log->course
;
3147 $log->url
= "recent.php?id=".$log->course
;
3152 $log->url
= "report/log/index.php?id=".$log->course
;
3153 $log->info
= $log->course
;
3157 $log->url
= "report/log/live.php?id=".$log->course
;
3158 $log->info
= $log->course
;
3161 case "report outline":
3162 $log->url
= "report/outline/index.php?id=".$log->course
;
3163 $log->info
= $log->course
;
3166 case "report participation":
3167 $log->url
= "report/participation/index.php?id=".$log->course
;
3168 $log->info
= $log->course
;
3171 case "report stats":
3172 $log->url
= "report/stats/index.php?id=".$log->course
;
3173 $log->info
= $log->course
;
3177 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
3181 //echo "After transformations<br />"; //Debug
3182 //print_object($log); //Debug
3184 //Now if $toinsert is set, insert the record
3186 //echo "Inserting record<br />"; //Debug
3187 $status = insert_record("log",$log);
3192 //This function inserts a user log record, calculating the URL field as necessary
3193 function restore_log_user($restore,$log) {
3198 //echo "<hr />Before transformations<br />"; //Debug
3199 //print_object($log); //Debug
3200 //Depending of the action, we recode different things
3201 switch ($log->action
) {
3203 //recode the info field (it's the user id)
3204 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3206 $log->info
= $user->new_id
;
3207 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3211 case "change password":
3212 //recode the info field (it's the user id)
3213 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3215 $log->info
= $user->new_id
;
3216 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3221 //recode the info field (it's the user id)
3222 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3224 $log->info
= $user->new_id
;
3225 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3230 //recode the info field (it's the user id)
3231 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3233 $log->info
= $user->new_id
;
3234 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3239 $log->url
= "view.php?id=".$log->course
;
3243 //We split the url by ampersand char
3244 $first_part = strtok($log->url
,"&");
3245 //Get data after the = char. It's the user being updated
3246 $userid = substr(strrchr($first_part,"="),1);
3248 $user = backup_getid($restore->backup_unique_code
,"user",$userid);
3251 $log->url
= "view.php?id=".$user->new_id
."&course=".$log->course
;
3256 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
3260 //echo "After transformations<br />"; //Debug
3261 //print_object($log); //Debug
3263 //Now if $toinsert is set, insert the record
3265 //echo "Inserting record<br />"; //Debug
3266 $status = insert_record("log",$log);
3271 //This function inserts a module log record, calculating the URL field as necessary
3272 function restore_log_module($restore,$log) {
3277 //echo "<hr />Before transformations<br />"; //Debug
3278 //print_object($log); //Debug
3280 //Now we see if the required function in the module exists
3281 $function = $log->module
."_restore_logs";
3282 if (function_exists($function)) {
3284 $log = $function($restore,$log);
3285 //If everything is ok, mark the insert flag
3291 //echo "After transformations<br />"; //Debug
3292 //print_object($log); //Debug
3294 //Now if $toinsert is set, insert the record
3296 //echo "Inserting record<br />"; //Debug
3297 $status = insert_record("log",$log);
3302 //This function adjusts the instance field into course_modules. It's executed after
3303 //modules restore. There, we KNOW the new instance id !!
3304 function restore_check_instances($restore) {
3310 //We are going to iterate over each course_module saved in backup_ids
3311 $course_modules = get_records_sql("SELECT old_id,new_id
3312 FROM {$CFG->prefix}backup_ids
3313 WHERE backup_code = '$restore->backup_unique_code' AND
3314 table_name = 'course_modules'");
3315 if ($course_modules) {
3316 foreach($course_modules as $cm) {
3317 //Get full record, using backup_getids
3318 $cm_module = backup_getid($restore->backup_unique_code
,"course_modules",$cm->old_id
);
3319 //Now we are going to the REAL course_modules to get its type (field module)
3320 $module = get_record("course_modules","id",$cm_module->new_id
);
3322 //We know the module type id. Get the name from modules
3323 $type = get_record("modules","id",$module->module
);
3325 //We know the type name and the old_id. Get its new_id
3326 //from backup_ids. It's the instance !!!
3327 $instance = backup_getid($restore->backup_unique_code
,$type->name
,$cm_module->info
);
3329 //We have the new instance, so update the record in course_modules
3330 $module->instance
= $instance->new_id
;
3331 //print_object ($module); //Debug
3332 $status = update_record("course_modules",$module);
3349 //=====================================================================================
3351 //== XML Functions (SAX) ==
3353 //=====================================================================================
3355 //This is the class used to do all the xml parse
3356 class MoodleParser
{
3358 var $level = 0; //Level we are
3359 var $counter = 0; //Counter
3360 var $tree = array(); //Array of levels we are
3361 var $content = ""; //Content under current level
3362 var $todo = ""; //What we hav to do when parsing
3363 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
3364 var $temp = ""; //Temp storage.
3365 var $preferences = ""; //Preferences about what to load !!
3366 var $finished = false; //Flag to say xml_parse to stop
3368 //This function is used to get the current contents property value
3369 //They are trimed (and converted from utf8 if needed)
3370 function getContents() {
3371 return trim($this->content
);
3374 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3375 function startElementInfo($parser, $tagName, $attrs) {
3376 //Refresh properties
3378 $this->tree
[$this->level
] = $tagName;
3380 //Output something to avoid browser timeouts...
3383 //Check if we are into INFO zone
3384 //if ($this->tree[2] == "INFO") //Debug
3385 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3388 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3389 function startElementRoles($parser, $tagName, $attrs) {
3390 //Refresh properties
3392 $this->tree
[$this->level
] = $tagName;
3394 //Output something to avoid browser timeouts...
3397 //Check if we are into INFO zone
3398 //if ($this->tree[2] == "INFO") //Debug
3399 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3403 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
3404 function startElementCourseHeader($parser, $tagName, $attrs) {
3405 //Refresh properties
3407 $this->tree
[$this->level
] = $tagName;
3409 //Output something to avoid browser timeouts...
3412 //Check if we are into COURSE_HEADER zone
3413 //if ($this->tree[3] == "HEADER") //Debug
3414 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3417 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
3418 function startElementBlocks($parser, $tagName, $attrs) {
3419 //Refresh properties
3421 $this->tree
[$this->level
] = $tagName;
3423 //Output something to avoid browser timeouts...
3426 //Check if we are into BLOCKS zone
3427 //if ($this->tree[3] == "BLOCKS") //Debug
3428 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3431 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
3432 function startElementSections($parser, $tagName, $attrs) {
3433 //Refresh properties
3435 $this->tree
[$this->level
] = $tagName;
3437 //Output something to avoid browser timeouts...
3440 //Check if we are into SECTIONS zone
3441 //if ($this->tree[3] == "SECTIONS") //Debug
3442 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3445 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
3446 function startElementFormatData($parser, $tagName, $attrs) {
3447 //Refresh properties
3449 $this->tree
[$this->level
] = $tagName;
3451 //Output something to avoid browser timeouts...
3454 //Accumulate all the data inside this tag
3455 if (isset($this->tree
[3]) && $this->tree
[3] == "FORMATDATA") {
3456 if (!isset($this->temp
)) {
3459 $this->temp
.= "<".$tagName.">";
3462 //Check if we are into FORMATDATA zone
3463 //if ($this->tree[3] == "FORMATDATA") //Debug
3464 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3467 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
3468 function startElementMetacourse($parser, $tagName, $attrs) {
3470 //Refresh properties
3472 $this->tree
[$this->level
] = $tagName;
3474 //Output something to avoid browser timeouts...
3477 //Check if we are into METACOURSE zone
3478 //if ($this->tree[3] == "METACOURSE") //Debug
3479 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3482 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
3483 function startElementGradebook($parser, $tagName, $attrs) {
3485 //Refresh properties
3487 $this->tree
[$this->level
] = $tagName;
3489 //Output something to avoid browser timeouts...
3492 //Check if we are into GRADEBOOK zone
3493 //if ($this->tree[3] == "GRADEBOOK") //Debug
3494 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3496 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
3497 if (isset($this->tree
[5]) and isset($this->tree
[3])) {
3498 if (($this->tree
[5] == "GRADE_ITEM" ||
$this->tree
[5] == "GRADE_CATEGORY" ||
$this->tree
[5] == "GRADE_OUTCOME") && ($this->tree
[3] == "GRADEBOOK")) {
3499 if (!isset($this->temp
)) {
3502 $this->temp
.= "<".$tagName.">";
3508 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
3509 function startElementUsers($parser, $tagName, $attrs) {
3510 //Refresh properties
3512 $this->tree
[$this->level
] = $tagName;
3514 //Check if we are into USERS zone
3515 //if ($this->tree[3] == "USERS") //Debug
3516 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3519 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
3520 function startElementMessages($parser, $tagName, $attrs) {
3521 //Refresh properties
3523 $this->tree
[$this->level
] = $tagName;
3525 //Output something to avoid browser timeouts...
3528 //Check if we are into MESSAGES zone
3529 //if ($this->tree[3] == "MESSAGES") //Debug
3530 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3532 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
3533 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3534 if (($this->tree
[4] == "MESSAGE" ||
$this->tree
[5] == "CONTACT" ) and ($this->tree
[3] == "MESSAGES")) {
3535 if (!isset($this->temp
)) {
3538 $this->temp
.= "<".$tagName.">";
3542 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
3543 function startElementQuestions($parser, $tagName, $attrs) {
3544 //Refresh properties
3546 $this->tree
[$this->level
] = $tagName;
3548 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
3549 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
3552 //Output something to avoid browser timeouts...
3555 //Check if we are into QUESTION_CATEGORIES zone
3556 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
3557 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3559 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
3560 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3561 if (($this->tree
[4] == "QUESTION_CATEGORY") and ($this->tree
[3] == "QUESTION_CATEGORIES")) {
3562 if (!isset($this->temp
)) {
3565 $this->temp
.= "<".$tagName.">";
3570 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
3571 function startElementScales($parser, $tagName, $attrs) {
3572 //Refresh properties
3574 $this->tree
[$this->level
] = $tagName;
3576 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
3577 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
3580 //Output something to avoid browser timeouts...
3583 //Check if we are into SCALES zone
3584 //if ($this->tree[3] == "SCALES") //Debug
3585 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3587 //If we are under a SCALE tag under a SCALES zone, accumule it
3588 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3589 if (($this->tree
[4] == "SCALE") and ($this->tree
[3] == "SCALES")) {
3590 if (!isset($this->temp
)) {
3593 $this->temp
.= "<".$tagName.">";
3598 function startElementGroups($parser, $tagName, $attrs) {
3599 //Refresh properties
3601 $this->tree
[$this->level
] = $tagName;
3603 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
3604 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
3607 //Output something to avoid browser timeouts...
3610 //Check if we are into GROUPS zone
3611 //if ($this->tree[3] == "GROUPS") //Debug
3612 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3614 //If we are under a GROUP tag under a GROUPS zone, accumule it
3615 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3616 if (($this->tree
[4] == "GROUP") and ($this->tree
[3] == "GROUPS")) {
3617 if (!isset($this->temp
)) {
3620 $this->temp
.= "<".$tagName.">";
3625 function startElementGroupings($parser, $tagName, $attrs) { //TODO:
3626 //Refresh properties
3628 $this->tree
[$this->level
] = $tagName;
3630 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
3631 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
3634 //Output something to avoid browser timeouts...
3637 //Check if we are into GROUPINGS zone
3638 //if ($this->tree[3] == "GROUPINGS") //Debug
3639 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3641 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
3642 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3643 if (($this->tree
[4] == "GROUPING") and ($this->tree
[3] == "GROUPINGS")) {
3644 if (!isset($this->temp
)) {
3647 $this->temp
.= "<".$tagName.">";
3652 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
3653 function startElementEvents($parser, $tagName, $attrs) {
3654 //Refresh properties
3656 $this->tree
[$this->level
] = $tagName;
3658 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
3659 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
3662 //Output something to avoid browser timeouts...
3665 //Check if we are into EVENTS zone
3666 //if ($this->tree[3] == "EVENTS") //Debug
3667 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3669 //If we are under a EVENT tag under a EVENTS zone, accumule it
3670 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3671 if (($this->tree
[4] == "EVENT") and ($this->tree
[3] == "EVENTS")) {
3672 if (!isset($this->temp
)) {
3675 $this->temp
.= "<".$tagName.">";
3680 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
3681 function startElementModules($parser, $tagName, $attrs) {
3682 //Refresh properties
3684 $this->tree
[$this->level
] = $tagName;
3686 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
3687 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
3690 //Output something to avoid browser timeouts...
3693 //Check if we are into MODULES zone
3694 //if ($this->tree[3] == "MODULES") //Debug
3695 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3697 //If we are under a MOD tag under a MODULES zone, accumule it
3698 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3699 if (($this->tree
[4] == "MOD") and ($this->tree
[3] == "MODULES")) {
3700 if (!isset($this->temp
)) {
3703 $this->temp
.= "<".$tagName.">";
3708 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
3709 function startElementLogs($parser, $tagName, $attrs) {
3710 //Refresh properties
3712 $this->tree
[$this->level
] = $tagName;
3714 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
3715 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
3718 //Output something to avoid browser timeouts...
3721 //Check if we are into LOGS zone
3722 //if ($this->tree[3] == "LOGS") //Debug
3723 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3725 //If we are under a LOG tag under a LOGS zone, accumule it
3726 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3727 if (($this->tree
[4] == "LOG") and ($this->tree
[3] == "LOGS")) {
3728 if (!isset($this->temp
)) {
3731 $this->temp
.= "<".$tagName.">";
3736 //This is the startTag default handler we use when todo is undefined
3737 function startElement($parser, $tagName, $attrs) {
3739 $this->tree
[$this->level
] = $tagName;
3741 //Output something to avoid browser timeouts...
3744 echo $this->level
.str_repeat(" ",$this->level
*2)."<".$tagName."><br />\n"; //Debug
3747 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
3748 function endElementInfo($parser, $tagName) {
3749 //Check if we are into INFO zone
3750 if ($this->tree
[2] == "INFO") {
3751 //if (trim($this->content)) //Debug
3752 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
3753 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
3754 //Dependig of different combinations, do different things
3755 if ($this->level
== 3) {
3758 $this->info
->backup_name
= $this->getContents();
3760 case "MOODLE_VERSION":
3761 $this->info
->backup_moodle_version
= $this->getContents();
3763 case "MOODLE_RELEASE":
3764 $this->info
->backup_moodle_release
= $this->getContents();
3766 case "BACKUP_VERSION":
3767 $this->info
->backup_backup_version
= $this->getContents();
3769 case "BACKUP_RELEASE":
3770 $this->info
->backup_backup_release
= $this->getContents();
3773 $this->info
->backup_date
= $this->getContents();
3775 case "ORIGINAL_WWWROOT":
3776 $this->info
->original_wwwroot
= $this->getContents();
3778 case "MNET_EXTERNALUSERS":
3779 $this->info
->mnet_externalusers
= $this->getContents();
3783 if ($this->tree
[3] == "DETAILS") {
3784 if ($this->level
== 4) {
3787 $this->info
->backup_metacourse
= $this->getContents();
3790 $this->info
->backup_users
= $this->getContents();
3793 $this->info
->backup_logs
= $this->getContents();
3796 $this->info
->backup_user_files
= $this->getContents();
3799 $this->info
->backup_course_files
= $this->getContents();
3802 $this->info
->backup_messages
= $this->getContents();
3805 $this->info
->backup_block_format
= $this->getContents();
3809 if ($this->level
== 5) {
3812 $this->info
->tempName
= $this->getContents();
3815 $this->info
->mods
[$this->info
->tempName
]->backup
= $this->getContents();
3818 $this->info
->mods
[$this->info
->tempName
]->userinfo
= $this->getContents();
3822 if ($this->level
== 7) {
3825 $this->info
->tempId
= $this->getContents();
3826 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->id
= $this->info
->tempId
;
3829 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->name
= $this->getContents();
3832 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->backup
= $this->getContents();
3835 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->userinfo
= $this->getContents();
3842 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
3843 //Speed up a lot (avoid parse all)
3844 if ($tagName == "INFO") {
3845 $this->finished
= true;
3849 $this->tree
[$this->level
] = "";
3851 $this->content
= "";
3855 function endElementRoles($parser, $tagName) {
3856 //Check if we are into INFO zone
3857 if ($this->tree
[2] == "ROLES") {
3859 if ($this->tree
[3] == "ROLE") {
3860 if ($this->level
== 4) {
3863 $this->info
->tempname
= $this->getContents();
3867 $this->info
->tempshortname
= $this->getContents();
3869 case "ID": // this is the old id
3870 $this->info
->tempid
= $this->getContents();
3874 if ($this->level
== 6) {
3877 $this->info
->roles
[$this->info
->tempid
]->name
= $this->info
->tempname
;
3878 $this->info
->roles
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
3880 $this->info
->tempcapname
= $this->getContents();
3881 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->name
= $this->getContents();
3884 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->permission
= $this->getContents();
3886 case "TIMEMODIFIED":
3887 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->timemodified
= $this->getContents();
3890 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->modifierid
= $this->getContents();
3897 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
3898 //Speed up a lot (avoid parse all)
3899 if ($tagName == "ROLES") {
3900 $this->finished
= true;
3904 $this->tree
[$this->level
] = "";
3906 $this->content
= "";
3910 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
3911 function endElementCourseHeader($parser, $tagName) {
3912 //Check if we are into COURSE_HEADER zone
3913 if ($this->tree
[3] == "HEADER") {
3914 //if (trim($this->content)) //Debug
3915 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
3916 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
3917 //Dependig of different combinations, do different things
3918 if ($this->level
== 4) {
3921 $this->info
->course_id
= $this->getContents();
3924 $this->info
->course_password
= $this->getContents();
3927 $this->info
->course_fullname
= $this->getContents();
3930 $this->info
->course_shortname
= $this->getContents();
3933 $this->info
->course_idnumber
= $this->getContents();
3936 $this->info
->course_summary
= $this->getContents();
3939 $this->info
->course_format
= $this->getContents();
3942 $this->info
->course_showgrades
= $this->getContents();
3945 $this->info
->blockinfo
= $this->getContents();
3948 $this->info
->course_newsitems
= $this->getContents();
3951 $this->info
->course_teacher
= $this->getContents();
3954 $this->info
->course_teachers
= $this->getContents();
3957 $this->info
->course_student
= $this->getContents();
3960 $this->info
->course_students
= $this->getContents();
3963 $this->info
->course_guest
= $this->getContents();
3966 $this->info
->course_startdate
= $this->getContents();
3969 $this->info
->course_enrolperiod
= $this->getContents();
3972 $this->info
->course_numsections
= $this->getContents();
3974 //case "SHOWRECENT": INFO: This is out in 1.3
3975 // $this->info->course_showrecent = $this->getContents();
3978 $this->info
->course_maxbytes
= $this->getContents();
3981 $this->info
->course_showreports
= $this->getContents();
3984 $this->info
->course_groupmode
= $this->getContents();
3986 case "GROUPMODEFORCE":
3987 $this->info
->course_groupmodeforce
= $this->getContents();
3990 $this->info
->course_lang
= $this->getContents();
3993 $this->info
->course_theme
= $this->getContents();
3996 $this->info
->course_cost
= $this->getContents();
3999 $this->info
->course_currency
= $this->getContents();
4002 $this->info
->course_marker
= $this->getContents();
4005 $this->info
->course_visible
= $this->getContents();
4007 case "HIDDENSECTIONS":
4008 $this->info
->course_hiddensections
= $this->getContents();
4011 $this->info
->course_timecreated
= $this->getContents();
4013 case "TIMEMODIFIED":
4014 $this->info
->course_timemodified
= $this->getContents();
4017 $this->info
->course_metacourse
= $this->getContents();
4021 if ($this->tree
[4] == "CATEGORY") {
4022 if ($this->level
== 5) {
4025 $this->info
->category
->id
= $this->getContents();
4028 $this->info
->category
->name
= $this->getContents();
4034 if ($this->tree
[4] == "ROLES_ASSIGNMENTS") {
4035 if ($this->level
== 6) {
4038 $this->info
->tempname
= $this->getContents();
4041 $this->info
->tempshortname
= $this->getContents();
4044 $this->info
->tempid
= $this->getContents();
4049 if ($this->level
== 8) {
4052 $this->info
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4053 $this->info
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4054 $this->info
->tempuser
= $this->getContents();
4055 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
4058 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
4061 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
4064 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
4066 case "TIMEMODIFIED":
4067 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
4070 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
4073 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
4076 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
4081 } /// ends role_assignments
4083 if ($this->tree
[4] == "ROLES_OVERRIDES") {
4084 if ($this->level
== 6) {
4087 $this->info
->tempname
= $this->getContents();
4090 $this->info
->tempshortname
= $this->getContents();
4093 $this->info
->tempid
= $this->getContents();
4098 if ($this->level
== 8) {
4101 $this->info
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4102 $this->info
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4103 $this->info
->tempname
= $this->getContents(); // change to name of capability
4104 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4107 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4109 case "TIMEMODIFIED":
4110 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4113 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
4117 } /// ends role_overrides
4120 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
4121 //Speed up a lot (avoid parse all)
4122 if ($tagName == "HEADER") {
4123 $this->finished
= true;
4127 $this->tree
[$this->level
] = "";
4129 $this->content
= "";
4133 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
4134 function endElementBlocks($parser, $tagName) {
4135 //Check if we are into BLOCKS zone
4136 if ($this->tree
[3] == 'BLOCKS') {
4137 //if (trim($this->content)) //Debug
4138 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4139 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4140 //Dependig of different combinations, do different things
4141 if ($this->level
== 4) {
4144 //We've finalized a block, get it
4145 $this->info
->instances
[] = $this->info
->tempinstance
;
4146 unset($this->info
->tempinstance
);
4152 if ($this->level
== 5) {
4155 $this->info
->tempinstance
->id
= $this->getContents();
4157 $this->info
->tempinstance
->name
= $this->getContents();
4160 $this->info
->tempinstance
->pageid
= $this->getContents();
4163 $this->info
->tempinstance
->pagetype
= $this->getContents();
4166 $this->info
->tempinstance
->position
= $this->getContents();
4169 $this->info
->tempinstance
->weight
= $this->getContents();
4172 $this->info
->tempinstance
->visible
= $this->getContents();
4175 $this->info
->tempinstance
->configdata
= $this->getContents();
4182 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
4183 if ($this->level
== 7) {
4186 $this->info
->tempname
= $this->getContents();
4189 $this->info
->tempshortname
= $this->getContents();
4192 $this->info
->tempid
= $this->getContents(); // temp roleid
4197 if ($this->level
== 9) {
4201 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4203 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4205 $this->info
->tempuser
= $this->getContents();
4207 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
4210 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
4213 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
4216 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
4218 case "TIMEMODIFIED":
4219 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
4222 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
4225 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
4228 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
4233 } /// ends role_assignments
4235 if ($this->tree
[5] == "ROLES_OVERRIDES") {
4236 if ($this->level
== 7) {
4239 $this->info
->tempname
= $this->getContents();
4242 $this->info
->tempshortname
= $this->getContents();
4245 $this->info
->tempid
= $this->getContents(); // temp roleid
4250 if ($this->level
== 9) {
4254 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4255 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4256 $this->info
->tempname
= $this->getContents(); // change to name of capability
4257 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4260 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4262 case "TIMEMODIFIED":
4263 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4266 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
4270 } /// ends role_overrides
4273 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
4274 //Speed up a lot (avoid parse all)
4275 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
4276 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
4277 if ($this->tree
[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
4278 $this->finished
= true;
4282 $this->tree
[$this->level
] = '';
4284 $this->content
= "";
4287 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
4288 function endElementSections($parser, $tagName) {
4289 //Check if we are into SECTIONS zone
4290 if ($this->tree
[3] == "SECTIONS") {
4291 //if (trim($this->content)) //Debug
4292 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4293 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4294 //Dependig of different combinations, do different things
4295 if ($this->level
== 4) {
4298 //We've finalized a section, get it
4299 $this->info
->sections
[$this->info
->tempsection
->id
] = $this->info
->tempsection
;
4300 unset($this->info
->tempsection
);
4303 if ($this->level
== 5) {
4306 $this->info
->tempsection
->id
= $this->getContents();
4309 $this->info
->tempsection
->number
= $this->getContents();
4312 $this->info
->tempsection
->summary
= $this->getContents();
4315 $this->info
->tempsection
->visible
= $this->getContents();
4319 if ($this->level
== 6) {
4322 //We've finalized a mod, get it
4323 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->type
=
4324 $this->info
->tempmod
->type
;
4325 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->instance
=
4326 $this->info
->tempmod
->instance
;
4327 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->added
=
4328 $this->info
->tempmod
->added
;
4329 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->score
=
4330 $this->info
->tempmod
->score
;
4331 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->indent
=
4332 $this->info
->tempmod
->indent
;
4333 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->visible
=
4334 $this->info
->tempmod
->visible
;
4335 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupmode
=
4336 $this->info
->tempmod
->groupmode
;
4337 unset($this->info
->tempmod
);
4340 if ($this->level
== 7) {
4343 $this->info
->tempmod
->id
= $this->getContents();
4346 $this->info
->tempmod
->type
= $this->getContents();
4349 $this->info
->tempmod
->instance
= $this->getContents();
4352 $this->info
->tempmod
->added
= $this->getContents();
4355 $this->info
->tempmod
->score
= $this->getContents();
4358 $this->info
->tempmod
->indent
= $this->getContents();
4361 $this->info
->tempmod
->visible
= $this->getContents();
4364 $this->info
->tempmod
->groupmode
= $this->getContents();
4371 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_ASSIGNMENTS") {
4373 if ($this->level
== 9) {
4376 $this->info
->tempname
= $this->getContents();
4379 $this->info
->tempshortname
= $this->getContents();
4382 $this->info
->tempid
= $this->getContents(); // temp roleid
4387 if ($this->level
== 11) {
4390 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4392 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4394 $this->info
->tempuser
= $this->getContents();
4396 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
4399 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
4402 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
4405 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
4407 case "TIMEMODIFIED":
4408 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
4411 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
4414 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
4417 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
4422 } /// ends role_assignments
4424 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_OVERRIDES") {
4425 if ($this->level
== 9) {
4428 $this->info
->tempname
= $this->getContents();
4431 $this->info
->tempshortname
= $this->getContents();
4434 $this->info
->tempid
= $this->getContents(); // temp roleid
4439 if ($this->level
== 11) {
4443 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4444 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4445 $this->info
->tempname
= $this->getContents(); // change to name of capability
4446 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4449 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4451 case "TIMEMODIFIED":
4452 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4455 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
4459 } /// ends role_overrides
4463 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
4464 //Speed up a lot (avoid parse all)
4465 if ($tagName == "SECTIONS") {
4466 $this->finished
= true;
4470 $this->tree
[$this->level
] = "";
4472 $this->content
= "";
4476 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4477 function endElementFormatData($parser, $tagName) {
4478 //Check if we are into FORMATDATA zone
4479 if ($this->tree
[3] == 'FORMATDATA') {
4480 if (!isset($this->temp
)) {
4483 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
4486 if($tagName=='FORMATDATA') {
4487 //Did we have any data? If not don't bother
4488 if($this->temp
!='<FORMATDATA></FORMATDATA>') {
4489 //Prepend XML standard header to info gathered
4490 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4493 //Call to xmlize for this portion of xml data (the FORMATDATA block)
4494 $this->info
->format_data
= xmlize($xml_data,0);
4496 //Stop parsing at end of FORMATDATA
4497 $this->finished
=true;
4501 $this->tree
[$this->level
] = "";
4503 $this->content
= "";
4506 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4507 function endElementMetacourse($parser, $tagName) {
4508 //Check if we are into METACOURSE zone
4509 if ($this->tree
[3] == 'METACOURSE') {
4510 //if (trim($this->content)) //Debug
4511 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4512 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4513 //Dependig of different combinations, do different things
4514 if ($this->level
== 5) {
4517 //We've finalized a child, get it
4518 $this->info
->childs
[] = $this->info
->tempmeta
;
4519 unset($this->info
->tempmeta
);
4522 //We've finalized a parent, get it
4523 $this->info
->parents
[] = $this->info
->tempmeta
;
4524 unset($this->info
->tempmeta
);
4530 if ($this->level
== 6) {
4533 $this->info
->tempmeta
->id
= $this->getContents();
4536 $this->info
->tempmeta
->idnumber
= $this->getContents();
4539 $this->info
->tempmeta
->shortname
= $this->getContents();
4545 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
4546 //Speed up a lot (avoid parse all)
4547 if ($this->tree
[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
4548 $this->finished
= true;
4552 $this->tree
[$this->level
] = '';
4554 $this->content
= "";
4557 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4558 function endElementGradebook($parser, $tagName) {
4559 //Check if we are into GRADEBOOK zone
4560 if ($this->tree
[3] == "GRADEBOOK") {
4561 //if (trim($this->content)) //Debug
4562 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4563 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
4564 //Acumulate data to info (content + close tag)
4565 //Reconvert: strip htmlchars again and trim to generate xml data
4566 if (!isset($this->temp
)) {
4569 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
4570 // We have finished outcome, grade_category or grade_item, reset accumulated
4571 // data because they are close tags
4572 if ($this->level
== 4) {
4575 //If we've finished a message, xmlize it an save to db
4576 if (($this->level
== 5) and ($tagName == "GRADE_ITEM")) {
4577 //Prepend XML standard header to info gathered
4578 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4579 //Call to xmlize for this portion of xml data (one PREFERENCE)
4580 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4581 $data = xmlize($xml_data,0);
4582 //echo strftime ("%X",time())."<p>"; //Debug
4583 //traverse_xmlize($data); //Debug
4584 //print_object ($GLOBALS['traverse_array']); //Debug
4585 //$GLOBALS['traverse_array']=""; //Debug
4586 //Now, save data to db. We'll use it later
4587 //Get id and status from data
4588 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
4592 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_items', $item_id,
4594 //Create returning info
4595 $this->info
= $this->counter
;
4601 //If we've finished a grade_category, xmlize it an save to db
4602 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORY")) {
4603 //Prepend XML standard header to info gathered
4604 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4605 //Call to xmlize for this portion of xml data (one CATECORY)
4606 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4607 $data = xmlize($xml_data,0);
4608 //echo strftime ("%X",time())."<p>"; //Debug
4609 //traverse_xmlize($data); //Debug
4610 //print_object ($GLOBALS['traverse_array']); //Debug
4611 //$GLOBALS['traverse_array']=""; //Debug
4612 //Now, save data to db. We'll use it later
4613 //Get id and status from data
4614 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
4617 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_categories' ,$category_id,
4619 //Create returning info
4620 $this->info
= $this->counter
;
4625 //If we've finished a grade_category, xmlize it an save to db
4626 if (($this->level
== 5) and ($tagName == "GRADE_OUTCOME")) {
4627 //Prepend XML standard header to info gathered
4628 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4629 //Call to xmlize for this portion of xml data (one CATECORY)
4630 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4631 $data = xmlize($xml_data,0);
4632 //echo strftime ("%X",time())."<p>"; //Debug
4633 //traverse_xmlize($data); //Debug
4634 //print_object ($GLOBALS['traverse_array']); //Debug
4635 //$GLOBALS['traverse_array']=""; //Debug
4636 //Now, save data to db. We'll use it later
4637 //Get id and status from data
4638 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
4641 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_outcomes' ,$outcome_id,
4643 //Create returning info
4644 $this->info
= $this->counter
;
4650 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
4651 //Speed up a lot (avoid parse all)
4652 if ($tagName == "GRADEBOOK" and $this->level
== 3) {
4653 $this->finished
= true;
4658 $this->tree
[$this->level
] = "";
4660 $this->content
= "";
4664 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
4665 function endElementUsers($parser, $tagName) {
4667 //Check if we are into USERS zone
4668 if ($this->tree
[3] == "USERS") {
4669 //if (trim($this->content)) //Debug
4670 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4671 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4672 //Dependig of different combinations, do different things
4673 if ($this->level
== 4) {
4678 //Save to db, only save if record not already exist
4679 // if there already is an new_id for this entry, just use that new_id?
4680 $newuser = backup_getid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
);
4681 if (isset($newuser->new_id
)) {
4682 $newid = $newuser->new_id
;
4687 backup_putid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
,
4688 $newid,$this->info
->tempuser
);
4691 if ($this->counter %
10 == 0) {
4692 if (!defined('RESTORE_SILENTLY')) {
4694 if ($this->counter %
200 == 0) {
4701 //Delete temp obejct
4702 unset($this->info
->tempuser
);
4706 if ($this->level
== 5) {
4709 $this->info
->users
[$this->getContents()] = $this->getContents();
4710 $this->info
->tempuser
->id
= $this->getContents();
4713 $this->info
->tempuser
->auth
= $this->getContents();
4716 $this->info
->tempuser
->confirmed
= $this->getContents();
4718 case "POLICYAGREED":
4719 $this->info
->tempuser
->policyagreed
= $this->getContents();
4722 $this->info
->tempuser
->deleted
= $this->getContents();
4725 $this->info
->tempuser
->username
= $this->getContents();
4728 $this->info
->tempuser
->password
= $this->getContents();
4731 $this->info
->tempuser
->idnumber
= $this->getContents();
4734 $this->info
->tempuser
->firstname
= $this->getContents();
4737 $this->info
->tempuser
->lastname
= $this->getContents();
4740 $this->info
->tempuser
->email
= $this->getContents();
4743 $this->info
->tempuser
->emailstop
= $this->getContents();
4746 $this->info
->tempuser
->icq
= $this->getContents();
4749 $this->info
->tempuser
->skype
= $this->getContents();
4752 $this->info
->tempuser
->aim
= $this->getContents();
4755 $this->info
->tempuser
->yahoo
= $this->getContents();
4758 $this->info
->tempuser
->msn
= $this->getContents();
4761 $this->info
->tempuser
->phone1
= $this->getContents();
4764 $this->info
->tempuser
->phone2
= $this->getContents();
4767 $this->info
->tempuser
->institution
= $this->getContents();
4770 $this->info
->tempuser
->department
= $this->getContents();
4773 $this->info
->tempuser
->address
= $this->getContents();
4776 $this->info
->tempuser
->city
= $this->getContents();
4779 $this->info
->tempuser
->country
= $this->getContents();
4782 $this->info
->tempuser
->lang
= $this->getContents();
4785 $this->info
->tempuser
->theme
= $this->getContents();
4788 $this->info
->tempuser
->timezone
= $this->getContents();
4791 $this->info
->tempuser
->firstaccess
= $this->getContents();
4794 $this->info
->tempuser
->lastaccess
= $this->getContents();
4797 $this->info
->tempuser
->lastlogin
= $this->getContents();
4799 case "CURRENTLOGIN":
4800 $this->info
->tempuser
->currentlogin
= $this->getContents();
4803 $this->info
->tempuser
->lastip
= $this->getContents();
4806 $this->info
->tempuser
->secret
= $this->getContents();
4809 $this->info
->tempuser
->picture
= $this->getContents();
4812 $this->info
->tempuser
->url
= $this->getContents();
4815 $this->info
->tempuser
->description
= $this->getContents();
4818 $this->info
->tempuser
->mailformat
= $this->getContents();
4821 $this->info
->tempuser
->maildigest
= $this->getContents();
4824 $this->info
->tempuser
->maildisplay
= $this->getContents();
4827 $this->info
->tempuser
->htmleditor
= $this->getContents();
4830 $this->info
->tempuser
->ajax
= $this->getContents();
4832 case "AUTOSUBSCRIBE":
4833 $this->info
->tempuser
->autosubscribe
= $this->getContents();
4836 $this->info
->tempuser
->trackforums
= $this->getContents();
4839 $this->info
->tempuser
->mnethosturl
= $this->getContents();
4841 case "TIMEMODIFIED":
4842 $this->info
->tempuser
->timemodified
= $this->getContents();
4848 if ($this->level
== 6 && $this->tree
[5]!="ROLES_ASSIGNMENTS" && $this->tree
[5]!="ROLES_OVERRIDES") {
4851 //We've finalized a role, get it
4852 $this->info
->tempuser
->roles
[$this->info
->temprole
->type
] = $this->info
->temprole
;
4853 unset($this->info
->temprole
);
4855 case "USER_PREFERENCE":
4856 //We've finalized a user_preference, get it
4857 $this->info
->tempuser
->user_preferences
[$this->info
->tempuserpreference
->name
] = $this->info
->tempuserpreference
;
4858 unset($this->info
->tempuserpreference
);
4863 if ($this->level
== 7) {
4866 $this->info
->temprole
->type
= $this->getContents();
4869 $this->info
->temprole
->authority
= $this->getContents();
4872 $this->info
->temprole
->tea_role
= $this->getContents();
4875 $this->info
->temprole
->editall
= $this->getContents();
4878 $this->info
->temprole
->timestart
= $this->getContents();
4881 $this->info
->temprole
->timeend
= $this->getContents();
4883 case "TIMEMODIFIED":
4884 $this->info
->temprole
->timemodified
= $this->getContents();
4887 $this->info
->temprole
->timestart
= $this->getContents();
4890 $this->info
->temprole
->timeend
= $this->getContents();
4893 $this->info
->temprole
->time
= $this->getContents();
4896 $this->info
->temprole
->timeaccess
= $this->getContents();
4899 $this->info
->temprole
->enrol
= $this->getContents();
4902 $this->info
->tempuserpreference
->name
= $this->getContents();
4905 $this->info
->tempuserpreference
->value
= $this->getContents();
4913 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
4915 if ($this->level
== 7) {
4918 $this->info
->tempname
= $this->getContents();
4921 $this->info
->tempshortname
= $this->getContents();
4924 $this->info
->tempid
= $this->getContents(); // temp roleid
4929 if ($this->level
== 9) {
4933 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4935 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4937 $this->info
->tempuserid
= $this->getContents();
4939 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->userid
= $this->getContents();
4942 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->hidden
= $this->getContents();
4945 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timestart
= $this->getContents();
4948 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timeend
= $this->getContents();
4950 case "TIMEMODIFIED":
4951 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timemodified
= $this->getContents();
4954 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->modifierid
= $this->getContents();
4957 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->enrol
= $this->getContents();
4960 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->sortorder
= $this->getContents();
4965 } /// ends role_assignments
4967 if ($this->tree
[5] == "ROLES_OVERRIDES") {
4968 if ($this->level
== 7) {
4971 $this->info
->tempname
= $this->getContents();
4974 $this->info
->tempshortname
= $this->getContents();
4977 $this->info
->tempid
= $this->getContents(); // temp roleid
4982 if ($this->level
== 9) {
4986 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4987 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4988 $this->info
->tempname
= $this->getContents(); // change to name of capability
4989 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4992 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4994 case "TIMEMODIFIED":
4995 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4998 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
5002 } /// ends role_overrides
5004 } // closes if this->tree[3]=="users"
5006 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
5007 //Speed up a lot (avoid parse all)
5008 if ($tagName == "USERS" and $this->level
== 3) {
5009 $this->finished
= true;
5014 $this->tree
[$this->level
] = "";
5016 $this->content
= "";
5020 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
5021 function endElementMessages($parser, $tagName) {
5022 //Check if we are into MESSAGES zone
5023 if ($this->tree
[3] == "MESSAGES") {
5024 //if (trim($this->content)) //Debug
5025 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5026 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
5027 //Acumulate data to info (content + close tag)
5028 //Reconvert: strip htmlchars again and trim to generate xml data
5029 if (!isset($this->temp
)) {
5032 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5033 //If we've finished a message, xmlize it an save to db
5034 if (($this->level
== 4) and ($tagName == "MESSAGE")) {
5035 //Prepend XML standard header to info gathered
5036 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5037 //Call to xmlize for this portion of xml data (one MESSAGE)
5038 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5039 $data = xmlize($xml_data,0);
5040 //echo strftime ("%X",time())."<p>"; //Debug
5041 //traverse_xmlize($data); //Debug
5042 //print_object ($GLOBALS['traverse_array']); //Debug
5043 //$GLOBALS['traverse_array']=""; //Debug
5044 //Now, save data to db. We'll use it later
5045 //Get id and status from data
5046 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
5047 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
5048 if ($message_status == "READ") {
5049 $table = "message_read";
5055 $status = backup_putid($this->preferences
->backup_unique_code
, $table,$message_id,
5057 //Create returning info
5058 $this->info
= $this->counter
;
5062 //If we've finished a contact, xmlize it an save to db
5063 if (($this->level
== 5) and ($tagName == "CONTACT")) {
5064 //Prepend XML standard header to info gathered
5065 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5066 //Call to xmlize for this portion of xml data (one MESSAGE)
5067 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5068 $data = xmlize($xml_data,0);
5069 //echo strftime ("%X",time())."<p>"; //Debug
5070 //traverse_xmlize($data); //Debug
5071 //print_object ($GLOBALS['traverse_array']); //Debug
5072 //$GLOBALS['traverse_array']=""; //Debug
5073 //Now, save data to db. We'll use it later
5074 //Get id and status from data
5075 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
5078 $status = backup_putid($this->preferences
->backup_unique_code
, 'message_contacts' ,$contact_id,
5080 //Create returning info
5081 $this->info
= $this->counter
;
5087 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
5088 //Speed up a lot (avoid parse all)
5089 if ($tagName == "MESSAGES" and $this->level
== 3) {
5090 $this->finished
= true;
5095 $this->tree
[$this->level
] = "";
5097 $this->content
= "";
5101 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
5102 function endElementQuestions($parser, $tagName) {
5103 //Check if we are into QUESTION_CATEGORIES zone
5104 if ($this->tree
[3] == "QUESTION_CATEGORIES") {
5105 //if (trim($this->content)) //Debug
5106 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5107 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5108 //Acumulate data to info (content + close tag)
5109 //Reconvert: strip htmlchars again and trim to generate xml data
5110 if (!isset($this->temp
)) {
5113 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5114 //If we've finished a mod, xmlize it an save to db
5115 if (($this->level
== 4) and ($tagName == "QUESTION_CATEGORY")) {
5116 //Prepend XML standard header to info gathered
5117 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5118 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
5119 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5120 $data = xmlize($xml_data,0);
5121 //echo strftime ("%X",time())."<p>"; //Debug
5122 //traverse_xmlize($data); //Debug
5123 //print_object ($GLOBALS['traverse_array']); //Debug
5124 //$GLOBALS['traverse_array']=""; //Debug
5125 //Now, save data to db. We'll use it later
5127 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
5129 $status = backup_putid($this->preferences
->backup_unique_code
,"question_categories",$category_id,
5131 //Create returning info
5132 $ret_info->id
= $category_id;
5133 $this->info
[] = $ret_info;
5139 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
5140 //Speed up a lot (avoid parse all)
5141 if ($tagName == "QUESTION_CATEGORIES" and $this->level
== 3) {
5142 $this->finished
= true;
5146 $this->tree
[$this->level
] = "";
5148 $this->content
= "";
5152 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
5153 function endElementScales($parser, $tagName) {
5154 //Check if we are into SCALES zone
5155 if ($this->tree
[3] == "SCALES") {
5156 //if (trim($this->content)) //Debug
5157 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5158 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5159 //Acumulate data to info (content + close tag)
5160 //Reconvert: strip htmlchars again and trim to generate xml data
5161 if (!isset($this->temp
)) {
5164 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5165 //If we've finished a scale, xmlize it an save to db
5166 if (($this->level
== 4) and ($tagName == "SCALE")) {
5167 //Prepend XML standard header to info gathered
5168 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5169 //Call to xmlize for this portion of xml data (one SCALE)
5170 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5171 $data = xmlize($xml_data,0);
5172 //echo strftime ("%X",time())."<p>"; //Debug
5173 //traverse_xmlize($data); //Debug
5174 //print_object ($GLOBALS['traverse_array']); //Debug
5175 //$GLOBALS['traverse_array']=""; //Debug
5176 //Now, save data to db. We'll use it later
5177 //Get id and from data
5178 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
5180 $status = backup_putid($this->preferences
->backup_unique_code
,"scale",$scale_id,
5182 //Create returning info
5183 $ret_info->id
= $scale_id;
5184 $this->info
[] = $ret_info;
5190 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
5191 //Speed up a lot (avoid parse all)
5192 if ($tagName == "SCALES" and $this->level
== 3) {
5193 $this->finished
= true;
5197 $this->tree
[$this->level
] = "";
5199 $this->content
= "";
5203 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
5204 function endElementGroups($parser, $tagName) {
5205 //Check if we are into GROUPS zone
5206 if ($this->tree
[3] == "GROUPS") {
5207 //if (trim($this->content)) //Debug
5208 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5209 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5210 //Acumulate data to info (content + close tag)
5211 //Reconvert: strip htmlchars again and trim to generate xml data
5212 if (!isset($this->temp
)) {
5215 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5216 //If we've finished a group, xmlize it an save to db
5217 if (($this->level
== 4) and ($tagName == "GROUP")) {
5218 //Prepend XML standard header to info gathered
5219 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5220 //Call to xmlize for this portion of xml data (one GROUP)
5221 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5222 $data = xmlize($xml_data,0);
5223 //echo strftime ("%X",time())."<p>"; //Debug
5224 //traverse_xmlize($data); //Debug
5225 //print_object ($GLOBALS['traverse_array']); //Debug
5226 //$GLOBALS['traverse_array']=""; //Debug
5227 //Now, save data to db. We'll use it later
5228 //Get id and from data
5229 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
5231 $status = backup_putid($this->preferences
->backup_unique_code
,"groups",$group_id,
5233 //Create returning info
5234 $ret_info = new Object();
5235 $ret_info->id
= $group_id;
5236 $this->info
[] = $ret_info;
5242 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
5243 //Speed up a lot (avoid parse all)
5244 if ($tagName == "GROUPS" and $this->level
== 3) {
5245 $this->finished
= true;
5249 $this->tree
[$this->level
] = "";
5251 $this->content
= "";
5255 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPINGS")
5256 function endElementGroupings($parser, $tagName) { //TODO:
5257 //Check if we are into GROUPS zone
5258 if ($this->tree
[3] == "GROUPINGS") {
5259 //Acumulate data to info (content + close tag)
5260 //Reconvert: strip htmlchars again and trim to generate xml data
5261 if (!isset($this->temp
)) {
5264 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5265 //If we've finished a group, xmlize it an save to db
5266 if (($this->level
== 4) and ($tagName == "GROUPING")) {
5267 //Prepend XML standard header to info gathered
5268 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5269 //Call to xmlize for this portion of xml data (one GROUPING)
5270 $data = xmlize($xml_data,0);
5271 //Now, save data to db. We'll use it later
5272 //Get id and from data
5273 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
5275 $status = backup_putid($this->preferences
->backup_unique_code
,"groupings",$grouping_id,
5277 //Create returning info
5278 $ret_info = new Object();
5279 $ret_info->id
= $grouping_id;
5280 $this->info
[] = $ret_info;
5286 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
5287 //Speed up a lot (avoid parse all)
5288 if ($tagName == "GROUPINGS" and $this->level
== 3) {
5289 $this->finished
= true;
5293 $this->tree
[$this->level
] = "";
5295 $this->content
= "";
5299 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
5300 function endElementEvents($parser, $tagName) {
5301 //Check if we are into EVENTS zone
5302 if ($this->tree
[3] == "EVENTS") {
5303 //if (trim($this->content)) //Debug
5304 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5305 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5306 //Acumulate data to info (content + close tag)
5307 //Reconvert: strip htmlchars again and trim to generate xml data
5308 if (!isset($this->temp
)) {
5311 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5312 //If we've finished a event, xmlize it an save to db
5313 if (($this->level
== 4) and ($tagName == "EVENT")) {
5314 //Prepend XML standard header to info gathered
5315 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5316 //Call to xmlize for this portion of xml data (one EVENT)
5317 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5318 $data = xmlize($xml_data,0);
5319 //echo strftime ("%X",time())."<p>"; //Debug
5320 //traverse_xmlize($data); //Debug
5321 //print_object ($GLOBALS['traverse_array']); //Debug
5322 //$GLOBALS['traverse_array']=""; //Debug
5323 //Now, save data to db. We'll use it later
5324 //Get id and from data
5325 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
5327 $status = backup_putid($this->preferences
->backup_unique_code
,"event",$event_id,
5329 //Create returning info
5330 $ret_info->id
= $event_id;
5331 $this->info
[] = $ret_info;
5337 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
5338 //Speed up a lot (avoid parse all)
5339 if ($tagName == "EVENTS" and $this->level
== 3) {
5340 $this->finished
= true;
5344 $this->tree
[$this->level
] = "";
5346 $this->content
= "";
5350 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
5351 function endElementModules($parser, $tagName) {
5352 //Check if we are into MODULES zone
5353 if ($this->tree
[3] == "MODULES") {
5354 //if (trim($this->content)) //Debug
5355 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5356 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5357 //Acumulate data to info (content + close tag)
5358 //Reconvert: strip htmlchars again and trim to generate xml data
5359 if (!isset($this->temp
)) {
5362 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5363 //If we've finished a mod, xmlize it an save to db
5364 if (($this->level
== 4) and ($tagName == "MOD")) {
5365 //Prepend XML standard header to info gathered
5366 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5367 //Call to xmlize for this portion of xml data (one MOD)
5368 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5369 $data = xmlize($xml_data,0);
5370 //echo strftime ("%X",time())."<p>"; //Debug
5371 //traverse_xmlize($data); //Debug
5372 //print_object ($GLOBALS['traverse_array']); //Debug
5373 //$GLOBALS['traverse_array']=""; //Debug
5374 //Now, save data to db. We'll use it later
5375 //Get id and modtype from data
5376 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
5377 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
5378 //Only if we've selected to restore it
5379 if (!empty($this->preferences
->mods
[$mod_type]->restore
)) {
5381 $status = backup_putid($this->preferences
->backup_unique_code
,$mod_type,$mod_id,
5383 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
5384 //Create returning info
5385 $ret_info->id
= $mod_id;
5386 $ret_info->modtype
= $mod_type;
5387 $this->info
[] = $ret_info;
5396 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
5397 //Speed up a lot (avoid parse all)
5398 if ($tagName == "MODULES" and $this->level
== 3) {
5399 $this->finished
= true;
5403 $this->tree
[$this->level
] = "";
5405 $this->content
= "";
5409 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
5410 function endElementLogs($parser, $tagName) {
5411 //Check if we are into LOGS zone
5412 if ($this->tree
[3] == "LOGS") {
5413 //if (trim($this->content)) //Debug
5414 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5415 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5416 //Acumulate data to info (content + close tag)
5417 //Reconvert: strip htmlchars again and trim to generate xml data
5418 if (!isset($this->temp
)) {
5421 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5422 //If we've finished a log, xmlize it an save to db
5423 if (($this->level
== 4) and ($tagName == "LOG")) {
5424 //Prepend XML standard header to info gathered
5425 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5426 //Call to xmlize for this portion of xml data (one LOG)
5427 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5428 $data = xmlize($xml_data,0);
5429 //echo strftime ("%X",time())."<p>"; //Debug
5430 //traverse_xmlize($data); //Debug
5431 //print_object ($GLOBALS['traverse_array']); //Debug
5432 //$GLOBALS['traverse_array']=""; //Debug
5433 //Now, save data to db. We'll use it later
5434 //Get id and modtype from data
5435 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
5436 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
5437 //We only save log entries from backup file if they are:
5440 // - Module logs about one restored module
5441 if ($log_module == "course" or
5442 $log_module == "user" or
5443 $this->preferences
->mods
[$log_module]->restore
) {
5447 $status = backup_putid($this->preferences
->backup_unique_code
,"log",$log_id,
5449 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
5450 //Create returning info
5451 $this->info
= $this->counter
;
5458 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
5459 //Speed up a lot (avoid parse all)
5460 if ($tagName == "LOGS" and $this->level
== 3) {
5461 $this->finished
= true;
5466 $this->tree
[$this->level
] = "";
5468 $this->content
= "";
5472 //This is the endTag default handler we use when todo is undefined
5473 function endElement($parser, $tagName) {
5474 if (trim($this->content
)) //Debug
5475 echo "C".str_repeat(" ",($this->level+
2)*2).$this->getContents()."<br />\n"; //Debug
5476 echo $this->level
.str_repeat(" ",$this->level
*2)."</".$tagName."><br />\n"; //Debug
5479 $this->tree
[$this->level
] = "";
5481 $this->content
= "";
5484 //This is the handler to read data contents (simple accumule it)
5485 function characterData($parser, $data) {
5486 $this->content
.= $data;
5490 //This function executes the MoodleParser
5491 function restore_read_xml ($xml_file,$todo,$preferences) {
5495 $xml_parser = xml_parser_create('UTF-8');
5496 $moodle_parser = new MoodleParser();
5497 $moodle_parser->todo
= $todo;
5498 $moodle_parser->preferences
= $preferences;
5499 xml_set_object($xml_parser,$moodle_parser);
5500 //Depending of the todo we use some element_handler or another
5501 if ($todo == "INFO") {
5502 //Define handlers to that zone
5503 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
5504 } else if ($todo == "ROLES") {
5505 // Define handlers to that zone
5506 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
5507 } else if ($todo == "COURSE_HEADER") {
5508 //Define handlers to that zone
5509 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
5510 } else if ($todo == 'BLOCKS') {
5511 //Define handlers to that zone
5512 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
5513 } else if ($todo == "SECTIONS") {
5514 //Define handlers to that zone
5515 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
5516 } else if ($todo == 'FORMATDATA') {
5517 //Define handlers to that zone
5518 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
5519 } else if ($todo == "METACOURSE") {
5520 //Define handlers to that zone
5521 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
5522 } else if ($todo == "GRADEBOOK") {
5523 //Define handlers to that zone
5524 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
5525 } else if ($todo == "USERS") {
5526 //Define handlers to that zone
5527 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
5528 } else if ($todo == "MESSAGES") {
5529 //Define handlers to that zone
5530 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
5531 } else if ($todo == "QUESTIONS") {
5532 //Define handlers to that zone
5533 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
5534 } else if ($todo == "SCALES") {
5535 //Define handlers to that zone
5536 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
5537 } else if ($todo == "GROUPS") {
5538 //Define handlers to that zone
5539 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
5540 } else if ($todo == "GROUPINGS") {
5541 //Define handlers to that zone
5542 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
5543 } else if ($todo == "EVENTS") {
5544 //Define handlers to that zone
5545 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
5546 } else if ($todo == "MODULES") {
5547 //Define handlers to that zone
5548 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
5549 } else if ($todo == "LOGS") {
5550 //Define handlers to that zone
5551 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
5553 //Define default handlers (must no be invoked when everything become finished)
5554 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
5556 xml_set_character_data_handler($xml_parser, "characterData");
5557 $fp = fopen($xml_file,"r")
5560 while ($data = fread($fp, 4096) and !$moodle_parser->finished
)
5561 xml_parse($xml_parser, $data, feof($fp))
5562 or die(sprintf("XML error: %s at line %d",
5563 xml_error_string(xml_get_error_code($xml_parser)),
5564 xml_get_current_line_number($xml_parser)));
5567 //Get info from parser
5568 $info = $moodle_parser->info
;
5571 xml_parser_free($xml_parser);
5573 if ($status && !empty($info)) {
5581 * @param string $errorstr passed by reference, if silent is true,
5582 * errorstr will be populated and this function will return false rather than calling error() or notify()
5583 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
5584 * redirect to the next step in the restore process, instead will return $backup_unique_code
5586 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
5588 global $CFG, $SESSION;
5590 //Prepend dataroot to variable to have the absolute path
5591 $file = $CFG->dataroot
."/".$file;
5593 if (!defined('RESTORE_SILENTLY')) {
5594 //Start the main table
5595 echo "<table cellpadding=\"5\">";
5602 //Check the file exists
5603 if (!is_file($file)) {
5604 if (!defined('RESTORE_SILENTLY')) {
5605 error ("File not exists ($file)");
5607 $errorstr = "File not exists ($file)";
5612 //Check the file name ends with .zip
5613 if (!substr($file,-4) == ".zip") {
5614 if (!defined('RESTORE_SILENTLY')) {
5615 error ("File has an incorrect extension");
5617 $errorstr = 'File has an incorrect extension';
5622 //Now calculate the unique_code for this restore
5623 $backup_unique_code = time();
5625 //Now check and create the backup dir (if it doesn't exist)
5626 if (!defined('RESTORE_SILENTLY')) {
5627 echo "<li>".get_string("creatingtemporarystructures").'</li>';
5629 $status = check_and_create_backup_dir($backup_unique_code);
5632 $status = clear_backup_dir($backup_unique_code);
5635 //Now delete old data and directories under dataroot/temp/backup
5637 if (!defined('RESTORE_SILENTLY')) {
5638 echo "<li>".get_string("deletingolddata").'</li>';
5640 $status = backup_delete_old_data();
5643 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
5645 if (!defined('RESTORE_SILENTLY')) {
5646 echo "<li>".get_string("copyingzipfile").'</li>';
5648 if (! $status = backup_copy_file($file,$CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
5649 if (!defined('RESTORE_SILENTLY')) {
5650 notify("Error copying backup file. Invalid name or bad perms.");
5652 $errorstr = "Error copying backup file. Invalid name or bad perms";
5658 //Now unzip the file
5660 if (!defined('RESTORE_SILENTLY')) {
5661 echo "<li>".get_string("unzippingbackup").'</li>';
5663 if (! $status = restore_unzip ($CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
5664 if (!defined('RESTORE_SILENTLY')) {
5665 notify("Error unzipping backup file. Invalid zip file.");
5667 $errorstr = "Error unzipping backup file. Invalid zip file.";
5673 //Check for Blackboard backups and convert
5675 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
5676 if (!defined('RESTORE_SILENTLY')) {
5677 echo "<li>".get_string("checkingforbbexport").'</li>';
5679 $status = blackboard_convert($CFG->dataroot
."/temp/backup/".$backup_unique_code);
5682 //Now check for the moodle.xml file
5684 $xml_file = $CFG->dataroot
."/temp/backup/".$backup_unique_code."/moodle.xml";
5685 if (!defined('RESTORE_SILENTLY')) {
5686 echo "<li>".get_string("checkingbackup").'</li>';
5688 if (! $status = restore_check_moodle_file ($xml_file)) {
5689 if (!is_file($xml_file)) {
5690 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
5692 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
5694 if (!defined('RESTORE_SILENTLY')) {
5703 $course_header = "";
5705 //Now read the info tag (all)
5707 if (!defined('RESTORE_SILENTLY')) {
5708 echo "<li>".get_string("readinginfofrombackup").'</li>';
5710 //Reading info from file
5711 $info = restore_read_xml_info ($xml_file);
5712 //Reading course_header from file
5713 $course_header = restore_read_xml_course_header ($xml_file);
5716 if (!defined('RESTORE_SILENTLY')) {
5720 //End the main table
5725 //We compare Moodle's versions
5726 if ($CFG->version
< $info->backup_moodle_version
&& $status) {
5727 $message->serverversion
= $CFG->version
;
5728 $message->serverrelease
= $CFG->release
;
5729 $message->backupversion
= $info->backup_moodle_version
;
5730 $message->backuprelease
= $info->backup_moodle_release
;
5731 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
5735 //Now we print in other table, the backup and the course it contains info
5736 if ($info and $course_header and $status) {
5737 //First, the course info
5738 if (!defined('RESTORE_SILENTLY')) {
5739 $status = restore_print_course_header($course_header);
5741 //Now, the backup info
5743 if (!defined('RESTORE_SILENTLY')) {
5744 $status = restore_print_info($info);
5749 //Save course header and info into php session
5751 $SESSION->info
= $info;
5752 $SESSION->course_header
= $course_header;
5755 //Finally, a little form to continue
5756 //with some hidden fields
5758 if (!defined('RESTORE_SILENTLY')) {
5759 echo "<br /><div style='text-align:center'>";
5760 $hidden["backup_unique_code"] = $backup_unique_code;
5761 $hidden["launch"] = "form";
5762 $hidden["file"] = $file;
5763 $hidden["id"] = $id;
5764 print_single_button("restore.php", $hidden, get_string("continue"),"post");
5768 if (empty($noredirect)) {
5769 redirect($CFG->wwwroot
.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
5771 return $backup_unique_code;
5777 if (!defined('RESTORE_SILENTLY')) {
5778 error ("An error has ocurred");
5780 $errorstr = "An error has occured"; // helpful! :P
5787 function restore_setup_for_check(&$restore,$backup_unique_code) {
5789 $restore->backup_unique_code
=$backup_unique_code;
5790 $restore->users
= 2; // yuk
5791 $restore->course_files
= $SESSION->restore
->restore_course_files
;
5792 if ($allmods = get_records("modules")) {
5793 foreach ($allmods as $mod) {
5794 $modname = $mod->name
;
5795 $var = "restore_".$modname;
5796 //Now check that we have that module info in the backup file
5797 if (isset($SESSION->info
->mods
[$modname]) && $SESSION->info
->mods
[$modname]->backup
== "true") {
5805 function backup_to_restore_array($backup,$k=0) {
5806 if (is_array($backup) ) {
5807 foreach ($backup as $key => $value) {
5808 $newkey = str_replace('backup','restore',$key);
5809 $restore[$newkey] = backup_to_restore_array($value,$key);
5812 else if (is_object($backup)) {
5813 $tmp = get_object_vars($backup);
5814 foreach ($tmp as $key => $value) {
5815 $newkey = str_replace('backup','restore',$key);
5816 $restore->$newkey = backup_to_restore_array($value,$key);
5820 $newkey = str_replace('backup','restore',$k);
5827 * compatibility function
5828 * checks for per-instance backups AND
5829 * older per-module backups
5830 * and returns whether userdata has been selected.
5832 function restore_userdata_selected($restore,$modname,$modid) {
5833 // check first for per instance array
5834 if (!empty($restore->mods
[$modname]->granular
)) { // supports per instance
5835 return array_key_exists($modid,$restore->mods
[$modname]->instances
)
5836 && !empty($restore->mods
[$modname]->instances
[$modid]->userinfo
);
5839 print_object($restore->mods
[$modname]);
5840 return !empty($restore->mods
[$modname]->userinfo
);
5843 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
5848 //Checks for the required files/functions to restore every module
5850 if ($allmods = get_records("modules") ) {
5851 foreach ($allmods as $mod) {
5852 $modname = $mod->name
;
5853 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
5854 //If file exists and we have selected to restore that type of module
5855 if ((file_exists($modfile)) and ($restore->mods
[$modname]->restore
)) {
5856 include_once($modfile);
5861 if (!defined('RESTORE_SILENTLY')) {
5862 //Start the main table
5863 echo "<table cellpadding=\"5\">";
5870 //Localtion of the xml file
5871 $xml_file = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/moodle.xml";
5873 //If we've selected to restore into new course
5874 //create it (course)
5875 //Saving conversion id variables into backup_tables
5876 if ($restore->restoreto
== 2) {
5877 if (!defined('RESTORE_SILENTLY')) {
5878 echo '<li>'.get_string('creatingnewcourse') . '</li>';
5880 $oldidnumber = $course_header->course_idnumber
;
5881 if (!$status = restore_create_new_course($restore,$course_header)) {
5882 if (!defined('RESTORE_SILENTLY')) {
5883 notify("Error while creating the new empty course.");
5885 $errorstr = "Error while creating the new empty course.";
5890 //Print course fullname and shortname and category
5892 if (!defined('RESTORE_SILENTLY')) {
5894 echo "<li>".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
5895 echo "<li>".get_string("category").": ".$course_header->category
->name
.'</li>';
5896 if (!empty($oldidnumber)) {
5897 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
5900 //Put the destination course_id
5902 $restore->course_id
= $course_header->course_id
;
5905 if ($status = restore_open_html($restore,$course_header)){
5906 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
5910 $course = get_record("course","id",$restore->course_id
);
5912 if (!defined('RESTORE_SILENTLY')) {
5913 echo "<li>".get_string("usingexistingcourse");
5915 echo "<li>".get_string("from").": ".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
5916 echo "<li>".get_string("to").": ". format_string($course->fullname
) ." (".format_string($course->shortname
).")".'</li>';
5917 if (($restore->deleting
)) {
5918 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
5920 echo "<li>".get_string("addingdatatoexisting").'</li>';
5924 //If we have selected to restore deleting, we do it now.
5925 if ($restore->deleting
) {
5926 if (!defined('RESTORE_SILENTLY')) {
5927 echo "<li>".get_string("deletingolddata").'</li>';
5929 $status = remove_course_contents($restore->course_id
,false) and
5930 delete_dir_contents($CFG->dataroot
."/".$restore->course_id
,"backupdata");
5932 //Now , this situation is equivalent to the "restore to new course" one (we
5933 //have a course record and nothing more), so define it as "to new course"
5934 $restore->restoreto
= 2;
5936 if (!defined('RESTORE_SILENTLY')) {
5937 notify("An error occurred while deleting some of the course contents.");
5939 $errrostr = "An error occurred while deleting some of the course contents.";
5945 if (!defined('RESTORE_SILENTLY')) {
5946 notify("Error opening existing course.");
5949 $errorstr = "Error opening existing course.";
5955 //Now create the course_sections and their associated course_modules
5958 if ($restore->restoreto
== 2) {
5959 if (!defined('RESTORE_SILENTLY')) {
5960 echo "<li>".get_string("creatingsections");
5962 if (!$status = restore_create_sections($restore,$xml_file)) {
5963 if (!defined('RESTORE_SILENTLY')) {
5964 notify("Error creating sections in the existing course.");
5966 $errorstr = "Error creating sections in the existing course.";
5970 if (!defined('RESTORE_SILENTLY')) {
5973 //Into existing course
5974 } else if ($restore->restoreto
== 0 or $restore->restoreto
== 1) {
5975 if (!defined('RESTORE_SILENTLY')) {
5976 echo "<li>".get_string("checkingsections");
5978 if (!$status = restore_create_sections($restore,$xml_file)) {
5979 if (!defined('RESTORE_SILENTLY')) {
5980 notify("Error creating sections in the existing course.");
5982 $errorstr = "Error creating sections in the existing course.";
5986 if (!defined('RESTORE_SILENTLY')) {
5991 if (!defined('RESTORE_SILENTLY')) {
5992 notify("Neither a new course or an existing one was specified.");
5995 $errorstr = "Neither a new course or an existing one was specified.";
6001 //Now create users as needed
6002 if ($status and ($restore->users
== 0 or $restore->users
== 1)) {
6003 if (!defined('RESTORE_SILENTLY')) {
6004 echo "<li>".get_string("creatingusers")."<br />";
6006 if (!$status = restore_create_users($restore,$xml_file)) {
6007 if (!defined('RESTORE_SILENTLY')) {
6008 notify("Could not restore users.");
6010 $errorstr = "Could not restore users.";
6015 //Now print info about the work done
6017 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
6018 where backup_code = '$restore->backup_unique_code' and
6019 table_name = 'user'");
6027 //Iterate, filling counters
6028 foreach ($recs as $rec) {
6029 //Get full record, using backup_getids
6030 $record = backup_getid($restore->backup_unique_code
,"user",$rec->old_id
);
6031 if (strpos($record->info
,"new") !== false) {
6034 if (strpos($record->info
,"exists") !== false) {
6037 if (strpos($record->info
,"student") !== false) {
6039 } else if (strpos($record->info
,"teacher") !== false) {
6044 if ($counter %
10 == 0) {
6045 if (!defined('RESTORE_SILENTLY')) {
6047 if ($counter %
200 == 0) {
6054 if (!defined('RESTORE_SILENTLY')) {
6055 //Now print information gathered
6056 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
6058 echo "<li>".get_string("students").": ".$student_count.'</li>';
6059 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
6063 if (!defined('RESTORE_SILENTLY')) {
6064 notify("No users were found!");
6065 } // no need to return false here, it's recoverable.
6069 if (!defined('RESTORE_SILENTLY')) {
6074 //Now create metacourse info
6075 if ($status and $restore->metacourse
) {
6076 //Only to new courses!
6077 if ($restore->restoreto
== 2) {
6078 if (!defined('RESTORE_SILENTLY')) {
6079 echo "<li>".get_string("creatingmetacoursedata");
6081 if (!$status = restore_create_metacourse($restore,$xml_file)) {
6082 if (!defined('RESTORE_SILENTLY')) {
6083 notify("Error creating metacourse in the course.");
6085 $errorstr = "Error creating metacourse in the course.";
6089 if (!defined('RESTORE_SILENTLY')) {
6096 //Now create categories and questions as needed
6097 if ($status and ($restore->mods
['quiz']->restore
)) {
6098 include_once("$CFG->dirroot/question/restorelib.php");
6099 if (!defined('RESTORE_SILENTLY')) {
6100 echo "<li>".get_string("creatingcategoriesandquestions");
6103 if (!$status = restore_create_questions($restore,$xml_file)) {
6104 if (!defined('RESTORE_SILENTLY')) {
6105 notify("Could not restore categories and questions!");
6107 $errorstr = "Could not restore categories and questions!";
6111 if (!defined('RESTORE_SILENTLY')) {
6116 //Now create user_files as needed
6117 if ($status and ($restore->user_files
)) {
6118 if (!defined('RESTORE_SILENTLY')) {
6119 echo "<li>".get_string("copyinguserfiles");
6121 if (!$status = restore_user_files($restore)) {
6122 if (!defined('RESTORE_SILENTLY')) {
6123 notify("Could not restore user files!");
6125 $errorstr = "Could not restore user files!";
6129 //If all is ok (and we have a counter)
6130 if ($status and ($status !== true)) {
6131 //Inform about user dirs created from backup
6132 if (!defined('RESTORE_SILENTLY')) {
6134 echo "<li>".get_string("userzones").": ".$status;
6138 if (!defined('RESTORE_SILENTLY')) {
6143 //Now create course files as needed
6144 if ($status and ($restore->course_files
)) {
6145 if (!defined('RESTORE_SILENTLY')) {
6146 echo "<li>".get_string("copyingcoursefiles");
6148 if (!$status = restore_course_files($restore)) {
6149 if (empty($status)) {
6150 notify("Could not restore course files!");
6152 $errorstr = "Could not restore course files!";
6156 //If all is ok (and we have a counter)
6157 if ($status and ($status !== true)) {
6158 //Inform about user dirs created from backup
6159 if (!defined('RESTORE_SILENTLY')) {
6161 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
6165 if (!defined('RESTORE_SILENTLY')) {
6170 //Now create messages as needed
6171 if ($status and ($restore->messages
)) {
6172 if (!defined('RESTORE_SILENTLY')) {
6173 echo "<li>".get_string("creatingmessagesinfo");
6175 if (!$status = restore_create_messages($restore,$xml_file)) {
6176 if (!defined('RESTORE_SILENTLY')) {
6177 notify("Could not restore messages!");
6179 $errorstr = "Could not restore messages!";
6183 if (!defined('RESTORE_SILENTLY')) {
6188 //Now create scales as needed
6190 if (!defined('RESTORE_SILENTLY')) {
6191 echo "<li>".get_string("creatingscales");
6193 if (!$status = restore_create_scales($restore,$xml_file)) {
6194 if (!defined('RESTORE_SILENTLY')) {
6195 notify("Could not restore custom scales!");
6197 $errorstr = "Could not restore custom scales!";
6201 if (!defined('RESTORE_SILENTLY')) {
6206 //Now create groups as needed
6208 if (!defined('RESTORE_SILENTLY')) {
6209 echo "<li>".get_string("creatinggroups");
6211 if (!$status = restore_create_groups($restore,$xml_file)) {
6212 if (!defined('RESTORE_SILENTLY')) {
6213 notify("Could not restore groups!");
6215 $errorstr = "Could not restore groups!";
6219 if (!defined('RESTORE_SILENTLY')) {
6224 //Now create groupings as needed
6226 if (!defined('RESTORE_SILENTLY')) {
6227 echo "<li>".get_string("creatinggroupings");
6229 if (!$status = restore_create_groupings($restore,$xml_file)) {
6230 if (!defined('RESTORE_SILENTLY')) {
6231 notify("Could not restore groupings!");
6233 $errorstr = "Could not restore groupings!";
6237 if (!defined('RESTORE_SILENTLY')) {
6242 //Now create events as needed
6244 if (!defined('RESTORE_SILENTLY')) {
6245 echo "<li>".get_string("creatingevents");
6247 if (!$status = restore_create_events($restore,$xml_file)) {
6248 if (!defined('RESTORE_SILENTLY')) {
6249 notify("Could not restore course events!");
6251 $errorstr = "Could not restore course events!";
6255 if (!defined('RESTORE_SILENTLY')) {
6260 //Now create course modules as needed
6262 if (!defined('RESTORE_SILENTLY')) {
6263 echo "<li>".get_string("creatingcoursemodules");
6265 if (!$status = restore_create_modules($restore,$xml_file)) {
6266 if (!defined('RESTORE_SILENTLY')) {
6267 notify("Could not restore modules!");
6269 $errorstr = "Could not restore modules!";
6273 if (!defined('RESTORE_SILENTLY')) {
6278 //Now create gradebook as needed -- AFTER modules!!!
6280 if (!defined('RESTORE_SILENTLY')) {
6281 echo "<li>".get_string("creatinggradebook");
6283 if (!$status = restore_create_gradebook($restore,$xml_file)) {
6284 if (!defined('RESTORE_SILENTLY')) {
6285 notify("Could not restore gradebook!");
6287 $errorstr = "Could not restore gradebook!";
6291 if (!defined('RESTORE_SILENTLY')) {
6296 //Bring back the course blocks -- do it AFTER the modules!!!
6298 //If we are deleting and bringing into a course or making a new course, same situation
6299 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
6300 if (!defined('RESTORE_SILENTLY')) {
6301 echo '<li>'.get_string('creatingblocks');
6303 $course_header->blockinfo
= !empty($course_header->blockinfo
) ?
$course_header->blockinfo
: NULL;
6304 if (!$status = restore_create_blocks($restore, $info->backup_block_format
, $course_header->blockinfo
, $xml_file)) {
6305 if (!defined('RESTORE_SILENTLY')) {
6306 notify('Error while creating the course blocks');
6308 $errorstr = "Error while creating the course blocks";
6312 if (!defined('RESTORE_SILENTLY')) {
6319 //If we are deleting and bringing into a course or making a new course, same situation
6320 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
6321 if (!defined('RESTORE_SILENTLY')) {
6322 echo '<li>'.get_string('courseformatdata');
6324 if (!$status = restore_set_format_data($restore, $xml_file)) {
6325 $error = "Error while setting the course format data";
6326 if (!defined('RESTORE_SILENTLY')) {
6333 if (!defined('RESTORE_SILENTLY')) {
6339 //Now create log entries as needed
6340 if ($status and ($restore->logs
)) {
6341 if (!defined('RESTORE_SILENTLY')) {
6342 echo "<li>".get_string("creatinglogentries");
6344 if (!$status = restore_create_logs($restore,$xml_file)) {
6345 if (!defined('RESTORE_SILENTLY')) {
6346 notify("Could not restore logs!");
6348 $errorstr = "Could not restore logs!";
6352 if (!defined('RESTORE_SILENTLY')) {
6357 //Now, if all is OK, adjust the instance field in course_modules !!
6359 if (!defined('RESTORE_SILENTLY')) {
6360 echo "<li>".get_string("checkinginstances");
6362 if (!$status = restore_check_instances($restore)) {
6363 if (!defined('RESTORE_SILENTLY')) {
6364 notify("Could not adjust instances in course_modules!");
6366 $errorstr = "Could not adjust instances in course_modules!";
6370 if (!defined('RESTORE_SILENTLY')) {
6375 //Now, if all is OK, adjust activity events
6377 if (!defined('RESTORE_SILENTLY')) {
6378 echo "<li>".get_string("refreshingevents");
6380 if (!$status = restore_refresh_events($restore)) {
6381 if (!defined('RESTORE_SILENTLY')) {
6382 notify("Could not refresh events for activities!");
6384 $errorstr = "Could not refresh events for activities!";
6388 if (!defined('RESTORE_SILENTLY')) {
6393 //Now, if all is OK, adjust inter-activity links
6395 if (!defined('RESTORE_SILENTLY')) {
6396 echo "<li>".get_string("decodinginternallinks");
6398 if (!$status = restore_decode_content_links($restore)) {
6399 if (!defined('RESTORE_SILENTLY')) {
6400 notify("Could not decode content links!");
6402 $errorstr = "Could not decode content links!";
6406 if (!defined('RESTORE_SILENTLY')) {
6411 //Now, with backup files prior to version 2005041100,
6412 //convert all the wiki texts in the course to markdown
6413 if ($status && $restore->backup_version
< 2005041100) {
6414 if (!defined('RESTORE_SILENTLY')) {
6415 echo "<li>".get_string("convertingwikitomarkdown");
6417 if (!$status = restore_convert_wiki2markdown($restore)) {
6418 if (!defined('RESTORE_SILENTLY')) {
6419 notify("Could not convert wiki texts to markdown!");
6421 $errorstr = "Could not convert wiki texts to markdown!";
6425 if (!defined('RESTORE_SILENTLY')) {
6430 /*******************************************************************************
6431 ************* Restore of Roles and Capabilities happens here ******************
6432 *******************************************************************************/
6433 $status = restore_create_roles($restore, $xml_file);
6434 $status = restore_roles_settings($restore, $xml_file);
6436 //Now if all is OK, update:
6437 // - course modinfo field
6438 // - categories table
6439 // - add user as teacher
6441 if (!defined('RESTORE_SILENTLY')) {
6442 echo "<li>".get_string("checkingcourse");
6445 rebuild_course_cache($restore->course_id
);
6447 $course = get_record("course","id",$restore->course_id
);
6448 fix_course_sortorder();
6449 // Check if the user has course update capability in the newly restored course
6450 // there is no need to load his capabilities again, because restore_roles_settings
6451 // would have loaded it anyway, if there is any assignments.
6453 $newcontext = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
6454 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
6455 // fix for MDL-9065, use the new config setting if exists
6456 if ($CFG->creatornewroleid
) {
6457 role_assign($CFG->creatornewroleid
, $USER->id
, 0, $newcontext->id
);
6459 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW
, get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
6460 if ($legacyteacher = array_shift($legacyteachers)) {
6461 role_assign($legacyteacher->id
, $USER->id
, 0, $newcontext->id
);
6464 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
6468 if (!defined('RESTORE_SILENTLY')) {
6473 //Cleanup temps (files and db)
6475 if (!defined('RESTORE_SILENTLY')) {
6476 echo "<li>".get_string("cleaningtempdata");
6478 if (!$status = clean_temp_data ($restore)) {
6479 if (!defined('RESTORE_SILENTLY')) {
6480 notify("Could not clean up temporary data from files and database");
6482 $errorstr = "Could not clean up temporary data from files and database";
6486 if (!defined('RESTORE_SILENTLY')) {
6491 if ($status = restore_close_html($restore)){
6492 if (!defined('RESTORE_SILENTLY')) {
6493 echo '<li>Closing the Restorelog.html file.</li>';
6497 if (!defined('RESTORE_SILENTLY')) {
6498 notify("Could not close the restorelog.html file");
6501 $errorstr = "Could not close the restorelog.html file";
6506 if (!defined('RESTORE_SILENTLY')) {
6510 //End the main table
6517 //Create, open and write header of the html log file
6518 function restore_open_html($restore,$course_header) {
6524 //Open file for writing
6525 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
6526 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
6527 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
6529 $status = check_dir_exists($dest_dir,true);
6530 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
6531 //Add the stylesheet
6532 $stylesheetshtml = '';
6533 foreach ($CFG->stylesheets
as $stylesheet) {
6534 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
6536 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
6537 $languagehtml = get_html_lang($dir=true);
6539 //Write the header in the new logging file
6540 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
6541 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
6542 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
6543 fwrite ($restorelog_file,"<head>");
6544 fwrite ($restorelog_file,$stylesheetshtml);
6545 fwrite ($restorelog_file,"<title>".$course_header->course_shortname
." Restored </title>");
6546 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
6547 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname
." The FullName is now - ".$course_header->course_fullname
."<br/><br/>");
6548 $startdate = addslashes($course_header->course_startdate
);
6549 $date = usergetdate($startdate);
6550 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
6551 $startdate +
= $restore->course_startdateoffset
;
6552 $date = usergetdate($startdate);
6553 fwrite ($restorelog_file," This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
6556 return $restorelog_file;
6561 //Create & close footer of the html log file
6562 function restore_close_html($restore) {
6568 //Open file for writing
6569 //First, check that course_id/backupdata folder exists in CFG->dataroot
6570 $dest_dir = $CFG->dataroot
."/".$restore->course_id
."/backupdata";
6571 $status = check_dir_exists($dest_dir, true, true);
6572 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
6573 //Write the footer to close the logging file
6574 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
6575 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
6578 return $restorelog_file;
6584 /********************** Roles and Capabilities Related Functions *******************************/
6586 /* Yu: Note recovering of role assignments/overrides need to take place after
6587 users have been recovered, i.e. after we get their new_id, and after all
6588 roles have been recreated or mapped. Contexts can be created on the fly.
6589 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
6590 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
6591 once roles and users have been restored.
6595 * This function restores all the needed roles for this course
6596 * i.e. roles with an assignment in any of the mods or blocks,
6597 * roles assigned on any user (e.g. parent role) and roles
6598 * assigned at course levle
6599 * This function should check for duplicate roles first
6600 * It isn't now, just overwriting
6602 function restore_create_roles($restore, $xmlfile) {
6603 if (!defined('RESTORE_SILENTLY')) {
6604 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
6606 $info = restore_read_xml_roles($xmlfile);
6608 $sitecontext = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
6610 // the following code creates new roles
6611 // but we could use more intelligent detection, and role mapping
6612 // get role mapping info from $restore
6613 $rolemappings = array();
6615 if (!empty($restore->rolesmapping
)) {
6616 $rolemappings = $restore->rolesmapping
;
6618 // $info->roles will be empty for backups pre 1.7
6619 if (isset($info->roles
) && $info->roles
) {
6621 foreach ($info->roles
as $oldroleid=>$roledata) {
6622 if (empty($restore->rolesmapping
)) {
6623 // if this is empty altogether, we came from import or there's no roles used in course at all
6624 // in this case, write the same oldid as this is the same site
6625 // no need to do mapping
6626 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
6627 $oldroleid); // adding a new id
6628 continue; // do not create additonal roles;
6630 // first we check if the roles are in the mappings
6631 // if so, we just do a mapping i.e. update oldids table
6632 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
6633 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
6634 $rolemappings[$oldroleid]); // adding a new id
6638 // code to make new role name/short name if same role name or shortname exists
6639 $fullname = $roledata->name
;
6640 $shortname = $roledata->shortname
;
6641 $currentfullname = "";
6642 $currentshortname = "";
6647 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
6648 $suffixshort = "_".$counter;
6653 $currentfullname = $fullname.$suffixfull;
6654 // Limit the size of shortname - database column accepts <= 15 chars
6655 $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
6656 $coursefull = get_record("role","name",addslashes($currentfullname));
6657 $courseshort = get_record("role","shortname",addslashes($currentshortname));
6659 } while ($coursefull ||
$courseshort);
6661 $roledata->name
= $currentfullname;
6662 $roledata->shortname
= $currentshortname;
6664 // done finding a unique name
6666 $newroleid = create_role(addslashes($roledata->name
),addslashes($roledata->shortname
),'');
6667 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
6668 $newroleid); // adding a new id
6669 foreach ($roledata->capabilities
as $capability) {
6671 $roleinfo = new object();
6672 $roleinfo = (object)$capability;
6673 $roleinfo->contextid
= $sitecontext->id
;
6674 $roleinfo->capability
= $capability->name
;
6675 $roleinfo->roleid
= $newroleid;
6677 insert_record('role_capabilities', $roleinfo);
6686 * this function restores role assignments and role overrides
6687 * in course/user/block/mod level, it passed through
6688 * the xml file again
6690 function restore_roles_settings($restore, $xmlfile) {
6691 // data pulls from course, mod, user, and blocks
6693 /*******************************************************
6694 * Restoring from course level assignments *
6695 *******************************************************/
6696 if (!defined('RESTORE_SILENTLY')) {
6697 echo "<li>".get_string("creatingcourseroles").'</li>';
6699 $course = restore_read_xml_course_header($xmlfile);
6701 if (!isset($restore->rolesmapping
)) {
6702 $isimport = true; // course import from another course, or course with no role assignments
6704 $isimport = false; // course restore with role assignments
6707 if (!empty($course->roleassignments
) && !$isimport) {
6708 $courseassignments = $course->roleassignments
;
6710 foreach ($courseassignments as $oldroleid => $courseassignment) {
6711 restore_write_roleassignments($restore, $courseassignment->assignments
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
6714 /*****************************************************
6715 * Restoring from course level overrides *
6716 *****************************************************/
6718 if (!empty($course->roleoverrides
) && !$isimport) {
6719 $courseoverrides = $course->roleoverrides
;
6720 foreach ($courseoverrides as $oldroleid => $courseoverride) {
6721 // if not importing into exiting course, or creating new role, we are ok
6722 // local course overrides to be respected (i.e. restored course overrides ignored)
6723 if ($restore->restoreto
!= 1 ||
empty($restore->rolesmapping
[$oldroleid])) {
6724 restore_write_roleoverrides($restore, $courseoverride->overrides
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
6729 /*******************************************************
6730 * Restoring role assignments/overrdies *
6731 * from module level assignments *
6732 *******************************************************/
6734 if (!defined('RESTORE_SILENTLY')) {
6735 echo "<li>".get_string("creatingmodroles").'</li>';
6737 $sections = restore_read_xml_sections($xmlfile);
6738 $secs = $sections->sections
;
6740 foreach ($secs as $section) {
6741 if (isset($section->mods
)) {
6742 foreach ($section->mods
as $modid=>$mod) {
6743 if (isset($mod->roleassignments
) && !$isimport) {
6744 foreach ($mod->roleassignments
as $oldroleid=>$modassignment) {
6745 restore_write_roleassignments($restore, $modassignment->assignments
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
6748 // role overrides always applies, in import or backup/restore
6749 if (isset($mod->roleoverrides
)) {
6750 foreach ($mod->roleoverrides
as $oldroleid=>$modoverride) {
6751 restore_write_roleoverrides($restore, $modoverride->overrides
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
6758 /*************************************************
6759 * Restoring assignments from blocks level *
6760 * role assignments/overrides *
6761 *************************************************/
6763 if ($restore->restoreto
!= 1) { // skip altogether if restoring to exisitng course by adding
6764 if (!defined('RESTORE_SILENTLY')) {
6765 echo "<li>".get_string("creatingblocksroles").'</li>';
6767 $blocks = restore_read_xml_blocks($xmlfile);
6768 if (isset($blocks->instances
)) {
6769 foreach ($blocks->instances
as $instance) {
6770 if (isset($instance->roleassignments
) && !$isimport) {
6771 foreach ($instance->roleassignments
as $oldroleid=>$blockassignment) {
6772 restore_write_roleassignments($restore, $blockassignment->assignments
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
6776 // likewise block overrides should always be restored like mods
6777 if (isset($instance->roleoverrides
)) {
6778 foreach ($instance->roleoverrides
as $oldroleid=>$blockoverride) {
6779 restore_write_roleoverrides($restore, $blockoverride->overrides
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
6785 /************************************************
6786 * Restoring assignments from userid level *
6787 * role assignments/overrides *
6788 ************************************************/
6789 if (!defined('RESTORE_SILENTLY')) {
6790 echo "<li>".get_string("creatinguserroles").'</li>';
6792 $info = restore_read_xml_users($restore, $xmlfile);
6793 if (!empty($info->users
) && !$isimport) { // no need to restore user assignments for imports (same course)
6794 //For each user, take its info from backup_ids
6795 foreach ($info->users
as $userid) {
6796 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
6797 if (isset($rec->info
->roleassignments
)) {
6798 foreach ($rec->info
->roleassignments
as $oldroleid=>$userassignment) {
6799 restore_write_roleassignments($restore, $userassignment->assignments
, "user", CONTEXT_USER
, $userid, $oldroleid);
6802 if (isset($rec->info
->roleoverrides
)) {
6803 foreach ($rec->info
->roleoverrides
as $oldroleid=>$useroverride) {
6804 restore_write_roleoverrides($restore, $useroverride->overrides
, "user", CONTEXT_USER
, $userid, $oldroleid);
6813 // auxillary function to write role assignments read from xml to db
6814 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
6816 $role = backup_getid($restore->backup_unique_code
, "role", $oldroleid);
6818 foreach ($assignments as $assignment) {
6820 $olduser = backup_getid($restore->backup_unique_code
,"user",$assignment->userid
);
6821 //Oh dear, $olduser... can be an object, $obj->string or bool!
6822 if (!$olduser ||
(is_string($olduser->info
) && $olduser->info
== "notincourse")) { // it's possible that user is not in the course
6825 $assignment->userid
= $olduser->new_id
; // new userid here
6826 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$assignment->modifierid
);
6827 $assignment->modifierid
= !empty($oldmodifier->new_id
) ?
$oldmodifier->new_id
: 0; // new modifier id here
6828 $assignment->roleid
= $role->new_id
; // restored new role id
6830 // hack to make the correct contextid for course level imports
6831 if ($contextlevel == CONTEXT_COURSE
) {
6832 $oldinstance->new_id
= $restore->course_id
;
6834 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
6837 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
6838 $assignment->contextid
= $newcontext->id
; // new context id
6839 // might already have same assignment
6840 role_assign($assignment->roleid
, $assignment->userid
, 0, $assignment->contextid
, $assignment->timestart
, $assignment->timeend
, $assignment->hidden
, $assignment->enrol
);
6845 // auxillary function to write role assignments read from xml to db
6846 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
6848 // it is possible to have an override not relevant to this course context.
6849 // should be ignored(?)
6850 if (!$role = backup_getid($restore->backup_unique_code
, "role", $oldroleid)) {
6854 foreach ($overrides as $override) {
6855 $override->capability
= $override->name
;
6856 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$override->modifierid
);
6857 $override->modifierid
= $oldmodifier->new_id?
$oldmodifier->new_id
:0; // new modifier id here
6858 $override->roleid
= $role->new_id
; // restored new role id
6860 // hack to make the correct contextid for course level imports
6861 if ($contextlevel == CONTEXT_COURSE
) {
6862 $oldinstance->new_id
= $restore->course_id
;
6864 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
6867 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
6868 $override->contextid
= $newcontext->id
; // new context id
6869 // might already have same override
6870 if (!get_record('role_capabilities', 'capability', $override->capability
, 'roleid', $override->roleid
, 'contextid', $override->contextid
)) {
6871 insert_record('role_capabilities', $override);
6875 //write activity date changes to the html log file, and update date values in the the xml array
6876 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
6881 // loop through time fields in $TAGS
6882 foreach ($TAGS as $TAG) {
6884 // check $TAG has a sensible value
6885 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
6887 if ($openlog==false) {
6888 $openlog = true; // only come through here once
6890 // open file for writing
6891 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
6892 check_dir_exists($course_dir, true);
6893 $restorelog = fopen("$course_dir/restorelog.html", "a");
6895 // start output for this record
6896 $msg = new stdClass();
6897 $msg->recordtype
= $recordtype;
6898 $msg->recordname
= $xml[$NAMETAG][0]['#'];
6899 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
6902 // write old date to $restorelog
6903 $value = $xml[$TAG][0]['#'];
6904 $date = usergetdate($value);
6906 $msg = new stdClass();
6908 $msg->weekday
= $date['weekday'];
6909 $msg->mday
= $date['mday'];
6910 $msg->month
= $date['month'];
6911 $msg->year
= $date['year'];
6912 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
6914 // write new date to $restorelog
6915 $value +
= $restore->course_startdateoffset
;
6916 $date = usergetdate($value);
6918 $msg = new stdClass();
6920 $msg->weekday
= $date['weekday'];
6921 $msg->mday
= $date['mday'];
6922 $msg->month
= $date['month'];
6923 $msg->year
= $date['year'];
6924 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
6926 // update $value in $xml tree for calling module
6927 $xml[$TAG][0]['#'] = "$value";
6930 // close the restore log, if it was opened
6932 fclose($restorelog);