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')) {
73 foreach ($restore->mods
as $name => $info) {
74 //If the module is being restored
75 if (isset($info->restore
) && $info->restore
== 1) {
76 //Check if the xxxx_decode_content_links_caller exists
77 include_once("$CFG->dirroot/mod/$name/restorelib.php");
78 $function_name = $name."_decode_content_links_caller";
79 if (function_exists($function_name)) {
80 if (!defined('RESTORE_SILENTLY')) {
81 echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
84 $status = $function_name($restore);
88 if (!defined('RESTORE_SILENTLY')) {
92 // TODO: process all html text also in blocks too
97 //This function is called from all xxxx_decode_content_links_caller(),
98 //its task is to ask all modules (maybe other linkable objects) to restore
100 function restore_decode_content_links_worker($content,$restore) {
101 foreach($restore->mods
as $name => $info) {
102 $function_name = $name."_decode_content_links";
103 if (function_exists($function_name)) {
104 $content = $function_name($content,$restore);
110 //This function converts all the wiki texts in the restored course
111 //to the Markdown format. Used only for backup files prior 2005041100.
112 //It calls every module xxxx_convert_wiki2markdown function
113 function restore_convert_wiki2markdown($restore) {
117 if (!defined('RESTORE_SILENTLY')) {
120 foreach ($restore->mods
as $name => $info) {
121 //If the module is being restored
122 if ($info->restore
== 1) {
123 //Check if the xxxx_restore_wiki2markdown exists
124 $function_name = $name."_restore_wiki2markdown";
125 if (function_exists($function_name)) {
126 $status = $function_name($restore);
127 if (!defined('RESTORE_SILENTLY')) {
128 echo "<li>".get_string("modulenameplural",$name);
134 if (!defined('RESTORE_SILENTLY')) {
140 //This function receives a wiki text in the restore process and
141 //return it with every link to modules " modulename:moduleid"
142 //converted if possible. See the space before modulename!!
143 function restore_decode_wiki_content($content,$restore) {
149 $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
151 preg_match_all($searchstring,$content,$foundset);
152 //If found, then we are going to look for its new id (in backup tables)
154 //print_object($foundset); //Debug
155 //Iterate over foundset[2]. They are the old_ids
156 foreach($foundset[2] as $old_id) {
157 //We get the needed variables here (course id)
158 $rec = backup_getid($restore->backup_unique_code
,"course_modules",$old_id);
159 //Personalize the searchstring
160 $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/';
161 //If it is a link to this course, update the link to its new location
164 $result= preg_replace($searchstring,' $1:'.$rec->new_id
.'($2)',$result);
166 //It's a foreign link so redirect it to its original URL
167 $result= preg_replace($searchstring,$restore->original_wwwroot
.'/mod/$1/view.php?id='.$old_id.'($2)',$result);
175 //This function read the xml file and store it data from the info zone in an object
176 function restore_read_xml_info ($xml_file) {
178 //We call the main read_xml function, with todo = INFO
179 $info = restore_read_xml ($xml_file,"INFO",false);
184 //This function read the xml file and store it data from the course header zone in an object
185 function restore_read_xml_course_header ($xml_file) {
187 //We call the main read_xml function, with todo = COURSE_HEADER
188 $info = restore_read_xml ($xml_file,"COURSE_HEADER",false);
193 //This function read the xml file and store its data from the blocks in a object
194 function restore_read_xml_blocks ($xml_file) {
196 //We call the main read_xml function, with todo = BLOCKS
197 $info = restore_read_xml ($xml_file,'BLOCKS',false);
202 //This function read the xml file and store its data from the sections in a object
203 function restore_read_xml_sections ($xml_file) {
205 //We call the main read_xml function, with todo = SECTIONS
206 $info = restore_read_xml ($xml_file,"SECTIONS",false);
211 //This function read the xml file and store its data from the course format in an object
212 function restore_read_xml_formatdata ($xml_file) {
214 //We call the main read_xml function, with todo = FORMATDATA
215 $info = restore_read_xml ($xml_file,'FORMATDATA',false);
220 //This function read the xml file and store its data from the metacourse in a object
221 function restore_read_xml_metacourse ($xml_file) {
223 //We call the main read_xml function, with todo = METACOURSE
224 $info = restore_read_xml ($xml_file,"METACOURSE",false);
229 //This function read the xml file and store its data from the gradebook in a object
230 function restore_read_xml_gradebook ($restore, $xml_file) {
232 //We call the main read_xml function, with todo = GRADEBOOK
233 $info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
238 //This function read the xml file and store its data from the users in
239 //backup_ids->info db (and user's id in $info)
240 function restore_read_xml_users ($restore,$xml_file) {
242 //We call the main read_xml function, with todo = USERS
243 $info = restore_read_xml ($xml_file,"USERS",$restore);
248 //This function read the xml file and store its data from the messages in
249 //backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
250 function restore_read_xml_messages ($restore,$xml_file) {
252 //We call the main read_xml function, with todo = MESSAGES
253 $info = restore_read_xml ($xml_file,"MESSAGES",$restore);
259 //This function read the xml file and store its data from the questions in
260 //backup_ids->info db (and category's id in $info)
261 function restore_read_xml_questions ($restore,$xml_file) {
263 //We call the main read_xml function, with todo = QUESTIONS
264 $info = restore_read_xml ($xml_file,"QUESTIONS",$restore);
269 //This function read the xml file and store its data from the scales in
270 //backup_ids->info db (and scale's id in $info)
271 function restore_read_xml_scales ($restore,$xml_file) {
273 //We call the main read_xml function, with todo = SCALES
274 $info = restore_read_xml ($xml_file,"SCALES",$restore);
279 //This function read the xml file and store its data from the groups in
280 //backup_ids->info db (and group's id in $info)
281 function restore_read_xml_groups ($restore,$xml_file) {
283 //We call the main read_xml function, with todo = GROUPS
284 $info = restore_read_xml ($xml_file,"GROUPS",$restore);
289 //This function read the xml file and store its data from the groupings in
290 //backup_ids->info db (and grouping's id in $info)
291 function restore_read_xml_groupings ($restore,$xml_file) {
293 //We call the main read_xml function, with todo = GROUPINGS
294 $info = restore_read_xml ($xml_file,"GROUPINGS",$restore);
299 //This function read the xml file and store its data from the events (course) in
300 //backup_ids->info db (and event's id in $info)
301 function restore_read_xml_events ($restore,$xml_file) {
303 //We call the main read_xml function, with todo = EVENTS
304 $info = restore_read_xml ($xml_file,"EVENTS",$restore);
309 //This function read the xml file and store its data from the modules in
311 function restore_read_xml_modules ($restore,$xml_file) {
313 //We call the main read_xml function, with todo = MODULES
314 $info = restore_read_xml ($xml_file,"MODULES",$restore);
319 //This function read the xml file and store its data from the logs in
321 function restore_read_xml_logs ($restore,$xml_file) {
323 //We call the main read_xml function, with todo = LOGS
324 $info = restore_read_xml ($xml_file,"LOGS",$restore);
329 function restore_read_xml_roles ($xml_file) {
330 //We call the main read_xml function, with todo = ROLES
331 $info = restore_read_xml ($xml_file,"ROLES",false);
336 //This function prints the contents from the info parammeter passed
337 function restore_print_info ($info) {
343 //This is tha align to every ingo table
344 $table->align
= array ("right","left");
345 //This is the nowrap clause
346 $table->wrap
= array ("","nowrap");
348 $table->width
= "70%";
349 //Put interesting info in table
350 //The backup original name
351 $tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
352 $tab[0][1] = $info->backup_name
;
354 $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
355 $tab[1][1] = $info->backup_moodle_release
." (".$info->backup_moodle_version
.")";
357 $tab[2][0] = "<b>".get_string("backupversion").":</b>";
358 $tab[2][1] = $info->backup_backup_release
." (".$info->backup_backup_version
.")";
360 $tab[3][0] = "<b>".get_string("backupdate").":</b>";
361 $tab[3][1] = userdate($info->backup_date
);
363 print_heading(get_string("backup").":");
365 //Print backup general info
368 if ($info->backup_backup_version
<= 2005070500) {
369 notify(get_string('backupnonisowarning')); // Message informing that this backup may not work!
372 //Now backup contents in another table
377 foreach ($mods as $key => $mod) {
378 $tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
379 if ($mod->backup
== "false") {
380 $tab[$elem][1] = get_string("notincluded");
382 if ($mod->userinfo
== "true") {
383 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
385 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
387 if (isset($mod->instances
) && is_array($mod->instances
) && count($mod->instances
)) {
388 foreach ($mod->instances
as $instance) {
389 if ($instance->backup
) {
391 $tab[$elem][0] = $instance->name
;
392 if ($instance->userinfo
== 'true') {
393 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
395 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
404 $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
405 if ($info->backup_metacourse
== "true") {
406 $tab[$elem][1] = get_string("yes");
408 $tab[$elem][1] = get_string("no");
412 $tab[$elem][0] = "<b>".get_string("users").":</b>";
413 $tab[$elem][1] = get_string($info->backup_users
);
416 $tab[$elem][0] = "<b>".get_string("logs").":</b>";
417 if ($info->backup_logs
== "true") {
418 $tab[$elem][1] = get_string("yes");
420 $tab[$elem][1] = get_string("no");
424 $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
425 if ($info->backup_user_files
== "true") {
426 $tab[$elem][1] = get_string("yes");
428 $tab[$elem][1] = get_string("no");
432 $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
433 if ($info->backup_course_files
== "true") {
434 $tab[$elem][1] = get_string("yes");
436 $tab[$elem][1] = get_string("no");
439 //Messages info (only showed if present)
440 if ($info->backup_messages
== 'true') {
441 $tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
442 $tab[$elem][1] = get_string('yes');
449 print_heading(get_string("backupdetails").":");
450 //Print backup general info
459 //This function prints the contents from the course_header parammeter passed
460 function restore_print_course_header ($course_header) {
463 if ($course_header) {
464 //This is tha align to every ingo table
465 $table->align
= array ("right","left");
467 $table->width
= "70%";
468 //Put interesting course header in table
470 $tab[0][0] = "<b>".get_string("name").":</b>";
471 $tab[0][1] = $course_header->course_fullname
." (".$course_header->course_shortname
.")";
473 $tab[1][0] = "<b>".get_string("summary").":</b>";
474 $tab[1][1] = $course_header->course_summary
;
477 print_heading(get_string("course").":");
478 //Print backup course header info
486 //This function create a new course record.
487 //When finished, course_header contains the id of the new course
488 function restore_create_new_course($restore,&$course_header) {
494 $fullname = $course_header->course_fullname
;
495 $shortname = $course_header->course_shortname
;
496 $currentfullname = "";
497 $currentshortname = "";
499 //Iteratere while the name exists
502 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
503 $suffixshort = "_".$counter;
508 $currentfullname = $fullname.$suffixfull;
509 // Limit the size of shortname - database column accepts <= 15 chars
510 $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
511 $coursefull = get_record("course","fullname",addslashes($currentfullname));
512 $courseshort = get_record("course","shortname",addslashes($currentshortname));
514 } while ($coursefull ||
$courseshort);
516 //New name = currentname
517 $course_header->course_fullname
= $currentfullname;
518 $course_header->course_shortname
= $currentshortname;
520 //Now calculate the category
521 $category = get_record("course_categories","id",$course_header->category
->id
,
522 "name",addslashes($course_header->category
->name
));
523 //If no exists, try by name only
525 $category = get_record("course_categories","name",addslashes($course_header->category
->name
));
527 //If no exists, get category id 1
529 $category = get_record("course_categories","id","1");
531 //If category 1 doesn'exists, lets create the course category (get it from backup file)
533 $ins_category->name
= addslashes($course_header->category
->name
);
534 $ins_category->parent
= 0;
535 $ins_category->sortorder
= 0;
536 $ins_category->coursecount
= 0;
537 $ins_category->visible
= 0; //To avoid interferences with the rest of the site
538 $ins_category->timemodified
= time();
539 $newid = insert_record("course_categories",$ins_category);
540 $category->id
= $newid;
541 $category->name
= $course_header->category
->name
;
543 //If exists, put new category id
545 $course_header->category
->id
= $category->id
;
546 $course_header->category
->name
= $category->name
;
547 //Error, cannot locate category
549 $course_header->category
->id
= 0;
550 $course_header->category
->name
= get_string("unknowncategory");
554 //Create the course_object
556 $course->category
= addslashes($course_header->category
->id
);
557 $course->password
= addslashes($course_header->course_password
);
558 $course->fullname
= addslashes($course_header->course_fullname
);
559 $course->shortname
= addslashes($course_header->course_shortname
);
560 $course->idnumber
= addslashes($course_header->course_idnumber
);
561 $course->idnumber
= ''; //addslashes($course_header->course_idnumber); // we don't want this at all.
562 $course->summary
= restore_decode_absolute_links(addslashes($course_header->course_summary
));
563 $course->format
= addslashes($course_header->course_format
);
564 $course->showgrades
= addslashes($course_header->course_showgrades
);
565 $course->newsitems
= addslashes($course_header->course_newsitems
);
566 $course->teacher
= addslashes($course_header->course_teacher
);
567 $course->teachers
= addslashes($course_header->course_teachers
);
568 $course->student
= addslashes($course_header->course_student
);
569 $course->students
= addslashes($course_header->course_students
);
570 $course->guest
= addslashes($course_header->course_guest
);
571 $course->startdate
= addslashes($course_header->course_startdate
);
572 $course->startdate +
= $restore->course_startdateoffset
;
573 $course->enrolperiod
= addslashes($course_header->course_enrolperiod
);
574 $course->numsections
= addslashes($course_header->course_numsections
);
575 //$course->showrecent = addslashes($course_header->course_showrecent); INFO: This is out in 1.3
576 $course->maxbytes
= addslashes($course_header->course_maxbytes
);
577 $course->showreports
= addslashes($course_header->course_showreports
);
578 if (isset($course_header->course_groupmode
)) {
579 $course->groupmode
= addslashes($course_header->course_groupmode
);
581 if (isset($course_header->course_groupmodeforce
)) {
582 $course->groupmodeforce
= addslashes($course_header->course_groupmodeforce
);
584 $course->lang
= addslashes($course_header->course_lang
);
585 $course->theme
= addslashes($course_header->course_theme
);
586 $course->cost
= addslashes($course_header->course_cost
);
587 $course->currency
= isset($course_header->course_currency
)?
addslashes($course_header->course_currency
):'';
588 $course->marker
= addslashes($course_header->course_marker
);
589 $course->visible
= addslashes($course_header->course_visible
);
590 $course->hiddensections
= addslashes($course_header->course_hiddensections
);
591 $course->timecreated
= addslashes($course_header->course_timecreated
);
592 $course->timemodified
= addslashes($course_header->course_timemodified
);
593 $course->metacourse
= addslashes($course_header->course_metacourse
);
594 //Calculate sortorder field
595 $sortmax = get_record_sql('SELECT MAX(sortorder) AS max
596 FROM ' . $CFG->prefix
. 'course
597 WHERE category=' . $course->category
);
598 if (!empty($sortmax->max
)) {
599 $course->sortorder
= $sortmax->max +
1;
602 $course->sortorder
= 100;
605 //Now, recode some languages (Moodle 1.5)
606 if ($course->lang
== 'ma_nt') {
607 $course->lang
= 'mi_nt';
610 //Disable course->metacourse if avoided in restore config
611 if (!$restore->metacourse
) {
612 $course->metacourse
= 0;
615 //Check if the theme exists in destination server
616 $themes = get_list_of_themes();
617 if (!in_array($course->theme
, $themes)) {
621 //Now insert the record
622 $newid = insert_record("course",$course);
624 //save old and new course id
625 backup_putid ($restore->backup_unique_code
,"course",$course_header->course_id
,$newid);
626 //Replace old course_id in course_header
627 $course_header->course_id
= $newid;
637 * Returns the best question category (id) found to restore one
638 * question category from a backup file. Works by stamp (since Moodle 1.1)
639 * or by name (for older versions).
641 * @param object $cat the question_categories record to be searched
642 * @param integer $courseid the course where we are restoring
643 * @return integer the id of a existing question_category or 0 (not found)
645 function restore_get_best_question_category($cat, $courseid) {
649 //Decide how to work (by stamp or name)
651 $searchfield = 'stamp';
652 $searchvalue = $cat->stamp
;
654 $searchfield = 'name';
655 $searchvalue = $cat->name
;
658 //First shot. Try to get the category from the course being restored
659 if ($fcat = get_record('question_categories','course',$courseid,$searchfield,$searchvalue)) {
661 //Second shot. Try to obtain any concordant category and check its publish status and editing rights
662 } else if ($fcats = get_records('question_categories', $searchfield, $searchvalue, 'id', 'id, publish, course')) {
663 foreach ($fcats as $fcat) {
664 if ($fcat->publish
== 1 && has_capability('moodle/site:restore', get_context_instance(CONTEXT_COURSE
, $fcat->course
))) {
674 //This function creates all the block stuff when restoring courses
675 //It calls selectively to restore_create_block_instances() for 1.5
676 //and above backups. Upwards compatible with old blocks.
677 function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) {
681 delete_records('block_instance', 'pageid', $restore->course_id
, 'pagetype', PAGE_COURSE_VIEW
);
682 if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5
683 if (empty($blockinfo)) {
684 // Looks like it's from Moodle < 1.3. Let's give the course default blocks...
685 $newpage = page_create_object(PAGE_COURSE_VIEW
, $restore->course_id
);
686 blocks_repopulate_page($newpage);
688 // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup
689 $blockrecords = get_records_select('block', '', '', 'name, id');
690 $temp_blocks_l = array();
691 $temp_blocks_r = array();
692 @list
($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo);
693 $temp_blocks = array(BLOCK_POS_LEFT
=> explode(',', $temp_blocks_l), BLOCK_POS_RIGHT
=> explode(',', $temp_blocks_r));
694 foreach($temp_blocks as $blockposition => $blocks) {
696 foreach($blocks as $blockname) {
697 if(!isset($blockrecords[$blockname])) {
698 // We don't know anything about this block!
701 $blockinstance = new stdClass
;
702 // Remove any - prefix before doing the name-to-id mapping
703 if(substr($blockname, 0, 1) == '-') {
704 $blockname = substr($blockname, 1);
705 $blockinstance->visible
= 0;
707 $blockinstance->visible
= 1;
709 $blockinstance->blockid
= $blockrecords[$blockname]->id
;
710 $blockinstance->pageid
= $restore->course_id
;
711 $blockinstance->pagetype
= PAGE_COURSE_VIEW
;
712 $blockinstance->position
= $blockposition;
713 $blockinstance->weight
= $blockweight;
714 if(!$status = insert_record('block_instance', $blockinstance)) {
721 } else if($backup_block_format == 'instances') {
722 $status = restore_create_block_instances($restore,$xml_file);
729 //This function creates all the block_instances from xml when restoring in a
731 function restore_create_block_instances($restore,$xml_file) {
735 if (!file_exists($xml_file)) {
740 $info = restore_read_xml_blocks($xml_file);
743 if(empty($info->instances
)) {
747 // First of all, iterate over the blocks to see which distinct pages we have
748 // in our hands and arrange the blocks accordingly.
749 $pageinstances = array();
750 foreach($info->instances
as $instance) {
752 //pagetype and pageid black magic, we have to handle the case of blocks for the
753 //course, blocks from other pages in that course etc etc etc.
755 if($instance->pagetype
== PAGE_COURSE_VIEW
) {
756 // This one's easy...
757 $instance->pageid
= $restore->course_id
;
760 $parts = explode('-', $instance->pagetype
);
761 if($parts[0] == 'mod') {
762 if(!$restore->mods
[$parts[1]]->restore
) {
765 $getid = backup_getid($restore->backup_unique_code
, $parts[1], $instance->pageid
);
766 $instance->pageid
= $getid->new_id
;
769 // Not invented here ;-)
774 if(!isset($pageinstances[$instance->pagetype
])) {
775 $pageinstances[$instance->pagetype
] = array();
777 if(!isset($pageinstances[$instance->pagetype
][$instance->pageid
])) {
778 $pageinstances[$instance->pagetype
][$instance->pageid
] = array();
781 $pageinstances[$instance->pagetype
][$instance->pageid
][] = $instance;
784 $blocks = get_records_select('block', '', '', 'name, id, multiple');
786 // For each type of page we have restored
787 foreach($pageinstances as $thistypeinstances) {
789 // For each page id of that type
790 foreach($thistypeinstances as $thisidinstances) {
792 $addedblocks = array();
793 $maxweights = array();
795 // For each block instance in that page
796 foreach($thisidinstances as $instance) {
798 if(!isset($blocks[$instance->name
])) {
799 //We are trying to restore a block we don't have...
803 //If we have already added this block once and multiples aren't allowed, disregard it
804 if(!$blocks[$instance->name
]->multiple
&& isset($addedblocks[$instance->name
])) {
808 //If its the first block we add to a new position, start weight counter equal to 0.
809 if(empty($maxweights[$instance->position
])) {
810 $maxweights[$instance->position
] = 0;
813 //If the instance weight is greater than the weight counter (we skipped some earlier
814 //blocks most probably), bring it back in line.
815 if($instance->weight
> $maxweights[$instance->position
]) {
816 $instance->weight
= $maxweights[$instance->position
];
820 $instance->blockid
= $blocks[$instance->name
]->id
;
822 if ($newid = insert_record('block_instance', $instance)) {
823 if (!empty($instance->id
)) { // this will only be set if we come from 1.7 and above backups
824 backup_putid ($restore->backup_unique_code
,"block_instance",$instance->id
,$newid);
831 //Get an object for the block and tell it it's been restored so it can update dates
833 $blockobj=block_instance($instance->name
,$instance);
834 $blockobj->after_restore($restore);
836 //Now we can increment the weight counter
837 ++
$maxweights[$instance->position
];
839 //Keep track of block types we have already added
840 $addedblocks[$instance->name
] = true;
849 //This function creates all the course_sections and course_modules from xml
850 //when restoring in a new course or simply checks sections and create records
851 //in backup_ids when restoring in a existing course
852 function restore_create_sections(&$restore, $xml_file) {
858 if (!file_exists($xml_file)) {
863 $info = restore_read_xml_sections($xml_file);
865 //Put the info in the DB, recoding ids and saving the in backup tables
870 //For each, section, save it to db
871 foreach ($info->sections
as $key => $sect) {
873 $section->course
= $restore->course_id
;
874 $section->section
= $sect->number
;
875 $section->summary
= restore_decode_absolute_links(addslashes($sect->summary
));
876 $section->visible
= $sect->visible
;
877 $section->sequence
= "";
878 //Now calculate the section's newid
880 if ($restore->restoreto
== 2) {
881 //Save it to db (only if restoring to new course)
882 $newid = insert_record("course_sections",$section);
884 //Get section id when restoring in existing course
885 $rec = get_record("course_sections","course",$restore->course_id
,
886 "section",$section->section
);
887 //If that section doesn't exist, get section 0 (every mod will be
890 $rec = get_record("course_sections","course",$restore->course_id
,
893 //New check. If section 0 doesn't exist, insert it here !!
894 //Teorically this never should happen but, in practice, some users
895 //have reported this issue.
897 $zero_sec->course
= $restore->course_id
;
898 $zero_sec->section
= 0;
899 $zero_sec->summary
= "";
900 $zero_sec->sequence
= "";
901 $newid = insert_record("course_sections",$zero_sec);
906 $sequence = $rec->sequence
;
909 //save old and new section id
910 backup_putid ($restore->backup_unique_code
,"course_sections",$key,$newid);
914 //If all is OK, go with associated mods
916 //If we have mods in the section
917 if (!empty($sect->mods
)) {
918 //For each mod inside section
919 foreach ($sect->mods
as $keym => $mod) {
920 // Yu: This part is called repeatedly for every instance,
921 // so it is necessary to set the granular flag and check isset()
922 // when the first instance of this type of mod is processed.
923 if (!isset($restore->mods
[$mod->type
]->granular
) && isset($restore->mods
[$mod->type
]->instances
) && is_array($restore->mods
[$mod->type
]->instances
)) {
924 // This defines whether we want to restore specific
925 // instances of the modules (granular restore), or
926 // whether we don't care and just want to restore
927 // all module instances (non-granular).
928 $restore->mods
[$mod->type
]->granular
= true;
930 $restore->mods
[$mod->type
]->granular
= false;
933 //Check if we've to restore this module (and instance)
934 if (!empty($restore->mods
[$mod->type
]->restore
)) {
935 if (empty($restore->mods
[$mod->type
]->granular
) // we don't care about per instance
936 ||
(array_key_exists($mod->instance
,$restore->mods
[$mod->type
]->instances
)
937 && !empty($restore->mods
[$mod->type
]->instances
[$mod->instance
]->restore
))) {
939 //Get the module id from modules
940 $module = get_record("modules","name",$mod->type
);
942 $course_module->course
= $restore->course_id
;
943 $course_module->module
= $module->id
;
944 $course_module->section
= $newid;
945 $course_module->added
= $mod->added
;
946 $course_module->score
= $mod->score
;
947 $course_module->indent
= $mod->indent
;
948 $course_module->visible
= $mod->visible
;
949 if (isset($mod->groupmode
)) {
950 $course_module->groupmode
= $mod->groupmode
;
952 $course_module->instance
= 0;
953 //NOTE: The instance (new) is calculated and updated in db in the
954 // final step of the restore. We don't know it yet.
955 //print_object($course_module); //Debug
958 $newidmod = insert_record("course_modules",$course_module);
960 //save old and new module id
961 //In the info field, we save the original instance of the module
963 backup_putid ($restore->backup_unique_code
,"course_modules",
964 $keym,$newidmod,$mod->instance
);
966 $restore->mods
[$mod->type
]->instances
[$mod->instance
]->restored_as_course_module
= $newidmod;
970 //Now, calculate the sequence field
973 $sequence .= ",".$newidmod;
975 $sequence = $newidmod;
986 //If all is OK, update sequence field in course_sections
988 if (isset($sequence)) {
989 $update_rec->id
= $newid;
990 $update_rec->sequence
= $sequence;
991 $status = update_record("course_sections",$update_rec);
1001 //Called to set up any course-format specific data that may be in the file
1002 function restore_set_format_data($restore,$xml_file) {
1007 if (!file_exists($xml_file)) {
1010 //Load data from XML to info
1011 if(!($info = restore_read_xml_formatdata($xml_file))) {
1015 //Process format data if there is any
1016 if (isset($info->format_data
)) {
1017 if(!$format=get_field('course','format','id',$restore->course_id
)) {
1020 // If there was any data then it must have a restore method
1021 $file=$CFG->dirroot
."/course/format/$format/restorelib.php";
1022 if(!file_exists($file)) {
1025 require_once($file);
1026 $function=$format.'_restore_format_data';
1027 if(!function_exists($function)) {
1030 return $function($restore,$info->format_data
);
1033 // If we got here then there's no data, but that's cool
1037 //This function creates all the metacourse data from xml, notifying
1038 //about each incidence
1039 function restore_create_metacourse($restore,$xml_file) {
1045 if (!file_exists($xml_file)) {
1050 //Load data from XML to info
1051 $info = restore_read_xml_metacourse($xml_file);
1054 //Process info about metacourse
1055 if ($status and $info) {
1056 //Process child records
1057 if (!empty($info->childs
)) {
1058 foreach ($info->childs
as $child) {
1060 $dbmetacourse = false;
1061 //Check if child course exists in destination server
1062 //(by id in the same server or by idnumber and shortname in other server)
1063 if ($restore->original_wwwroot
== $CFG->wwwroot
) {
1064 //Same server, lets see by id
1065 $dbcourse = get_record('course','id',$child->id
);
1067 //Different server, lets see by idnumber and shortname, and only ONE record
1068 $dbcount = count_records('course','idnumber',$child->idnumber
,'shortname',$child->shortname
);
1069 if ($dbcount == 1) {
1070 $dbcourse = get_record('course','idnumber',$child->idnumber
,'shortname',$child->shortname
);
1073 //If child course has been found, insert data
1075 $dbmetacourse->child_course
= $dbcourse->id
;
1076 $dbmetacourse->parent_course
= $restore->course_id
;
1077 $status = insert_record ('course_meta',$dbmetacourse);
1079 //Child course not found, notice!
1080 if (!defined('RESTORE_SILENTLY')) {
1081 echo '<ul><li>'.get_string ('childcoursenotfound').' ('.$child->id
.'/'.$child->idnumber
.'/'.$child->shortname
.')</li></ul>';
1085 //Now, recreate student enrolments...
1086 sync_metacourse($restore->course_id
);
1088 //Process parent records
1089 if (!empty($info->parents
)) {
1090 foreach ($info->parents
as $parent) {
1092 $dbmetacourse = false;
1093 //Check if parent course exists in destination server
1094 //(by id in the same server or by idnumber and shortname in other server)
1095 if ($restore->original_wwwroot
== $CFG->wwwroot
) {
1096 //Same server, lets see by id
1097 $dbcourse = get_record('course','id',$parent->id
);
1099 //Different server, lets see by idnumber and shortname, and only ONE record
1100 $dbcount = count_records('course','idnumber',$parent->idnumber
,'shortname',$parent->shortname
);
1101 if ($dbcount == 1) {
1102 $dbcourse = get_record('course','idnumber',$parent->idnumber
,'shortname',$parent->shortname
);
1105 //If parent course has been found, insert data if it is a metacourse
1107 if ($dbcourse->metacourse
) {
1108 $dbmetacourse->parent_course
= $dbcourse->id
;
1109 $dbmetacourse->child_course
= $restore->course_id
;
1110 $status = insert_record ('course_meta',$dbmetacourse);
1111 //Now, recreate student enrolments in parent course
1112 sync_metacourse($dbcourse->id
);
1114 //Parent course isn't metacourse, notice!
1115 if (!defined('RESTORE_SILENTLY')) {
1116 echo '<ul><li>'.get_string ('parentcoursenotmetacourse').' ('.$parent->id
.'/'.$parent->idnumber
.'/'.$parent->shortname
.')</li></ul>';
1120 //Parent course not found, notice!
1121 if (!defined('RESTORE_SILENTLY')) {
1122 echo '<ul><li>'.get_string ('parentcoursenotfound').' ('.$parent->id
.'/'.$parent->idnumber
.'/'.$parent->shortname
.')</li></ul>';
1132 //This function creates all the gradebook data from xml, notifying
1133 //about each incidence
1134 function restore_create_gradebook($restore,$xml_file) {
1140 if (!file_exists($xml_file)) {
1145 //info will contain the number of record to process
1146 $info = restore_read_xml_gradebook($restore, $xml_file);
1148 //If we have info, then process preferences, letters & categories
1150 //Count how many we have
1151 $preferencescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_preferences');
1152 $letterscount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_letter');
1153 $categoriescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'grade_category');
1155 if ($preferencescount ||
$letterscount ||
$categoriescount) {
1157 if (!defined('RESTORE_SILENTLY')) {
1160 //Number of records to get in every chunk
1161 $recordset_size = 2;
1162 //Flag to mark if we must continue
1165 //If there aren't preferences, stop
1166 if (!$preferencescount) {
1168 if (!defined('RESTORE_SILENTLY')) {
1169 echo '<li>'.get_string('backupwithoutgradebook','grade').'</li>';
1173 //If we are restoring to an existing course and it has advanced disabled, stop
1174 if ($restore->restoreto
!= 2) {
1175 //Fetch the 'use_advanced' preferences (id = 0)
1176 if ($pref_rec = get_record('grade_preferences','courseid',$restore->course_id
,'preference',0)) {
1177 if ($pref_rec->value
== 0) {
1179 if (!defined('RESTORE_SILENTLY')) {
1180 echo '<li>'.get_string('respectingcurrentdata','grade').'</li>';
1186 //Process preferences
1187 if ($preferencescount && $continue) {
1188 if (!defined('RESTORE_SILENTLY')) {
1189 echo '<li>'.get_string('preferences','grades').'</li>';
1192 while ($counter < $preferencescount) {
1193 //Fetch recordset_size records in each iteration
1194 $recs = get_records_select("backup_ids","table_name = 'grade_preferences' AND backup_code = '$restore->backup_unique_code'",
1200 foreach ($recs as $rec) {
1201 //Get the full record from backup_ids
1202 $data = backup_getid($restore->backup_unique_code
,'grade_preferences',$rec->old_id
);
1204 //Now get completed xmlized object
1205 $info = $data->info
;
1206 //traverse_xmlize($info); //Debug
1207 //print_object ($GLOBALS['traverse_array']); //Debug
1208 //$GLOBALS['traverse_array']=""; //Debug
1209 //Now build the GRADE_PREFERENCES record structure
1210 $dbrec->courseid
= $restore->course_id
;
1211 $dbrec->preference
= backup_todb($info['GRADE_PREFERENCE']['#']['PREFERENCE']['0']['#']);
1212 $dbrec->value
= backup_todb($info['GRADE_PREFERENCE']['#']['VALUE']['0']['#']);
1214 //Structure is equal to db, insert record
1215 //if the preference doesn't exist
1216 if (!$prerec = get_record('grade_preferences','courseid',$dbrec->courseid
,'preference',$dbrec->preference
)) {
1217 $status = insert_record('grade_preferences',$dbrec);
1220 //Increment counters
1223 if ($counter %
1 == 0) {
1224 if (!defined('RESTORE_SILENTLY')) {
1226 if ($counter %
20 == 0) {
1238 //If destination course has letters, skip restoring letters
1239 $hasletters = get_records('grade_letter', 'courseid', $restore->course_id
);
1241 if ($letterscount && $continue && !$hasletters) {
1242 if (!defined('RESTORE_SILENTLY')) {
1243 echo '<li>'.get_string('letters','grades').'</li>';
1246 while ($counter < $letterscount) {
1247 //Fetch recordset_size records in each iteration
1248 $recs = get_records_select("backup_ids","table_name = 'grade_letter' AND backup_code = '$restore->backup_unique_code'",
1254 foreach ($recs as $rec) {
1255 //Get the full record from backup_ids
1256 $data = backup_getid($restore->backup_unique_code
,'grade_letter',$rec->old_id
);
1258 //Now get completed xmlized object
1259 $info = $data->info
;
1260 //traverse_xmlize($info); //Debug
1261 //print_object ($GLOBALS['traverse_array']); //Debug
1262 //$GLOBALS['traverse_array']=""; //Debug
1263 //Now build the GRADE_LETTER record structure
1264 $dbrec->courseid
= $restore->course_id
;
1265 $dbrec->letter
= backup_todb($info['GRADE_LETTER']['#']['LETTER']['0']['#']);
1266 $dbrec->grade_high
= backup_todb($info['GRADE_LETTER']['#']['GRADE_HIGH']['0']['#']);
1267 $dbrec->grade_low
= backup_todb($info['GRADE_LETTER']['#']['GRADE_LOW']['0']['#']);
1269 //Structure is equal to db, insert record
1270 $status = insert_record('grade_letter',$dbrec);
1272 //Increment counters
1275 if ($counter %
1 == 0) {
1276 if (!defined('RESTORE_SILENTLY')) {
1278 if ($counter %
20 == 0) {
1289 //Process categories
1290 if ($categoriescount && $continue) {
1291 if (!defined('RESTORE_SILENTLY')) {
1292 echo '<li>'.get_string('categories','grades').'</li>';
1296 while ($countercat < $categoriescount) {
1297 //Fetch recordset_size records in each iteration
1298 $recs = get_records_select("backup_ids","table_name = 'grade_category' AND backup_code = '$restore->backup_unique_code'",
1304 foreach ($recs as $rec) {
1305 //Get the full record from backup_ids
1306 $data = backup_getid($restore->backup_unique_code
,'grade_category',$rec->old_id
);
1308 //Now get completed xmlized object
1309 $info = $data->info
;
1310 //traverse_xmlize($info); //Debug
1311 //print_object ($GLOBALS['traverse_array']); //Debug
1312 //$GLOBALS['traverse_array']=""; //Debug
1313 //Now build the GRADE_CATEGORY record structure
1314 $dbrec->courseid
= $restore->course_id
;
1315 $dbrec->name
= backup_todb($info['GRADE_CATEGORY']['#']['NAME']['0']['#']);
1316 $dbrec->drop_x_lowest
= backup_todb($info['GRADE_CATEGORY']['#']['DROP_X_LOWEST']['0']['#']);
1317 $dbrec->bonus_points
= backup_todb($info['GRADE_CATEGORY']['#']['BONUS_POINTS']['0']['#']);
1318 $dbrec->hidden
= backup_todb($info['GRADE_CATEGORY']['#']['HIDDEN']['0']['#']);
1319 $dbrec->weight
= backup_todb($info['GRADE_CATEGORY']['#']['WEIGHT']['0']['#']);
1321 //If the grade_category exists in the course (by name), don't insert anything
1322 $catex = get_record('grade_category','courseid',$dbrec->courseid
,'name',$dbrec->name
);
1325 //Structure is equal to db, insert record
1326 $categoryid = insert_record('grade_category',$dbrec);
1328 //Simply remap category
1329 $categoryid = $catex->id
;
1332 //Now, restore grade_item
1333 $items = $info['GRADE_CATEGORY']['#']['GRADE_ITEMS']['0']['#']['GRADE_ITEM'];
1335 //Iterate over items
1336 for($i = 0; $i < sizeof($items); $i++
) {
1337 $ite_info = $items[$i];
1338 //traverse_xmlize($ite_info); //Debug
1339 //print_object ($GLOBALS['traverse_array']); //Debug
1340 //$GLOBALS['traverse_array']=""; //Debug
1342 //Now build the GRADE_ITEM record structure
1343 $item->courseid
= $restore->course_id
;
1344 $item->category
= $categoryid;
1345 $item->module_name
= backup_todb($ite_info['#']['MODULE_NAME']['0']['#']);
1346 $item->cminstance
= backup_todb($ite_info['#']['CMINSTANCE']['0']['#']);
1347 $item->scale_grade
= backup_todb($ite_info['#']['SCALE_GRADE']['0']['#']);
1348 $item->extra_credit
= backup_todb($ite_info['#']['EXTRA_CREDIT']['0']['#']);
1349 $item->sort_order
= backup_todb($ite_info['#']['SORT_ORDER']['0']['#']);
1351 //Check that the module has been included in the restore
1352 if ($restore->mods
[$item->module_name
]->restore
) {
1353 //Get the id of the moduletype
1354 if ($module = get_record('modules','name',$item->module_name
)) {
1355 $item->modid
= $module->id
;
1356 //Get the instance id
1357 if ($instance = backup_getid($restore->backup_unique_code
,$item->module_name
,$item->cminstance
)) {
1358 $item->cminstance
= $instance->new_id
;
1359 //Structure is equal to db, insert record
1360 $itemid = insert_record('grade_item',$item);
1362 //Now process grade_exceptions
1363 if (!empty($ite_info['#']['GRADE_EXCEPTIONS'])) {
1364 $exceptions = $ite_info['#']['GRADE_EXCEPTIONS']['0']['#']['GRADE_EXCEPTION'];
1366 $exceptions = array();
1369 //Iterate over exceptions
1370 for($j = 0; $j < sizeof($exceptions); $j++
) {
1371 $exc_info = $exceptions[$j];
1372 //traverse_xmlize($exc_info); //Debug
1373 //print_object ($GLOBALS['traverse_array']); //Debug
1374 //$GLOBALS['traverse_array']=""; //Debug
1376 //Now build the GRADE_EXCEPTIONS record structure
1377 $exception->courseid
= $restore->course_id
;
1378 $exception->grade_itemid
= $itemid;
1379 $exception->userid
= backup_todb($exc_info['#']['USERID']['0']['#']);
1381 //We have to recode the useridto field
1382 $user = backup_getid($restore->backup_unique_code
,"user",$exception->userid
);
1384 $exception->userid
= $user->new_id
;
1385 //Structure is equal to db, insert record
1386 $exceptionid = insert_record('grade_exceptions',$exception);
1389 if ($counter %
20 == 0) {
1390 if (!defined('RESTORE_SILENTLY')) {
1392 if ($counter %
400 == 0) {
1405 //Re-sort all the grade_items because we can have duplicates
1406 if ($grade_items = get_records ('grade_item','courseid',$restore->course_id
,'sort_order','id,sort_order')) {
1408 foreach ($grade_items as $grade_item) {
1409 $grade_item->sort_order
= $order;
1410 set_field ('grade_item','sort_order',$grade_item->sort_order
,'id',$grade_item->id
);
1415 //Increment counters
1418 if ($countercat %
1 == 0) {
1419 if (!defined('RESTORE_SILENTLY')) {
1421 if ($countercat %
20 == 0) {
1431 if (!defined('RESTORE_SILENTLY')) {
1442 //This function creates all the user, user_students, user_teachers
1443 //user_course_creators and user_admins from xml
1444 function restore_create_users($restore,$xml_file) {
1450 if (!file_exists($xml_file)) {
1455 //info will contain the old_id of every user
1456 //in backup_ids->info will be the real info (serialized)
1457 $info = restore_read_xml_users($restore,$xml_file);
1460 //Now, get evey user_id from $info and user data from $backup_ids
1461 //and create the necessary records (users, user_students, user_teachers
1462 //user_course_creators and user_admins
1463 if (!empty($info->users
)) {
1464 // Grab mnethosts keyed by wwwroot, to map to id
1465 $mnethosts = get_records('mnethost', '', '',
1466 'wwwroot', 'wwwroot, id');
1467 foreach ($info->users
as $userid) {
1468 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
1471 //Now, recode some languages (Moodle 1.5)
1472 if ($user->lang
== 'ma_nt') {
1473 $user->lang
= 'mi_nt';
1476 //Check if it's admin and coursecreator
1477 $is_admin = !empty($user->roles
['admin']);
1478 $is_coursecreator = !empty($user->roles
['coursecreator']);
1480 //Check if it's teacher and student
1481 $is_teacher = !empty($user->roles
['teacher']);
1482 $is_student = !empty($user->roles
['student']);
1484 //Check if it's needed
1485 $is_needed = !empty($user->roles
['needed']);
1487 //Calculate if it is a course user
1488 //Has role teacher or student or needed
1489 $is_course_user = ($is_teacher or $is_student or $is_needed);
1491 //Calculate mnethostid
1492 if (empty($user->mnethosturl
) ||
$user->mnethosturl
===$CFG->wwwroot
) {
1493 $user->mnethostid
= $CFG->mnet_localhost_id
;
1495 // fast url-to-id lookups
1496 if (isset($mnethosts[$user->mnethosturl
])) {
1497 $user->mnethostid
= $mnethosts[$user->mnethosturl
]->id
;
1499 // should not happen, as we check in restore_chech.php
1500 // but handle the error if it does
1501 error("This backup file contains external Moodle Network Hosts that are not configured locally.");
1504 unset($user->mnethosturl
);
1506 //To store new ids created
1508 //check if it exists (by username) and get its id
1509 $user_exists = true;
1510 $user_data = get_record("user","username",addslashes($user->username
),
1511 'mnethostid', $user->mnethostid
);
1513 $user_exists = false;
1515 $newid = $user_data->id
;
1517 //Flags to see if we have to create the user, roles and preferences
1518 $create_user = true;
1519 $create_roles = true;
1520 $create_preferences = true;
1522 //If we are restoring course users and it isn't a course user
1523 if ($restore->users
== 1 and !$is_course_user) {
1524 //If only restoring course_users and user isn't a course_user, inform to $backup_ids
1525 $status = backup_putid($restore->backup_unique_code
,"user",$userid,null,'notincourse');
1526 $create_user = false;
1527 $create_roles = false;
1528 $create_preferences = false;
1531 if ($user_exists and $create_user) {
1532 //If user exists mark its newid in backup_ids (the same than old)
1533 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,'exists');
1534 $create_user = false;
1537 //Here, if create_user, do it
1539 //Unset the id because it's going to be inserted with a new one
1541 //We addslashes to necessary fields
1542 $user->username
= addslashes($user->username
);
1543 $user->firstname
= addslashes($user->firstname
);
1544 $user->lastname
= addslashes($user->lastname
);
1545 $user->email
= addslashes($user->email
);
1546 $user->institution
= addslashes($user->institution
);
1547 $user->department
= addslashes($user->department
);
1548 $user->address
= addslashes($user->address
);
1549 $user->city
= addslashes($user->city
);
1550 $user->url
= addslashes($user->url
);
1551 $user->description
= restore_decode_absolute_links(addslashes($user->description
));
1553 //We need to analyse the AUTH field to recode it:
1554 // - if the field isn't set, we are in a pre 1.4 backup and we'll
1556 // - if the destination site has any kind of INTERNAL authentication,
1557 // then apply it to the new user.
1558 // - if the destination site has any kind of EXTERNAL authentication,
1559 // then leave the original authentication of the user.
1561 if ((! isset($user->auth
)) ||
is_internal_auth($CFG->auth
)) {
1562 $user->auth
= $CFG->auth
;
1565 //We need to process the POLICYAGREED field to recalculate it:
1566 // - if the destination site is different (by wwwroot) reset it.
1567 // - if the destination site is the same (by wwwroot), leave it unmodified
1569 if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
1570 $user->policyagreed
= 0;
1572 //Nothing to do, we are in the same server
1575 //Check if the theme exists in destination server
1576 $themes = get_list_of_themes();
1577 if (!in_array($user->theme
, $themes)) {
1581 //We are going to create the user
1582 //The structure is exactly as we need
1583 $newid = insert_record ("user",$user);
1585 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,"new");
1588 //Here, if create_roles, do it as necessary
1589 if ($create_roles) {
1590 //Get the newid and current info from backup_ids
1591 $data = backup_getid($restore->backup_unique_code
,"user",$userid);
1592 $newid = $data->new_id
;
1593 $currinfo = $data->info
.",";
1595 //Now, depending of the role, create records in user_studentes and user_teacher
1596 //and/or mark it in backup_ids
1599 //If the record (user_admins) doesn't exists
1600 //Only put status in backup_ids
1601 $currinfo = $currinfo."admin,";
1602 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1604 if ($is_coursecreator) {
1605 //If the record (user_coursecreators) doesn't exists
1606 //Only put status in backup_ids
1607 $currinfo = $currinfo."coursecreator,";
1608 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1611 //Only put status in backup_ids
1612 $currinfo = $currinfo."needed,";
1613 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1616 //If the record (teacher) doesn't exists
1617 //Put status in backup_ids
1618 $currinfo = $currinfo."teacher,";
1619 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1620 //Set course and user
1621 $user->roles
['teacher']->course
= $restore->course_id
;
1622 $user->roles
['teacher']->userid
= $newid;
1624 //Need to analyse the enrol field
1625 // - if it isn't set, set it to $CFG->enrol
1626 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
1627 // - if we are in the same server (by wwwroot), maintain it unmodified.
1628 if (empty($user->roles
['teacher']->enrol
)) {
1629 $user->roles
['teacher']->enrol
= $CFG->enrol
;
1630 } else if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
1631 $user->roles
['teacher']->enrol
= $CFG->enrol
;
1633 //Nothing to do. Leave it unmodified
1636 $rolesmapping = $restore->rolesmapping
;
1637 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
1638 if ($user->roles
['teacher']->editall
) {
1639 role_assign($rolesmapping['defaultteacheredit'],
1643 $user->roles
['teacher']->timestart
,
1644 $user->roles
['teacher']->timeend
,
1646 $user->roles
['teacher']->enrol
);
1650 // non editting teacher
1651 role_assign($rolesmapping['defaultteacher'],
1655 $user->roles
['teacher']->timestart
,
1656 $user->roles
['teacher']->timeend
,
1658 $user->roles
['teacher']->enrol
);
1663 //Put status in backup_ids
1664 $currinfo = $currinfo."student,";
1665 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1666 //Set course and user
1667 $user->roles
['student']->course
= $restore->course_id
;
1668 $user->roles
['student']->userid
= $newid;
1670 //Need to analyse the enrol field
1671 // - if it isn't set, set it to $CFG->enrol
1672 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
1673 // - if we are in the same server (by wwwroot), maintain it unmodified.
1674 if (empty($user->roles
['student']->enrol
)) {
1675 $user->roles
['student']->enrol
= $CFG->enrol
;
1676 } else if ($restore->original_wwwroot
!= $CFG->wwwroot
) {
1677 $user->roles
['student']->enrol
= $CFG->enrol
;
1679 //Nothing to do. Leave it unmodified
1681 $rolesmapping = $restore->rolesmapping
;
1682 $context = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
1684 role_assign($rolesmapping['defaultstudent'],
1688 $user->roles
['student']->timestart
,
1689 $user->roles
['student']->timeend
,
1691 $user->roles
['student']->enrol
);
1694 if (!$is_course_user) {
1695 //If the record (user) doesn't exists
1696 if (!record_exists("user","id",$newid)) {
1697 //Put status in backup_ids
1698 $currinfo = $currinfo."user,";
1699 $status = backup_putid($restore->backup_unique_code
,"user",$userid,$newid,$currinfo);
1704 //Here, if create_preferences, do it as necessary
1705 if ($create_preferences) {
1706 //echo "Checking for preferences of user ".$user->username."<br />"; //Debug
1707 //Get user new id from backup_ids
1708 $data = backup_getid($restore->backup_unique_code
,"user",$userid);
1709 $newid = $data->new_id
;
1710 if (isset($user->user_preferences
)) {
1711 //echo "Preferences exist in backup file<br />"; //Debug
1712 foreach($user->user_preferences
as $user_preference) {
1713 //echo $user_preference->name." = ".$user_preference->value."<br />"; //Debug
1714 //We check if that user_preference exists in DB
1715 if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name
)) {
1716 //echo "Creating it<br />"; //Debug
1717 //Prepare the record and insert it
1718 $user_preference->userid
= $newid;
1719 $status = insert_record("user_preferences",$user_preference);
1730 //This function creates all the structures messages and contacts
1731 function restore_create_messages($restore,$xml_file) {
1737 if (!file_exists($xml_file)) {
1742 //info will contain the id and name of every table
1743 //(message, message_read and message_contacts)
1744 //in backup_ids->info will be the real info (serialized)
1745 $info = restore_read_xml_messages($restore,$xml_file);
1747 //If we have info, then process messages & contacts
1749 //Count how many we have
1750 $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message');
1751 $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message_read');
1752 $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code
, 'table_name', 'message_contacts');
1753 if ($unreadcount ||
$readcount ||
$contactcount) {
1755 if (!defined('RESTORE_SILENTLY')) {
1758 //Number of records to get in every chunk
1759 $recordset_size = 4;
1763 if (!defined('RESTORE_SILENTLY')) {
1764 echo '<li>'.get_string('unreadmessages','message').'</li>';
1767 while ($counter < $unreadcount) {
1768 //Fetch recordset_size records in each iteration
1769 $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);
1771 foreach ($recs as $rec) {
1772 //Get the full record from backup_ids
1773 $data = backup_getid($restore->backup_unique_code
,"message",$rec->old_id
);
1775 //Now get completed xmlized object
1776 $info = $data->info
;
1777 //traverse_xmlize($info); //Debug
1778 //print_object ($GLOBALS['traverse_array']); //Debug
1779 //$GLOBALS['traverse_array']=""; //Debug
1780 //Now build the MESSAGE record structure
1781 $dbrec->useridfrom
= backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
1782 $dbrec->useridto
= backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
1783 $dbrec->message
= backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
1784 $dbrec->format
= backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
1785 $dbrec->timecreated
= backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
1786 $dbrec->messagetype
= backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
1787 //We have to recode the useridfrom field
1788 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridfrom
);
1790 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
1791 $dbrec->useridfrom
= $user->new_id
;
1793 //We have to recode the useridto field
1794 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridto
);
1796 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
1797 $dbrec->useridto
= $user->new_id
;
1799 //Check if the record doesn't exist in DB!
1800 $exist = get_record('message','useridfrom',$dbrec->useridfrom
,
1801 'useridto', $dbrec->useridto
,
1802 'timecreated',$dbrec->timecreated
);
1805 $status = insert_record('message',$dbrec);
1807 //Duplicate. Do nothing
1812 if ($counter %
10 == 0) {
1813 if (!defined('RESTORE_SILENTLY')) {
1815 if ($counter %
200 == 0) {
1828 if (!defined('RESTORE_SILENTLY')) {
1829 echo '<li>'.get_string('readmessages','message').'</li>';
1832 while ($counter < $readcount) {
1833 //Fetch recordset_size records in each iteration
1834 $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);
1836 foreach ($recs as $rec) {
1837 //Get the full record from backup_ids
1838 $data = backup_getid($restore->backup_unique_code
,"message_read",$rec->old_id
);
1840 //Now get completed xmlized object
1841 $info = $data->info
;
1842 //traverse_xmlize($info); //Debug
1843 //print_object ($GLOBALS['traverse_array']); //Debug
1844 //$GLOBALS['traverse_array']=""; //Debug
1845 //Now build the MESSAGE_READ record structure
1846 $dbrec->useridfrom
= backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
1847 $dbrec->useridto
= backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
1848 $dbrec->message
= backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
1849 $dbrec->format
= backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
1850 $dbrec->timecreated
= backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
1851 $dbrec->messagetype
= backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
1852 $dbrec->timeread
= backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
1853 $dbrec->mailed
= backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
1854 //We have to recode the useridfrom field
1855 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridfrom
);
1857 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
1858 $dbrec->useridfrom
= $user->new_id
;
1860 //We have to recode the useridto field
1861 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->useridto
);
1863 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
1864 $dbrec->useridto
= $user->new_id
;
1866 //Check if the record doesn't exist in DB!
1867 $exist = get_record('message_read','useridfrom',$dbrec->useridfrom
,
1868 'useridto', $dbrec->useridto
,
1869 'timecreated',$dbrec->timecreated
);
1872 $status = insert_record('message_read',$dbrec);
1874 //Duplicate. Do nothing
1879 if ($counter %
10 == 0) {
1880 if (!defined('RESTORE_SILENTLY')) {
1882 if ($counter %
200 == 0) {
1894 if ($contactcount) {
1895 if (!defined('RESTORE_SILENTLY')) {
1896 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
1899 while ($counter < $contactcount) {
1900 //Fetch recordset_size records in each iteration
1901 $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);
1903 foreach ($recs as $rec) {
1904 //Get the full record from backup_ids
1905 $data = backup_getid($restore->backup_unique_code
,"message_contacts",$rec->old_id
);
1907 //Now get completed xmlized object
1908 $info = $data->info
;
1909 //traverse_xmlize($info); //Debug
1910 //print_object ($GLOBALS['traverse_array']); //Debug
1911 //$GLOBALS['traverse_array']=""; //Debug
1912 //Now build the MESSAGE_CONTACTS record structure
1913 $dbrec->userid
= backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
1914 $dbrec->contactid
= backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
1915 $dbrec->blocked
= backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
1916 //We have to recode the userid field
1917 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->userid
);
1919 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
1920 $dbrec->userid
= $user->new_id
;
1922 //We have to recode the contactid field
1923 $user = backup_getid($restore->backup_unique_code
,"user",$dbrec->contactid
);
1925 //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />"; //Debug
1926 $dbrec->contactid
= $user->new_id
;
1928 //Check if the record doesn't exist in DB!
1929 $exist = get_record('message_contacts','userid',$dbrec->userid
,
1930 'contactid', $dbrec->contactid
);
1933 $status = insert_record('message_contacts',$dbrec);
1935 //Duplicate. Do nothing
1940 if ($counter %
10 == 0) {
1941 if (!defined('RESTORE_SILENTLY')) {
1943 if ($counter %
200 == 0) {
1953 if (!defined('RESTORE_SILENTLY')) {
1964 //This function creates all the categories and questions
1966 function restore_create_questions($restore,$xml_file) {
1972 if (!file_exists($xml_file)) {
1977 //info will contain the old_id of every category
1978 //in backup_ids->info will be the real info (serialized)
1979 $info = restore_read_xml_questions($restore,$xml_file);
1981 //Now, if we have anything in info, we have to restore that
1982 //categories/questions
1984 if ($info !== true) {
1985 //Iterate over each category
1986 foreach ($info as $category) {
1987 //Skip empty categories (some backups can contain them)
1988 if (!empty($category->id
)) {
1989 $catrestore = "restore_question_categories";
1990 if (function_exists($catrestore)) {
1991 //print_object ($category); //Debug
1992 $status = $catrestore($category,$restore);
1994 //Something was wrong. Function should exist.
2000 //Now we have to recode the parent field of each restored category
2001 $categories = get_records_sql("SELECT old_id, new_id
2002 FROM {$CFG->prefix}backup_ids
2003 WHERE backup_code = $restore->backup_unique_code AND
2004 table_name = 'question_categories'");
2006 foreach ($categories as $category) {
2007 $restoredcategory = get_record('question_categories','id',$category->new_id
);
2008 $restoredcategory = addslashes_object($restoredcategory);
2009 if ($restoredcategory->parent
!= 0) {
2010 $idcat = backup_getid($restore->backup_unique_code
,'question_categories',$restoredcategory->parent
);
2011 if ($idcat->new_id
) {
2012 $restoredcategory->parent
= $idcat->new_id
;
2014 $restoredcategory->parent
= 0;
2016 update_record('question_categories', $restoredcategory);
2027 //This function creates all the scales
2028 function restore_create_scales($restore,$xml_file) {
2034 if (!file_exists($xml_file)) {
2039 //scales will contain the old_id of every scale
2040 //in backup_ids->info will be the real info (serialized)
2041 $scales = restore_read_xml_scales($restore,$xml_file);
2043 //Now, if we have anything in scales, we have to restore that
2046 //Get admin->id for later use
2047 $admin = get_admin();
2048 $adminid = $admin->id
;
2049 if ($scales !== true) {
2050 //Iterate over each scale
2051 foreach ($scales as $scale) {
2052 //Get record from backup_ids
2053 $data = backup_getid($restore->backup_unique_code
,"scale",$scale->id
);
2055 $create_scale = false;
2058 //Now get completed xmlized object
2059 $info = $data->info
;
2060 //traverse_xmlize($info); //Debug
2061 //print_object ($GLOBALS['traverse_array']); //Debug
2062 //$GLOBALS['traverse_array']=""; //Debug
2064 //Now build the SCALE record structure
2065 $sca->courseid
= backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
2066 $sca->userid
= backup_todb($info['SCALE']['#']['USERID']['0']['#']);
2067 $sca->name
= backup_todb($info['SCALE']['#']['NAME']['0']['#']);
2068 $sca->scale
= backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
2069 $sca->description
= backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
2070 $sca->timemodified
= backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);
2072 //Now search if that scale exists (by scale field) in course 0 (Standar scale)
2073 //or in restore->course_id course (Personal scale)
2074 if ($sca->courseid
== 0) {
2075 $course_to_search = 0;
2077 $course_to_search = $restore->course_id
;
2079 $sca_db = get_record("scale","scale",$sca->scale
,"courseid",$course_to_search);
2080 //If it doesn't exist, create
2082 $create_scale = true;
2084 //If we must create the scale
2085 if ($create_scale) {
2086 //Me must recode the courseid if it's <> 0 (common scale)
2087 if ($sca->courseid
!= 0) {
2088 $sca->courseid
= $restore->course_id
;
2090 //We must recode the userid
2091 $user = backup_getid($restore->backup_unique_code
,"user",$sca->userid
);
2093 $sca->userid
= $user->new_id
;
2095 //Assign it to admin
2096 $sca->userid
= $adminid;
2098 //The structure is equal to the db, so insert the scale
2099 $newid = insert_record ("scale",$sca);
2101 //get current scale id
2102 $newid = $sca_db->id
;
2105 //We have the newid, update backup_ids
2106 backup_putid($restore->backup_unique_code
,"scale",
2107 $scale->id
, $newid);
2118 //This function creates all the groups
2119 function restore_create_groups($restore,$xml_file) {
2126 if (!file_exists($xml_file)) {
2131 //groups will contain the old_id of every group
2132 //in backup_ids->info will be the real info (serialized)
2133 $groups = restore_read_xml_groups($restore,$xml_file);
2135 //Now, if we have anything in groups, we have to restore that
2138 if ($groups !== true) {
2139 //Iterate over each group
2140 foreach ($groups as $group) {
2141 //Get record from backup_ids
2142 $data = backup_getid($restore->backup_unique_code
,"groups",$group->id
);
2144 $create_group = false;
2147 //Now get completed xmlized object
2148 $info = $data->info
;
2149 //traverse_xmlize($info); //Debug
2150 //print_object ($GLOBALS['traverse_array']); //Debug
2151 //$GLOBALS['traverse_array']=""; //Debug
2152 //Now build the GROUP record structure
2153 $gro = new Object();
2154 ///$gro->courseid = backup_todb($info['GROUP']['#']['COURSEID']['0']['#']);
2155 $gro->name
= backup_todb($info['GROUP']['#']['NAME']['0']['#']);
2156 $gro->description
= backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
2157 if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) {
2158 $gro->enrolmentkey
= backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']);
2159 } else { //if (! isset($gro->enrolment)) {
2160 $gro->enrolmentkey
= backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
2162 $gro->lang
= backup_todb($info['GROUP']['#']['LANG']['0']['#']);
2163 $gro->theme
= backup_todb($info['GROUP']['#']['THEME']['0']['#']);
2164 $gro->picture
= backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
2165 $gro->hidepicture
= backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
2166 $gro->timecreated
= backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
2167 $gro->timemodified
= backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
2169 //Now search if that group exists (by name and description field) in
2170 //restore->course_id course
2171 $gro_db = groups_group_matches($restore->course_id
, $gro->name
, $gro->description
);
2172 //If it doesn't exist, create
2174 $create_group = true;
2176 //If we must create the group
2177 if ($create_group) {
2178 //Me must recode the courseid to the restore->course_id
2179 $gro->courseid
= $restore->course_id
;
2181 //Check if the theme exists in destination server
2182 $themes = get_list_of_themes();
2183 if (!in_array($gro->theme
, $themes)) {
2187 //The structure is equal to the db, so insert the group
2188 $newid = groups_restore_group($restore->course_id
, $gro);
2190 //get current group id
2191 $newid = $gro_db->id
;
2194 //We have the newid, update backup_ids
2195 backup_putid($restore->backup_unique_code
,"groups",
2196 $group->id
, $newid);
2198 //Now restore members in the groups_members, only if
2199 //users are included
2200 if ($restore->users
!= 2) {
2201 $status2 = restore_create_groups_members($newid,$info,$restore);
2205 //Now, restore group_files
2206 if ($status && $status2) {
2207 $status2 = restore_group_files($restore);
2213 return ($status && $status2);
2216 //This function restores the groups_members
2217 function restore_create_groups_members($group_id,$info,$restore) {
2223 //Get the members array
2224 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
2226 //Iterate over members
2227 for($i = 0; $i < sizeof($members); $i++
) {
2228 $mem_info = $members[$i];
2229 //traverse_xmlize($mem_info); //Debug
2230 //print_object ($GLOBALS['traverse_array']); //Debug
2231 //$GLOBALS['traverse_array']=""; //Debug
2233 //Now, build the GROUPS_MEMBERS record structure
2234 $group_member = new Object();
2235 $group_member->groupid
= $group_id;
2236 $group_member->userid
= backup_todb($mem_info['#']['USERID']['0']['#']);
2237 $group_member->timeadded
= backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
2239 //We have to recode the userid field
2240 $user = backup_getid($restore->backup_unique_code
,"user",$group_member->userid
);
2242 $group_member->userid
= $user->new_id
;
2245 //The structure is equal to the db, so insert the groups_members
2246 $newid = groups_restore_member($group_member);
2248 if (($i+
1) %
50 == 0) {
2249 if (!defined('RESTORE_SILENTLY')) {
2251 if (($i+
1) %
1000 == 0) {
2266 //This function creates all the groupings
2267 function restore_create_groupings($restore,$xml_file) {
2274 if (!file_exists($xml_file)) {
2279 //groupings will contain the old_id of every group
2280 //in backup_ids->info will be the real info (serialized)
2281 $groupings = restore_read_xml_groupings($restore,$xml_file);
2283 //Now, if we have anything in groupings, we have to restore that grouping
2285 if ($groupings !== true) {
2286 //Iterate over each group
2287 foreach ($groupings as $grouping) {
2288 //Get record from backup_ids
2289 $data = backup_getid($restore->backup_unique_code
,"groupings",$grouping->id
);
2291 $create_grouping = false;
2294 //Now get completed xmlized object
2295 $info = $data->info
;
2296 //Now build the GROUPING record structure
2297 $gro = new Object();
2298 ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']);
2299 $gro->name
= backup_todb($info['GROUPING']['#']['NAME']['0']['#']);
2300 $gro->description
= backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']);
2301 $gro->timecreated
= backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']);
2303 //Now search if that group exists (by name and description field) in
2304 //restore->course_id course
2305 $gro_db = groups_grouping_matches($restore->course_id
, $gro->name
, $gro->description
);
2306 //If it doesn't exist, create
2308 $create_grouping = true;
2310 //If we must create the group
2311 if ($create_grouping) {
2313 //The structure is equal to the db, so insert the grouping TODO: RESTORE.
2314 $newid = groups_create_grouping($restore->course_id
, $gro);
2316 //get current group id
2317 $newid = $gro_db->id
;
2320 //We have the newid, update backup_ids
2321 backup_putid($restore->backup_unique_code
,"groupings",
2322 $grouping->id
, $newid);
2324 //Now restore links from groupings to groups
2325 $status2 = restore_create_groupings_groups($newid,$info,$restore);
2328 //(Now, restore grouping_files)
2333 return ($status && $status2);
2336 //This function restores the groups_members
2337 function restore_create_groupings_groups($grouping_id,$info,$restore) {
2343 //Get the members array
2344 $members = $info['GROUPING']['#']['GROUPS']['0']['#']['GROUP'];
2346 //Iterate over members
2347 for($i = 0; $i < sizeof($members); $i++
) {
2348 $mem_info = $members[$i];
2349 //Now, build the GROUPINGS_GROUPS record structure
2350 $gro_member = new Object();
2351 $gro_member->groupingid
= $grouping_id;
2352 $gro_member->groupid
= backup_todb($mem_info['#']['GROUPID']['0']['#']);
2353 $gro_member->timeadded
= backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
2355 //We have to recode the userid field
2356 ///$user = backup_getid($restore->backup_unique_code,"user",$group_member->userid);
2357 $group = backup_getid($restore->backup_unique_code
,"group",$gro_member->groupid
);
2359 $gro_member->groupid
= $group->new_id
;
2362 //The structure is equal to the db, so link the groups to the groupings. TODO: RESTORE.
2363 $newid = groups_add_group_to_grouping($gro_member->groupid
, $gro_member->groupingid
);
2365 if (($i+
1) %
50 == 0) {
2366 if (!defined('RESTORE_SILENTLY')) {
2368 if (($i+
1) %
1000 == 0) {
2383 //This function creates all the course events
2384 function restore_create_events($restore,$xml_file) {
2390 if (!file_exists($xml_file)) {
2395 //events will contain the old_id of every event
2396 //in backup_ids->info will be the real info (serialized)
2397 $events = restore_read_xml_events($restore,$xml_file);
2400 //Get admin->id for later use
2401 $admin = get_admin();
2402 $adminid = $admin->id
;
2404 //Now, if we have anything in events, we have to restore that
2407 if ($events !== true) {
2408 //Iterate over each event
2409 foreach ($events as $event) {
2410 //Get record from backup_ids
2411 $data = backup_getid($restore->backup_unique_code
,"event",$event->id
);
2413 $create_event = false;
2416 //Now get completed xmlized object
2417 $info = $data->info
;
2418 //traverse_xmlize($info); //Debug
2419 //print_object ($GLOBALS['traverse_array']); //Debug
2420 //$GLOBALS['traverse_array']=""; //Debug
2422 //if necessary, write to restorelog and adjust date/time fields
2423 if ($restore->course_startdateoffset
) {
2424 restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
2427 //Now build the EVENT record structure
2428 $eve->name
= backup_todb($info['EVENT']['#']['NAME']['0']['#']);
2429 $eve->description
= backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
2430 $eve->format
= backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
2431 $eve->courseid
= $restore->course_id
;
2432 $eve->groupid
= backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
2433 $eve->userid
= backup_todb($info['EVENT']['#']['USERID']['0']['#']);
2434 $eve->repeatid
= backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
2435 $eve->modulename
= "";
2437 $eve->eventtype
= backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
2438 $eve->timestart
= backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
2439 $eve->timeduration
= backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
2440 $eve->visible
= backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
2441 $eve->timemodified
= backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
2443 //Now search if that event exists (by description and timestart field) in
2444 //restore->course_id course
2445 $eve_db = get_record("event","courseid",$eve->courseid
,"description",$eve->description
,"timestart",$eve->timestart
);
2446 //If it doesn't exist, create
2448 $create_event = true;
2450 //If we must create the event
2451 if ($create_event) {
2453 //We must recode the userid
2454 $user = backup_getid($restore->backup_unique_code
,"user",$eve->userid
);
2456 $eve->userid
= $user->new_id
;
2458 //Assign it to admin
2459 $eve->userid
= $adminid;
2462 //We must recode the repeatid if the event has it
2463 if (!empty($eve->repeatid
)) {
2464 $repeat_rec = backup_getid($restore->backup_unique_code
,"event_repeatid",$eve->repeatid
);
2465 if ($repeat_rec) { //Exists, so use it...
2466 $eve->repeatid
= $repeat_rec->new_id
;
2467 } else { //Doesn't exists, calculate the next and save it
2468 $oldrepeatid = $eve->repeatid
;
2469 $max_rec = get_record_sql('SELECT 1, MAX(repeatid) AS repeatid FROM '.$CFG->prefix
.'event');
2470 $eve->repeatid
= empty($max_rec) ?
1 : $max_rec->repeatid +
1;
2471 backup_putid($restore->backup_unique_code
,"event_repeatid", $oldrepeatid, $eve->repeatid
);
2475 //We have to recode the groupid field
2476 $group = backup_getid($restore->backup_unique_code
,"groups",$eve->groupid
);
2478 $eve->groupid
= $group->new_id
;
2480 //Assign it to group 0
2484 //The structure is equal to the db, so insert the event
2485 $newid = insert_record ("event",$eve);
2487 //get current event id
2488 $newid = $eve_db->id
;
2491 //We have the newid, update backup_ids
2492 backup_putid($restore->backup_unique_code
,"event",
2493 $event->id
, $newid);
2504 //This function decode things to make restore multi-site fully functional
2505 //It does this conversions:
2506 // - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
2507 // |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
2509 //Note: Inter-activities linking is being implemented as a final
2510 //step in the restore execution, because we need to have it
2511 //finished to know all the oldid, newid equivaleces
2512 function restore_decode_absolute_links($content) {
2514 global $CFG,$restore;
2516 //Now decode wwwroot and file.php calls
2517 $search = array ("$@FILEPHP@$");
2519 //Check for the status of the slasharguments config variable
2520 $slash = $CFG->slasharguments
;
2522 //Build the replace string as needed
2524 $replace = array ($CFG->wwwroot
."/file.php/".$restore->course_id
);
2526 $replace = array ($CFG->wwwroot
."/file.php?file=/".$restore->course_id
);
2529 $result = str_replace($search,$replace,$content);
2531 if ($result != $content && debugging()) { //Debug
2532 if (!defined('RESTORE_SILENTLY')) {
2533 echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />'; //Debug
2540 //This function restores the userfiles from the temp (user_files) directory to the
2541 //dataroot/users directory
2542 function restore_user_files($restore) {
2550 //First, we check to "users" exists and create is as necessary
2552 $dest_dir = $CFG->dataroot
."/users";
2553 $status = check_dir_exists($dest_dir,true);
2555 //Now, we iterate over "user_files" records to check if that user dir must be
2556 //copied (and renamed) to the "users" dir.
2557 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/user_files";
2558 //Check if directory exists
2559 if (is_dir($rootdir)) {
2560 $list = list_directories ($rootdir);
2564 foreach ($list as $dir) {
2565 //Look for dir like username in backup_ids
2566 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code
,
2567 "table_name","user",
2569 //If thar user exists in backup_ids
2571 //Only it user has been created now
2572 //or if it existed previously, but he hasn't image (see bug 1123)
2573 if ((strpos($data->info
,"new") !== false) or
2574 (!check_dir_exists($dest_dir."/".$data->new_id
,false))) {
2575 //Copy the old_dir to its new location (and name) !!
2576 //Only if destination doesn't exists
2577 if (!file_exists($dest_dir."/".$data->new_id
)) {
2578 $status = backup_copy_file($rootdir."/".$dir,
2579 $dest_dir."/".$data->new_id
,true);
2583 if ($counter %
2 == 0) {
2584 if (!defined('RESTORE_SILENTLY')) {
2586 if ($counter %
40 == 0) {
2597 //If status is ok and whe have dirs created, returns counter to inform
2598 if ($status and $counter) {
2605 //This function restores the groupfiles from the temp (group_files) directory to the
2606 //dataroot/groups directory
2607 function restore_group_files($restore) {
2615 //First, we check to "groups" exists and create is as necessary
2617 $dest_dir = $CFG->dataroot
.'/groups';
2618 $status = check_dir_exists($dest_dir,true);
2620 //Now, we iterate over "group_files" records to check if that user dir must be
2621 //copied (and renamed) to the "groups" dir.
2622 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/group_files";
2623 //Check if directory exists
2624 if (is_dir($rootdir)) {
2625 $list = list_directories ($rootdir);
2629 foreach ($list as $dir) {
2630 //Look for dir like groupid in backup_ids
2631 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code
,
2632 "table_name","groups",
2634 //If that group exists in backup_ids
2636 if (!file_exists($dest_dir."/".$data->new_id
)) {
2637 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id
,true);
2641 if ($counter %
2 == 0) {
2642 if (!defined('RESTORE_SILENTLY')) {
2644 if ($counter %
40 == 0) {
2654 //If status is ok and whe have dirs created, returns counter to inform
2655 if ($status and $counter) {
2662 //This function restores the course files from the temp (course_files) directory to the
2663 //dataroot/course_id directory
2664 function restore_course_files($restore) {
2672 //First, we check to "course_id" exists and create is as necessary
2674 $dest_dir = $CFG->dataroot
."/".$restore->course_id
;
2675 $status = check_dir_exists($dest_dir,true);
2677 //Now, we iterate over "course_files" records to check if that file/dir must be
2678 //copied to the "dest_dir" dir.
2679 $rootdir = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/course_files";
2680 //Check if directory exists
2681 if (is_dir($rootdir)) {
2682 $list = list_directories_and_files ($rootdir);
2686 foreach ($list as $dir) {
2687 //Copy the dir to its new location
2688 //Only if destination file/dir doesn exists
2689 if (!file_exists($dest_dir."/".$dir)) {
2690 $status = backup_copy_file($rootdir."/".$dir,
2691 $dest_dir."/".$dir,true);
2695 if ($counter %
2 == 0) {
2696 if (!defined('RESTORE_SILENTLY')) {
2698 if ($counter %
40 == 0) {
2707 //If status is ok and whe have dirs created, returns counter to inform
2708 if ($status and $counter) {
2716 //This function creates all the structures for every module in backup file
2717 //Depending what has been selected.
2718 function restore_create_modules($restore,$xml_file) {
2723 if (!file_exists($xml_file)) {
2728 //info will contain the id and modtype of every module
2729 //in backup_ids->info will be the real info (serialized)
2730 $info = restore_read_xml_modules($restore,$xml_file);
2732 //Now, if we have anything in info, we have to restore that mods
2733 //from backup_ids (calling every mod restore function)
2735 if ($info !== true) {
2736 if (!defined('RESTORE_SILENTLY')) {
2739 //Iterate over each module
2740 foreach ($info as $mod) {
2741 if (empty($restore->mods
[$mod->modtype
]->granular
) // We don't care about per instance, i.e. restore all instances.
2742 ||
(array_key_exists($mod->id
,$restore->mods
[$mod->modtype
]->instances
)
2743 && !empty($restore->mods
[$mod->modtype
]->instances
[$mod->id
]->restore
))) {
2744 $modrestore = $mod->modtype
."_restore_mods";
2745 if (function_exists($modrestore)) { //Debug
2746 $status = $status and $modrestore($mod,$restore); //bit operator & not reliable here!
2748 //Something was wrong. Function should exist.
2753 if (!defined('RESTORE_SILENTLY')) {
2763 //This function creates all the structures for every log in backup file
2764 //Depending what has been selected.
2765 function restore_create_logs($restore,$xml_file) {
2769 //Number of records to get in every chunk
2770 $recordset_size = 4;
2771 //Counter, points to current record
2773 //To count all the recods to restore
2778 if (!file_exists($xml_file)) {
2783 //count_logs will contain the number of logs entries to process
2784 //in backup_ids->info will be the real info (serialized)
2785 $count_logs = restore_read_xml_logs($restore,$xml_file);
2788 //Now, if we have records in count_logs, we have to restore that logs
2789 //from backup_ids. This piece of code makes calls to:
2790 // - restore_log_course() if it's a course log
2791 // - restore_log_user() if it's a user log
2792 // - restore_log_module() if it's a module log.
2793 //And all is segmented in chunks to allow large recordsets to be restored !!
2794 if ($count_logs > 0) {
2795 while ($counter < $count_logs) {
2796 //Get a chunk of records
2797 //Take old_id twice to avoid adodb limitation
2798 $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);
2802 foreach ($logs as $log) {
2803 //Get the full record from backup_ids
2804 $data = backup_getid($restore->backup_unique_code
,"log",$log->old_id
);
2806 //Now get completed xmlized object
2807 $info = $data->info
;
2808 //traverse_xmlize($info); //Debug
2809 //print_object ($GLOBALS['traverse_array']); //Debug
2810 //$GLOBALS['traverse_array']=""; //Debug
2811 //Now build the LOG record structure
2812 $dblog->time
= backup_todb($info['LOG']['#']['TIME']['0']['#']);
2813 $dblog->userid
= backup_todb($info['LOG']['#']['USERID']['0']['#']);
2814 $dblog->ip
= backup_todb($info['LOG']['#']['IP']['0']['#']);
2815 $dblog->course
= $restore->course_id
;
2816 $dblog->module
= backup_todb($info['LOG']['#']['MODULE']['0']['#']);
2817 $dblog->cmid
= backup_todb($info['LOG']['#']['CMID']['0']['#']);
2818 $dblog->action
= backup_todb($info['LOG']['#']['ACTION']['0']['#']);
2819 $dblog->url
= backup_todb($info['LOG']['#']['URL']['0']['#']);
2820 $dblog->info
= backup_todb($info['LOG']['#']['INFO']['0']['#']);
2821 //We have to recode the userid field
2822 $user = backup_getid($restore->backup_unique_code
,"user",$dblog->userid
);
2824 //echo "User ".$dblog->userid." to user ".$user->new_id."<br />"; //Debug
2825 $dblog->userid
= $user->new_id
;
2827 //We have to recode the cmid field (if module isn't "course" or "user")
2828 if ($dblog->module
!= "course" and $dblog->module
!= "user") {
2829 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$dblog->cmid
);
2831 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
2832 $dblog->cmid
= $cm->new_id
;
2837 //print_object ($dblog); //Debug
2838 //Now, we redirect to the needed function to make all the work
2839 if ($dblog->module
== "course") {
2840 //It's a course log,
2841 $stat = restore_log_course($restore,$dblog);
2842 } elseif ($dblog->module
== "user") {
2844 $stat = restore_log_user($restore,$dblog);
2846 //It's a module log,
2847 $stat = restore_log_module($restore,$dblog);
2853 if ($counter %
10 == 0) {
2854 if (!defined('RESTORE_SILENTLY')) {
2856 if ($counter %
200 == 0) {
2864 //We never should arrive here
2865 $counter = $count_logs;
2874 //This function inserts a course log record, calculating the URL field as necessary
2875 function restore_log_course($restore,$log) {
2880 //echo "<hr />Before transformations<br />"; //Debug
2881 //print_object($log); //Debug
2882 //Depending of the action, we recode different things
2883 switch ($log->action
) {
2885 $log->url
= "view.php?id=".$log->course
;
2886 $log->info
= $log->course
;
2890 $log->url
= "view.php?id=".$log->course
;
2894 //recode the info field (it's the user id)
2895 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
2897 $log->info
= $user->new_id
;
2898 //Now, extract the mode from the url field
2899 $mode = substr(strrchr($log->url
,"="),1);
2900 $log->url
= "user.php?id=".$log->course
."&user=".$log->info
."&mode=".$mode;
2905 //Extract the course_module from the url field
2906 $cmid = substr(strrchr($log->url
,"="),1);
2907 //recode the course_module to see it it has been restored
2908 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$cmid);
2910 $cmid = $cm->new_id
;
2911 //Extract the module name and the module id from the info field
2912 $modname = strtok($log->info
," ");
2913 $modid = strtok(" ");
2914 //recode the module id to see if it has been restored
2915 $mod = backup_getid($restore->backup_unique_code
,$modname,$modid);
2917 $modid = $mod->new_id
;
2918 //Now I have everything so reconstruct url and info
2919 $log->info
= $modname." ".$modid;
2920 $log->url
= "../mod/".$modname."/view.php?id=".$cmid;
2926 //Extract the course_module from the url field
2927 $cmid = substr(strrchr($log->url
,"="),1);
2928 //recode the course_module to see it it has been restored
2929 $cm = backup_getid($restore->backup_unique_code
,"course_modules",$cmid);
2931 $cmid = $cm->new_id
;
2932 //Extract the module name and the module id from the info field
2933 $modname = strtok($log->info
," ");
2934 $modid = strtok(" ");
2935 //recode the module id to see if it has been restored
2936 $mod = backup_getid($restore->backup_unique_code
,$modname,$modid);
2938 $modid = $mod->new_id
;
2939 //Now I have everything so reconstruct url and info
2940 $log->info
= $modname." ".$modid;
2941 $log->url
= "../mod/".$modname."/view.php?id=".$cmid;
2947 $log->url
= "view.php?id=".$log->course
;
2951 $log->url
= "edit.php?id=".$log->course
;
2956 //recode the info field (it's the user id)
2957 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
2959 $log->info
= $user->new_id
;
2960 $log->url
= "view.php?id=".$log->course
;
2965 //recode the info field (it's the user id)
2966 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
2968 $log->info
= $user->new_id
;
2969 $log->url
= "view.php?id=".$log->course
;
2974 //Extract the course_section from the url field
2975 $secid = substr(strrchr($log->url
,"="),1);
2976 //recode the course_section to see if it has been restored
2977 $sec = backup_getid($restore->backup_unique_code
,"course_sections",$secid);
2979 $secid = $sec->new_id
;
2980 //Now I have everything so reconstruct url and info
2981 $log->url
= "editsection.php?id=".$secid;
2986 $log->url
= "view.php?id=".$log->course
;
2991 $log->url
= "recent.php?id=".$log->course
;
2996 $log->url
= "report/log/index.php?id=".$log->course
;
2997 $log->info
= $log->course
;
3001 $log->url
= "report/log/live.php?id=".$log->course
;
3002 $log->info
= $log->course
;
3005 case "report outline":
3006 $log->url
= "report/outline/index.php?id=".$log->course
;
3007 $log->info
= $log->course
;
3010 case "report participation":
3011 $log->url
= "report/participation/index.php?id=".$log->course
;
3012 $log->info
= $log->course
;
3015 case "report stats":
3016 $log->url
= "report/stats/index.php?id=".$log->course
;
3017 $log->info
= $log->course
;
3021 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
3025 //echo "After transformations<br />"; //Debug
3026 //print_object($log); //Debug
3028 //Now if $toinsert is set, insert the record
3030 //echo "Inserting record<br />"; //Debug
3031 $status = insert_record("log",$log);
3036 //This function inserts a user log record, calculating the URL field as necessary
3037 function restore_log_user($restore,$log) {
3042 //echo "<hr />Before transformations<br />"; //Debug
3043 //print_object($log); //Debug
3044 //Depending of the action, we recode different things
3045 switch ($log->action
) {
3047 //recode the info field (it's the user id)
3048 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3050 $log->info
= $user->new_id
;
3051 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3055 case "change password":
3056 //recode the info field (it's the user id)
3057 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3059 $log->info
= $user->new_id
;
3060 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3065 //recode the info field (it's the user id)
3066 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3068 $log->info
= $user->new_id
;
3069 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3074 //recode the info field (it's the user id)
3075 $user = backup_getid($restore->backup_unique_code
,"user",$log->info
);
3077 $log->info
= $user->new_id
;
3078 $log->url
= "view.php?id=".$log->info
."&course=".$log->course
;
3083 $log->url
= "view.php?id=".$log->course
;
3087 //We split the url by ampersand char
3088 $first_part = strtok($log->url
,"&");
3089 //Get data after the = char. It's the user being updated
3090 $userid = substr(strrchr($first_part,"="),1);
3092 $user = backup_getid($restore->backup_unique_code
,"user",$userid);
3095 $log->url
= "view.php?id=".$user->new_id
."&course=".$log->course
;
3100 echo "action (".$log->module
."-".$log->action
.") unknown. Not restored<br />"; //Debug
3104 //echo "After transformations<br />"; //Debug
3105 //print_object($log); //Debug
3107 //Now if $toinsert is set, insert the record
3109 //echo "Inserting record<br />"; //Debug
3110 $status = insert_record("log",$log);
3115 //This function inserts a module log record, calculating the URL field as necessary
3116 function restore_log_module($restore,$log) {
3121 //echo "<hr />Before transformations<br />"; //Debug
3122 //print_object($log); //Debug
3124 //Now we see if the required function in the module exists
3125 $function = $log->module
."_restore_logs";
3126 if (function_exists($function)) {
3128 $log = $function($restore,$log);
3129 //If everything is ok, mark the insert flag
3135 //echo "After transformations<br />"; //Debug
3136 //print_object($log); //Debug
3138 //Now if $toinsert is set, insert the record
3140 //echo "Inserting record<br />"; //Debug
3141 $status = insert_record("log",$log);
3146 //This function adjusts the instance field into course_modules. It's executed after
3147 //modules restore. There, we KNOW the new instance id !!
3148 function restore_check_instances($restore) {
3154 //We are going to iterate over each course_module saved in backup_ids
3155 $course_modules = get_records_sql("SELECT old_id,new_id
3156 FROM {$CFG->prefix}backup_ids
3157 WHERE backup_code = '$restore->backup_unique_code' AND
3158 table_name = 'course_modules'");
3159 if ($course_modules) {
3160 foreach($course_modules as $cm) {
3161 //Get full record, using backup_getids
3162 $cm_module = backup_getid($restore->backup_unique_code
,"course_modules",$cm->old_id
);
3163 //Now we are going to the REAL course_modules to get its type (field module)
3164 $module = get_record("course_modules","id",$cm_module->new_id
);
3166 //We know the module type id. Get the name from modules
3167 $type = get_record("modules","id",$module->module
);
3169 //We know the type name and the old_id. Get its new_id
3170 //from backup_ids. It's the instance !!!
3171 $instance = backup_getid($restore->backup_unique_code
,$type->name
,$cm_module->info
);
3173 //We have the new instance, so update the record in course_modules
3174 $module->instance
= $instance->new_id
;
3175 //print_object ($module); //Debug
3176 $status = update_record("course_modules",$module);
3193 //=====================================================================================
3195 //== XML Functions (SAX) ==
3197 //=====================================================================================
3199 //This is the class used to do all the xml parse
3200 class MoodleParser
{
3202 var $level = 0; //Level we are
3203 var $counter = 0; //Counter
3204 var $tree = array(); //Array of levels we are
3205 var $content = ""; //Content under current level
3206 var $todo = ""; //What we hav to do when parsing
3207 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
3208 var $temp = ""; //Temp storage.
3209 var $preferences = ""; //Preferences about what to load !!
3210 var $finished = false; //Flag to say xml_parse to stop
3212 //This function is used to get the current contents property value
3213 //They are trimed (and converted from utf8 if needed)
3214 function getContents() {
3215 return trim($this->content
);
3218 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3219 function startElementInfo($parser, $tagName, $attrs) {
3220 //Refresh properties
3222 $this->tree
[$this->level
] = $tagName;
3224 //Output something to avoid browser timeouts...
3227 //Check if we are into INFO zone
3228 //if ($this->tree[2] == "INFO") //Debug
3229 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3232 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3233 function startElementRoles($parser, $tagName, $attrs) {
3234 //Refresh properties
3236 $this->tree
[$this->level
] = $tagName;
3238 //Output something to avoid browser timeouts...
3241 //Check if we are into INFO zone
3242 //if ($this->tree[2] == "INFO") //Debug
3243 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3247 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
3248 function startElementCourseHeader($parser, $tagName, $attrs) {
3249 //Refresh properties
3251 $this->tree
[$this->level
] = $tagName;
3253 //Output something to avoid browser timeouts...
3256 //Check if we are into COURSE_HEADER zone
3257 //if ($this->tree[3] == "HEADER") //Debug
3258 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3261 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
3262 function startElementBlocks($parser, $tagName, $attrs) {
3263 //Refresh properties
3265 $this->tree
[$this->level
] = $tagName;
3267 //Output something to avoid browser timeouts...
3270 //Check if we are into BLOCKS zone
3271 //if ($this->tree[3] == "BLOCKS") //Debug
3272 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3275 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
3276 function startElementSections($parser, $tagName, $attrs) {
3277 //Refresh properties
3279 $this->tree
[$this->level
] = $tagName;
3281 //Output something to avoid browser timeouts...
3284 //Check if we are into SECTIONS zone
3285 //if ($this->tree[3] == "SECTIONS") //Debug
3286 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3289 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
3290 function startElementFormatData($parser, $tagName, $attrs) {
3291 //Refresh properties
3293 $this->tree
[$this->level
] = $tagName;
3295 //Output something to avoid browser timeouts...
3298 //Accumulate all the data inside this tag
3299 if (isset($this->tree
[3]) && $this->tree
[3] == "FORMATDATA") {
3300 if (!isset($this->temp
)) {
3303 $this->temp
.= "<".$tagName.">";
3306 //Check if we are into FORMATDATA zone
3307 //if ($this->tree[3] == "FORMATDATA") //Debug
3308 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3311 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
3312 function startElementMetacourse($parser, $tagName, $attrs) {
3314 //Refresh properties
3316 $this->tree
[$this->level
] = $tagName;
3318 //Output something to avoid browser timeouts...
3321 //Check if we are into METACOURSE zone
3322 //if ($this->tree[3] == "METACOURSE") //Debug
3323 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3326 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
3327 function startElementGradebook($parser, $tagName, $attrs) {
3329 //Refresh properties
3331 $this->tree
[$this->level
] = $tagName;
3333 //Output something to avoid browser timeouts...
3336 //Check if we are into GRADEBOOK zone
3337 //if ($this->tree[3] == "GRADEBOOK") //Debug
3338 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3340 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
3341 if (isset($this->tree
[5]) and isset($this->tree
[3])) {
3342 if (($this->tree
[5] == "GRADE_PREFERENCE" ||
$this->tree
[5] == "GRADE_LETTER" ||
$this->tree
[5] == "GRADE_CATEGORY" ) && ($this->tree
[3] == "GRADEBOOK")) {
3343 if (!isset($this->temp
)) {
3346 $this->temp
.= "<".$tagName.">";
3352 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
3353 function startElementUsers($parser, $tagName, $attrs) {
3354 //Refresh properties
3356 $this->tree
[$this->level
] = $tagName;
3358 //Check if we are into USERS zone
3359 //if ($this->tree[3] == "USERS") //Debug
3360 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3363 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
3364 function startElementMessages($parser, $tagName, $attrs) {
3365 //Refresh properties
3367 $this->tree
[$this->level
] = $tagName;
3369 //Output something to avoid browser timeouts...
3372 //Check if we are into MESSAGES zone
3373 //if ($this->tree[3] == "MESSAGES") //Debug
3374 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3376 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
3377 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3378 if (($this->tree
[4] == "MESSAGE" ||
$this->tree
[5] == "CONTACT" ) and ($this->tree
[3] == "MESSAGES")) {
3379 if (!isset($this->temp
)) {
3382 $this->temp
.= "<".$tagName.">";
3386 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
3387 function startElementQuestions($parser, $tagName, $attrs) {
3388 //Refresh properties
3390 $this->tree
[$this->level
] = $tagName;
3392 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
3393 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
3396 //Output something to avoid browser timeouts...
3399 //Check if we are into QUESTION_CATEGORIES zone
3400 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
3401 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3403 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
3404 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3405 if (($this->tree
[4] == "QUESTION_CATEGORY") and ($this->tree
[3] == "QUESTION_CATEGORIES")) {
3406 if (!isset($this->temp
)) {
3409 $this->temp
.= "<".$tagName.">";
3414 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
3415 function startElementScales($parser, $tagName, $attrs) {
3416 //Refresh properties
3418 $this->tree
[$this->level
] = $tagName;
3420 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
3421 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
3424 //Output something to avoid browser timeouts...
3427 //Check if we are into SCALES zone
3428 //if ($this->tree[3] == "SCALES") //Debug
3429 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3431 //If we are under a SCALE tag under a SCALES zone, accumule it
3432 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3433 if (($this->tree
[4] == "SCALE") and ($this->tree
[3] == "SCALES")) {
3434 if (!isset($this->temp
)) {
3437 $this->temp
.= "<".$tagName.">";
3442 function startElementGroups($parser, $tagName, $attrs) {
3443 //Refresh properties
3445 $this->tree
[$this->level
] = $tagName;
3447 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
3448 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
3451 //Output something to avoid browser timeouts...
3454 //Check if we are into GROUPS zone
3455 //if ($this->tree[3] == "GROUPS") //Debug
3456 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3458 //If we are under a GROUP tag under a GROUPS zone, accumule it
3459 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3460 if (($this->tree
[4] == "GROUP") and ($this->tree
[3] == "GROUPS")) {
3461 if (!isset($this->temp
)) {
3464 $this->temp
.= "<".$tagName.">";
3469 function startElementGroupings($parser, $tagName, $attrs) { //TODO:
3470 //Refresh properties
3472 $this->tree
[$this->level
] = $tagName;
3474 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
3475 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
3478 //Output something to avoid browser timeouts...
3481 //Check if we are into GROUPINGS zone
3482 //if ($this->tree[3] == "GROUPINGS") //Debug
3483 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3485 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
3486 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3487 if (($this->tree
[4] == "GROUPING") and ($this->tree
[3] == "GROUPINGS")) {
3488 if (!isset($this->temp
)) {
3491 $this->temp
.= "<".$tagName.">";
3496 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
3497 function startElementEvents($parser, $tagName, $attrs) {
3498 //Refresh properties
3500 $this->tree
[$this->level
] = $tagName;
3502 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
3503 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
3506 //Output something to avoid browser timeouts...
3509 //Check if we are into EVENTS zone
3510 //if ($this->tree[3] == "EVENTS") //Debug
3511 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3513 //If we are under a EVENT tag under a EVENTS zone, accumule it
3514 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3515 if (($this->tree
[4] == "EVENT") and ($this->tree
[3] == "EVENTS")) {
3516 if (!isset($this->temp
)) {
3519 $this->temp
.= "<".$tagName.">";
3524 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
3525 function startElementModules($parser, $tagName, $attrs) {
3526 //Refresh properties
3528 $this->tree
[$this->level
] = $tagName;
3530 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
3531 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
3534 //Output something to avoid browser timeouts...
3537 //Check if we are into MODULES zone
3538 //if ($this->tree[3] == "MODULES") //Debug
3539 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3541 //If we are under a MOD tag under a MODULES zone, accumule it
3542 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3543 if (($this->tree
[4] == "MOD") and ($this->tree
[3] == "MODULES")) {
3544 if (!isset($this->temp
)) {
3547 $this->temp
.= "<".$tagName.">";
3552 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
3553 function startElementLogs($parser, $tagName, $attrs) {
3554 //Refresh properties
3556 $this->tree
[$this->level
] = $tagName;
3558 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
3559 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
3562 //Output something to avoid browser timeouts...
3565 //Check if we are into LOGS zone
3566 //if ($this->tree[3] == "LOGS") //Debug
3567 // echo $this->level.str_repeat(" ",$this->level*2)."<".$tagName."><br />\n"; //Debug
3569 //If we are under a LOG tag under a LOGS zone, accumule it
3570 if (isset($this->tree
[4]) and isset($this->tree
[3])) {
3571 if (($this->tree
[4] == "LOG") and ($this->tree
[3] == "LOGS")) {
3572 if (!isset($this->temp
)) {
3575 $this->temp
.= "<".$tagName.">";
3580 //This is the startTag default handler we use when todo is undefined
3581 function startElement($parser, $tagName, $attrs) {
3583 $this->tree
[$this->level
] = $tagName;
3585 //Output something to avoid browser timeouts...
3588 echo $this->level
.str_repeat(" ",$this->level
*2)."<".$tagName."><br />\n"; //Debug
3591 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
3592 function endElementInfo($parser, $tagName) {
3593 //Check if we are into INFO zone
3594 if ($this->tree
[2] == "INFO") {
3595 //if (trim($this->content)) //Debug
3596 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
3597 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
3598 //Dependig of different combinations, do different things
3599 if ($this->level
== 3) {
3602 $this->info
->backup_name
= $this->getContents();
3604 case "MOODLE_VERSION":
3605 $this->info
->backup_moodle_version
= $this->getContents();
3607 case "MOODLE_RELEASE":
3608 $this->info
->backup_moodle_release
= $this->getContents();
3610 case "BACKUP_VERSION":
3611 $this->info
->backup_backup_version
= $this->getContents();
3613 case "BACKUP_RELEASE":
3614 $this->info
->backup_backup_release
= $this->getContents();
3617 $this->info
->backup_date
= $this->getContents();
3619 case "ORIGINAL_WWWROOT":
3620 $this->info
->original_wwwroot
= $this->getContents();
3622 case "MNET_EXTERNALUSERS":
3623 $this->info
->mnet_externalusers
= $this->getContents();
3627 if ($this->tree
[3] == "DETAILS") {
3628 if ($this->level
== 4) {
3631 $this->info
->backup_metacourse
= $this->getContents();
3634 $this->info
->backup_users
= $this->getContents();
3637 $this->info
->backup_logs
= $this->getContents();
3640 $this->info
->backup_user_files
= $this->getContents();
3643 $this->info
->backup_course_files
= $this->getContents();
3646 $this->info
->backup_messages
= $this->getContents();
3649 $this->info
->backup_block_format
= $this->getContents();
3653 if ($this->level
== 5) {
3656 $this->info
->tempName
= $this->getContents();
3659 $this->info
->mods
[$this->info
->tempName
]->backup
= $this->getContents();
3662 $this->info
->mods
[$this->info
->tempName
]->userinfo
= $this->getContents();
3666 if ($this->level
== 7) {
3669 $this->info
->tempId
= $this->getContents();
3670 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->id
= $this->info
->tempId
;
3673 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->name
= $this->getContents();
3676 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->backup
= $this->getContents();
3679 $this->info
->mods
[$this->info
->tempName
]->instances
[$this->info
->tempId
]->userinfo
= $this->getContents();
3686 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
3687 //Speed up a lot (avoid parse all)
3688 if ($tagName == "INFO") {
3689 $this->finished
= true;
3693 $this->tree
[$this->level
] = "";
3695 $this->content
= "";
3699 function endElementRoles($parser, $tagName) {
3700 //Check if we are into INFO zone
3701 if ($this->tree
[2] == "ROLES") {
3703 if ($this->tree
[3] == "ROLE") {
3704 if ($this->level
== 4) {
3707 $this->info
->tempname
= $this->getContents();
3711 $this->info
->tempshortname
= $this->getContents();
3713 case "ID": // this is the old id
3714 $this->info
->tempid
= $this->getContents();
3718 if ($this->level
== 6) {
3721 $this->info
->roles
[$this->info
->tempid
]->name
= $this->info
->tempname
;
3722 $this->info
->roles
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
3724 $this->info
->tempcapname
= $this->getContents();
3725 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->name
= $this->getContents();
3728 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->permission
= $this->getContents();
3730 case "TIMEMODIFIED":
3731 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->timemodified
= $this->getContents();
3734 $this->info
->roles
[$this->info
->tempid
]->capabilities
[$this->info
->tempcapname
]->modifierid
= $this->getContents();
3741 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
3742 //Speed up a lot (avoid parse all)
3743 if ($tagName == "ROLES") {
3744 $this->finished
= true;
3748 $this->tree
[$this->level
] = "";
3750 $this->content
= "";
3754 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
3755 function endElementCourseHeader($parser, $tagName) {
3756 //Check if we are into COURSE_HEADER zone
3757 if ($this->tree
[3] == "HEADER") {
3758 //if (trim($this->content)) //Debug
3759 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
3760 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
3761 //Dependig of different combinations, do different things
3762 if ($this->level
== 4) {
3765 $this->info
->course_id
= $this->getContents();
3768 $this->info
->course_password
= $this->getContents();
3771 $this->info
->course_fullname
= $this->getContents();
3774 $this->info
->course_shortname
= $this->getContents();
3777 $this->info
->course_idnumber
= $this->getContents();
3780 $this->info
->course_summary
= $this->getContents();
3783 $this->info
->course_format
= $this->getContents();
3786 $this->info
->course_showgrades
= $this->getContents();
3789 $this->info
->blockinfo
= $this->getContents();
3792 $this->info
->course_newsitems
= $this->getContents();
3795 $this->info
->course_teacher
= $this->getContents();
3798 $this->info
->course_teachers
= $this->getContents();
3801 $this->info
->course_student
= $this->getContents();
3804 $this->info
->course_students
= $this->getContents();
3807 $this->info
->course_guest
= $this->getContents();
3810 $this->info
->course_startdate
= $this->getContents();
3813 $this->info
->course_enrolperiod
= $this->getContents();
3816 $this->info
->course_numsections
= $this->getContents();
3818 //case "SHOWRECENT": INFO: This is out in 1.3
3819 // $this->info->course_showrecent = $this->getContents();
3822 $this->info
->course_maxbytes
= $this->getContents();
3825 $this->info
->course_showreports
= $this->getContents();
3828 $this->info
->course_groupmode
= $this->getContents();
3830 case "GROUPMODEFORCE":
3831 $this->info
->course_groupmodeforce
= $this->getContents();
3834 $this->info
->course_lang
= $this->getContents();
3837 $this->info
->course_theme
= $this->getContents();
3840 $this->info
->course_cost
= $this->getContents();
3843 $this->info
->course_currency
= $this->getContents();
3846 $this->info
->course_marker
= $this->getContents();
3849 $this->info
->course_visible
= $this->getContents();
3851 case "HIDDENSECTIONS":
3852 $this->info
->course_hiddensections
= $this->getContents();
3855 $this->info
->course_timecreated
= $this->getContents();
3857 case "TIMEMODIFIED":
3858 $this->info
->course_timemodified
= $this->getContents();
3861 $this->info
->course_metacourse
= $this->getContents();
3865 if ($this->tree
[4] == "CATEGORY") {
3866 if ($this->level
== 5) {
3869 $this->info
->category
->id
= $this->getContents();
3872 $this->info
->category
->name
= $this->getContents();
3878 if ($this->tree
[4] == "ROLES_ASSIGNMENTS") {
3879 if ($this->level
== 6) {
3882 $this->info
->tempname
= $this->getContents();
3885 $this->info
->tempshortname
= $this->getContents();
3888 $this->info
->tempid
= $this->getContents();
3893 if ($this->level
== 8) {
3896 $this->info
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
3897 $this->info
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
3898 $this->info
->tempuser
= $this->getContents();
3899 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
3902 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
3905 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
3908 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
3910 case "TIMEMODIFIED":
3911 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
3914 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
3917 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
3920 $this->info
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
3925 } /// ends role_assignments
3927 if ($this->tree
[4] == "ROLES_OVERRIDES") {
3928 if ($this->level
== 6) {
3931 $this->info
->tempname
= $this->getContents();
3934 $this->info
->tempshortname
= $this->getContents();
3937 $this->info
->tempid
= $this->getContents();
3942 if ($this->level
== 8) {
3945 $this->info
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
3946 $this->info
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
3947 $this->info
->tempname
= $this->getContents(); // change to name of capability
3948 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
3951 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
3953 case "TIMEMODIFIED":
3954 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
3957 $this->info
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
3961 } /// ends role_overrides
3964 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
3965 //Speed up a lot (avoid parse all)
3966 if ($tagName == "HEADER") {
3967 $this->finished
= true;
3971 $this->tree
[$this->level
] = "";
3973 $this->content
= "";
3977 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
3978 function endElementBlocks($parser, $tagName) {
3979 //Check if we are into BLOCKS zone
3980 if ($this->tree
[3] == 'BLOCKS') {
3981 //if (trim($this->content)) //Debug
3982 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
3983 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
3984 //Dependig of different combinations, do different things
3985 if ($this->level
== 4) {
3988 //We've finalized a block, get it
3989 $this->info
->instances
[] = $this->info
->tempinstance
;
3990 unset($this->info
->tempinstance
);
3996 if ($this->level
== 5) {
3999 $this->info
->tempinstance
->id
= $this->getContents();
4001 $this->info
->tempinstance
->name
= $this->getContents();
4004 $this->info
->tempinstance
->pageid
= $this->getContents();
4007 $this->info
->tempinstance
->pagetype
= $this->getContents();
4010 $this->info
->tempinstance
->position
= $this->getContents();
4013 $this->info
->tempinstance
->weight
= $this->getContents();
4016 $this->info
->tempinstance
->visible
= $this->getContents();
4019 $this->info
->tempinstance
->configdata
= $this->getContents();
4026 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
4027 if ($this->level
== 7) {
4030 $this->info
->tempname
= $this->getContents();
4033 $this->info
->tempshortname
= $this->getContents();
4036 $this->info
->tempid
= $this->getContents(); // temp roleid
4041 if ($this->level
== 9) {
4045 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4047 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4049 $this->info
->tempuser
= $this->getContents();
4051 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
4054 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
4057 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
4060 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
4062 case "TIMEMODIFIED":
4063 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
4066 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
4069 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
4072 $this->info
->tempinstance
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
4077 } /// ends role_assignments
4079 if ($this->tree
[5] == "ROLES_OVERRIDES") {
4080 if ($this->level
== 7) {
4083 $this->info
->tempname
= $this->getContents();
4086 $this->info
->tempshortname
= $this->getContents();
4089 $this->info
->tempid
= $this->getContents(); // temp roleid
4094 if ($this->level
== 9) {
4098 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4099 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4100 $this->info
->tempname
= $this->getContents(); // change to name of capability
4101 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4104 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4106 case "TIMEMODIFIED":
4107 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4110 $this->info
->tempinstance
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
4114 } /// ends role_overrides
4117 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
4118 //Speed up a lot (avoid parse all)
4119 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
4120 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
4121 if ($this->tree
[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
4122 $this->finished
= true;
4126 $this->tree
[$this->level
] = '';
4128 $this->content
= "";
4131 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
4132 function endElementSections($parser, $tagName) {
4133 //Check if we are into SECTIONS zone
4134 if ($this->tree
[3] == "SECTIONS") {
4135 //if (trim($this->content)) //Debug
4136 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4137 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4138 //Dependig of different combinations, do different things
4139 if ($this->level
== 4) {
4142 //We've finalized a section, get it
4143 $this->info
->sections
[$this->info
->tempsection
->id
] = $this->info
->tempsection
;
4144 unset($this->info
->tempsection
);
4147 if ($this->level
== 5) {
4150 $this->info
->tempsection
->id
= $this->getContents();
4153 $this->info
->tempsection
->number
= $this->getContents();
4156 $this->info
->tempsection
->summary
= $this->getContents();
4159 $this->info
->tempsection
->visible
= $this->getContents();
4163 if ($this->level
== 6) {
4166 //We've finalized a mod, get it
4167 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->type
=
4168 $this->info
->tempmod
->type
;
4169 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->instance
=
4170 $this->info
->tempmod
->instance
;
4171 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->added
=
4172 $this->info
->tempmod
->added
;
4173 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->score
=
4174 $this->info
->tempmod
->score
;
4175 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->indent
=
4176 $this->info
->tempmod
->indent
;
4177 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->visible
=
4178 $this->info
->tempmod
->visible
;
4179 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->groupmode
=
4180 $this->info
->tempmod
->groupmode
;
4181 unset($this->info
->tempmod
);
4184 if ($this->level
== 7) {
4187 $this->info
->tempmod
->id
= $this->getContents();
4190 $this->info
->tempmod
->type
= $this->getContents();
4193 $this->info
->tempmod
->instance
= $this->getContents();
4196 $this->info
->tempmod
->added
= $this->getContents();
4199 $this->info
->tempmod
->score
= $this->getContents();
4202 $this->info
->tempmod
->indent
= $this->getContents();
4205 $this->info
->tempmod
->visible
= $this->getContents();
4208 $this->info
->tempmod
->groupmode
= $this->getContents();
4215 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_ASSIGNMENTS") {
4217 if ($this->level
== 9) {
4220 $this->info
->tempname
= $this->getContents();
4223 $this->info
->tempshortname
= $this->getContents();
4226 $this->info
->tempid
= $this->getContents(); // temp roleid
4231 if ($this->level
== 11) {
4234 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4236 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4238 $this->info
->tempuser
= $this->getContents();
4240 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->userid
= $this->getContents();
4243 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->hidden
= $this->getContents();
4246 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timestart
= $this->getContents();
4249 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timeend
= $this->getContents();
4251 case "TIMEMODIFIED":
4252 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->timemodified
= $this->getContents();
4255 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->modifierid
= $this->getContents();
4258 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->enrol
= $this->getContents();
4261 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuser
]->sortorder
= $this->getContents();
4266 } /// ends role_assignments
4268 if (isset($this->tree
[7]) && $this->tree
[7] == "ROLES_OVERRIDES") {
4269 if ($this->level
== 9) {
4272 $this->info
->tempname
= $this->getContents();
4275 $this->info
->tempshortname
= $this->getContents();
4278 $this->info
->tempid
= $this->getContents(); // temp roleid
4283 if ($this->level
== 11) {
4287 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4288 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4289 $this->info
->tempname
= $this->getContents(); // change to name of capability
4290 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4293 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4295 case "TIMEMODIFIED":
4296 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4299 $this->info
->tempsection
->mods
[$this->info
->tempmod
->id
]->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
4303 } /// ends role_overrides
4307 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
4308 //Speed up a lot (avoid parse all)
4309 if ($tagName == "SECTIONS") {
4310 $this->finished
= true;
4314 $this->tree
[$this->level
] = "";
4316 $this->content
= "";
4320 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4321 function endElementFormatData($parser, $tagName) {
4322 //Check if we are into FORMATDATA zone
4323 if ($this->tree
[3] == 'FORMATDATA') {
4324 if (!isset($this->temp
)) {
4327 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
4330 if($tagName=='FORMATDATA') {
4331 //Did we have any data? If not don't bother
4332 if($this->temp
!='<FORMATDATA></FORMATDATA>') {
4333 //Prepend XML standard header to info gathered
4334 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4337 //Call to xmlize for this portion of xml data (the FORMATDATA block)
4338 $this->info
->format_data
= xmlize($xml_data,0);
4340 //Stop parsing at end of FORMATDATA
4341 $this->finished
=true;
4345 $this->tree
[$this->level
] = "";
4347 $this->content
= "";
4350 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4351 function endElementMetacourse($parser, $tagName) {
4352 //Check if we are into METACOURSE zone
4353 if ($this->tree
[3] == 'METACOURSE') {
4354 //if (trim($this->content)) //Debug
4355 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4356 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4357 //Dependig of different combinations, do different things
4358 if ($this->level
== 5) {
4361 //We've finalized a child, get it
4362 $this->info
->childs
[] = $this->info
->tempmeta
;
4363 unset($this->info
->tempmeta
);
4366 //We've finalized a parent, get it
4367 $this->info
->parents
[] = $this->info
->tempmeta
;
4368 unset($this->info
->tempmeta
);
4374 if ($this->level
== 6) {
4377 $this->info
->tempmeta
->id
= $this->getContents();
4380 $this->info
->tempmeta
->idnumber
= $this->getContents();
4383 $this->info
->tempmeta
->shortname
= $this->getContents();
4389 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
4390 //Speed up a lot (avoid parse all)
4391 if ($this->tree
[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
4392 $this->finished
= true;
4396 $this->tree
[$this->level
] = '';
4398 $this->content
= "";
4401 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4402 function endElementGradebook($parser, $tagName) {
4403 //Check if we are into GRADEBOOK zone
4404 if ($this->tree
[3] == "GRADEBOOK") {
4405 //if (trim($this->content)) //Debug
4406 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4407 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
4408 //Acumulate data to info (content + close tag)
4409 //Reconvert: strip htmlchars again and trim to generate xml data
4410 if (!isset($this->temp
)) {
4413 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
4414 //We have finished preferences, letters or categories, reset accumulated
4415 //data because they are close tags
4416 if ($this->level
== 4) {
4419 //If we've finished a message, xmlize it an save to db
4420 if (($this->level
== 5) and ($tagName == "GRADE_PREFERENCE")) {
4421 //Prepend XML standard header to info gathered
4422 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4423 //Call to xmlize for this portion of xml data (one PREFERENCE)
4424 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4425 $data = xmlize($xml_data,0);
4426 //echo strftime ("%X",time())."<p>"; //Debug
4427 //traverse_xmlize($data); //Debug
4428 //print_object ($GLOBALS['traverse_array']); //Debug
4429 //$GLOBALS['traverse_array']=""; //Debug
4430 //Now, save data to db. We'll use it later
4431 //Get id and status from data
4432 $preference_id = $data["GRADE_PREFERENCE"]["#"]["ID"]["0"]["#"];
4435 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_preferences', $preference_id,
4437 //Create returning info
4438 $this->info
= $this->counter
;
4442 //If we've finished a grade_letter, xmlize it an save to db
4443 if (($this->level
== 5) and ($tagName == "GRADE_LETTER")) {
4444 //Prepend XML standard header to info gathered
4445 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4446 //Call to xmlize for this portion of xml data (one LETTER)
4447 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4448 $data = xmlize($xml_data,0);
4449 //echo strftime ("%X",time())."<p>"; //Debug
4450 //traverse_xmlize($data); //Debug
4451 //print_object ($GLOBALS['traverse_array']); //Debug
4452 //$GLOBALS['traverse_array']=""; //Debug
4453 //Now, save data to db. We'll use it later
4454 //Get id and status from data
4455 $letter_id = $data["GRADE_LETTER"]["#"]["ID"]["0"]["#"];
4458 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_letter' ,$letter_id,
4460 //Create returning info
4461 $this->info
= $this->counter
;
4466 //If we've finished a grade_category, xmlize it an save to db
4467 if (($this->level
== 5) and ($tagName == "GRADE_CATEGORY")) {
4468 //Prepend XML standard header to info gathered
4469 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4470 //Call to xmlize for this portion of xml data (one CATECORY)
4471 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4472 $data = xmlize($xml_data,0);
4473 //echo strftime ("%X",time())."<p>"; //Debug
4474 //traverse_xmlize($data); //Debug
4475 //print_object ($GLOBALS['traverse_array']); //Debug
4476 //$GLOBALS['traverse_array']=""; //Debug
4477 //Now, save data to db. We'll use it later
4478 //Get id and status from data
4479 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
4482 $status = backup_putid($this->preferences
->backup_unique_code
, 'grade_category' ,$category_id,
4484 //Create returning info
4485 $this->info
= $this->counter
;
4491 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
4492 //Speed up a lot (avoid parse all)
4493 if ($tagName == "GRADEBOOK" and $this->level
== 3) {
4494 $this->finished
= true;
4499 $this->tree
[$this->level
] = "";
4501 $this->content
= "";
4505 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
4506 function endElementUsers($parser, $tagName) {
4508 //Check if we are into USERS zone
4509 if ($this->tree
[3] == "USERS") {
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
== 4) {
4519 //Save to db, only save if record not already exist
4520 // if there already is an new_id for this entry, just use that new_id?
4521 $newuser = backup_getid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
);
4522 if (isset($newuser->new_id
)) {
4523 $newid = $newuser->new_id
;
4528 backup_putid($this->preferences
->backup_unique_code
,"user",$this->info
->tempuser
->id
,
4529 $newid,$this->info
->tempuser
);
4532 if ($this->counter %
10 == 0) {
4533 if (!defined('RESTORE_SILENTLY')) {
4535 if ($this->counter %
200 == 0) {
4542 //Delete temp obejct
4543 unset($this->info
->tempuser
);
4547 if ($this->level
== 5) {
4550 $this->info
->users
[$this->getContents()] = $this->getContents();
4551 $this->info
->tempuser
->id
= $this->getContents();
4554 $this->info
->tempuser
->auth
= $this->getContents();
4557 $this->info
->tempuser
->confirmed
= $this->getContents();
4559 case "POLICYAGREED":
4560 $this->info
->tempuser
->policyagreed
= $this->getContents();
4563 $this->info
->tempuser
->deleted
= $this->getContents();
4566 $this->info
->tempuser
->username
= $this->getContents();
4569 $this->info
->tempuser
->password
= $this->getContents();
4572 $this->info
->tempuser
->idnumber
= $this->getContents();
4575 $this->info
->tempuser
->firstname
= $this->getContents();
4578 $this->info
->tempuser
->lastname
= $this->getContents();
4581 $this->info
->tempuser
->email
= $this->getContents();
4584 $this->info
->tempuser
->emailstop
= $this->getContents();
4587 $this->info
->tempuser
->icq
= $this->getContents();
4590 $this->info
->tempuser
->skype
= $this->getContents();
4593 $this->info
->tempuser
->aim
= $this->getContents();
4596 $this->info
->tempuser
->yahoo
= $this->getContents();
4599 $this->info
->tempuser
->msn
= $this->getContents();
4602 $this->info
->tempuser
->phone1
= $this->getContents();
4605 $this->info
->tempuser
->phone2
= $this->getContents();
4608 $this->info
->tempuser
->institution
= $this->getContents();
4611 $this->info
->tempuser
->department
= $this->getContents();
4614 $this->info
->tempuser
->address
= $this->getContents();
4617 $this->info
->tempuser
->city
= $this->getContents();
4620 $this->info
->tempuser
->country
= $this->getContents();
4623 $this->info
->tempuser
->lang
= $this->getContents();
4626 $this->info
->tempuser
->theme
= $this->getContents();
4629 $this->info
->tempuser
->timezone
= $this->getContents();
4632 $this->info
->tempuser
->firstaccess
= $this->getContents();
4635 $this->info
->tempuser
->lastaccess
= $this->getContents();
4638 $this->info
->tempuser
->lastlogin
= $this->getContents();
4640 case "CURRENTLOGIN":
4641 $this->info
->tempuser
->currentlogin
= $this->getContents();
4644 $this->info
->tempuser
->lastip
= $this->getContents();
4647 $this->info
->tempuser
->secret
= $this->getContents();
4650 $this->info
->tempuser
->picture
= $this->getContents();
4653 $this->info
->tempuser
->url
= $this->getContents();
4656 $this->info
->tempuser
->description
= $this->getContents();
4659 $this->info
->tempuser
->mailformat
= $this->getContents();
4662 $this->info
->tempuser
->maildigest
= $this->getContents();
4665 $this->info
->tempuser
->maildisplay
= $this->getContents();
4668 $this->info
->tempuser
->htmleditor
= $this->getContents();
4671 $this->info
->tempuser
->ajax
= $this->getContents();
4673 case "AUTOSUBSCRIBE":
4674 $this->info
->tempuser
->autosubscribe
= $this->getContents();
4677 $this->info
->tempuser
->trackforums
= $this->getContents();
4679 case "TIMEMODIFIED":
4680 $this->info
->tempuser
->timemodified
= $this->getContents();
4686 if ($this->level
== 6 && $this->tree
[5]!="ROLE_ASSIGNMENTS" && $this->tree
[5]!="ROLE_OVERRIDES") {
4689 //We've finalized a role, get it
4690 $this->info
->tempuser
->roles
[$this->info
->temprole
->type
] = $this->info
->temprole
;
4691 unset($this->info
->temprole
);
4693 case "USER_PREFERENCE":
4694 //We've finalized a user_preference, get it
4695 $this->info
->tempuser
->user_preferences
[$this->info
->tempuserpreference
->name
] = $this->info
->tempuserpreference
;
4696 unset($this->info
->tempuserpreference
);
4701 if ($this->level
== 7 && $this->tree
[5]!="ROLE_ASSIGNMENTS" && $this->tree
[5]!="ROLE_OVERRIDES") {
4704 $this->info
->temprole
->type
= $this->getContents();
4707 $this->info
->temprole
->authority
= $this->getContents();
4710 $this->info
->temprole
->tea_role
= $this->getContents();
4713 $this->info
->temprole
->editall
= $this->getContents();
4716 $this->info
->temprole
->timestart
= $this->getContents();
4719 $this->info
->temprole
->timeend
= $this->getContents();
4721 case "TIMEMODIFIED":
4722 $this->info
->temprole
->timemodified
= $this->getContents();
4725 $this->info
->temprole
->timestart
= $this->getContents();
4728 $this->info
->temprole
->timeend
= $this->getContents();
4731 $this->info
->temprole
->time
= $this->getContents();
4734 $this->info
->temprole
->timeaccess
= $this->getContents();
4737 $this->info
->temprole
->enrol
= $this->getContents();
4740 $this->info
->tempuserpreference
->name
= $this->getContents();
4743 $this->info
->tempuserpreference
->value
= $this->getContents();
4751 if ($this->tree
[5] == "ROLES_ASSIGNMENTS") {
4753 if ($this->level
== 7) {
4756 $this->info
->tempname
= $this->getContents();
4759 $this->info
->tempshortname
= $this->getContents();
4762 $this->info
->tempid
= $this->getContents(); // temp roleid
4767 if ($this->level
== 9) {
4771 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4773 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4775 $this->info
->tempuserid
= $this->getContents();
4777 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->userid
= $this->getContents();
4780 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->hidden
= $this->getContents();
4783 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timestart
= $this->getContents();
4786 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timeend
= $this->getContents();
4788 case "TIMEMODIFIED":
4789 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->timemodified
= $this->getContents();
4792 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->modifierid
= $this->getContents();
4795 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->enrol
= $this->getContents();
4798 $this->info
->tempuser
->roleassignments
[$this->info
->tempid
]->assignments
[$this->info
->tempuserid
]->sortorder
= $this->getContents();
4803 } /// ends role_assignments
4805 if ($this->tree
[5] == "ROLES_OVERRIDES") {
4806 if ($this->level
== 7) {
4809 $this->info
->tempname
= $this->getContents();
4812 $this->info
->tempshortname
= $this->getContents();
4815 $this->info
->tempid
= $this->getContents(); // temp roleid
4820 if ($this->level
== 9) {
4824 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->name
= $this->info
->tempname
;
4825 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->shortname
= $this->info
->tempshortname
;
4826 $this->info
->tempname
= $this->getContents(); // change to name of capability
4827 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->name
= $this->getContents();
4830 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->permission
= $this->getContents();
4832 case "TIMEMODIFIED":
4833 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->timemodified
= $this->getContents();
4836 $this->info
->tempuser
->roleoverrides
[$this->info
->tempid
]->overrides
[$this->info
->tempname
]->modifierid
= $this->getContents();
4840 } /// ends role_overrides
4842 } // closes if this->tree[3]=="users"
4844 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
4845 //Speed up a lot (avoid parse all)
4846 if ($tagName == "USERS" and $this->level
== 3) {
4847 $this->finished
= true;
4852 $this->tree
[$this->level
] = "";
4854 $this->content
= "";
4858 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
4859 function endElementMessages($parser, $tagName) {
4860 //Check if we are into MESSAGES zone
4861 if ($this->tree
[3] == "MESSAGES") {
4862 //if (trim($this->content)) //Debug
4863 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4864 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n";//Debug
4865 //Acumulate data to info (content + close tag)
4866 //Reconvert: strip htmlchars again and trim to generate xml data
4867 if (!isset($this->temp
)) {
4870 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
4871 //If we've finished a message, xmlize it an save to db
4872 if (($this->level
== 4) and ($tagName == "MESSAGE")) {
4873 //Prepend XML standard header to info gathered
4874 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4875 //Call to xmlize for this portion of xml data (one MESSAGE)
4876 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4877 $data = xmlize($xml_data,0);
4878 //echo strftime ("%X",time())."<p>"; //Debug
4879 //traverse_xmlize($data); //Debug
4880 //print_object ($GLOBALS['traverse_array']); //Debug
4881 //$GLOBALS['traverse_array']=""; //Debug
4882 //Now, save data to db. We'll use it later
4883 //Get id and status from data
4884 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
4885 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
4886 if ($message_status == "READ") {
4887 $table = "message_read";
4893 $status = backup_putid($this->preferences
->backup_unique_code
, $table,$message_id,
4895 //Create returning info
4896 $this->info
= $this->counter
;
4900 //If we've finished a contact, xmlize it an save to db
4901 if (($this->level
== 5) and ($tagName == "CONTACT")) {
4902 //Prepend XML standard header to info gathered
4903 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4904 //Call to xmlize for this portion of xml data (one MESSAGE)
4905 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4906 $data = xmlize($xml_data,0);
4907 //echo strftime ("%X",time())."<p>"; //Debug
4908 //traverse_xmlize($data); //Debug
4909 //print_object ($GLOBALS['traverse_array']); //Debug
4910 //$GLOBALS['traverse_array']=""; //Debug
4911 //Now, save data to db. We'll use it later
4912 //Get id and status from data
4913 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
4916 $status = backup_putid($this->preferences
->backup_unique_code
, 'message_contacts' ,$contact_id,
4918 //Create returning info
4919 $this->info
= $this->counter
;
4925 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
4926 //Speed up a lot (avoid parse all)
4927 if ($tagName == "MESSAGES" and $this->level
== 3) {
4928 $this->finished
= true;
4933 $this->tree
[$this->level
] = "";
4935 $this->content
= "";
4939 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4940 function endElementQuestions($parser, $tagName) {
4941 //Check if we are into QUESTION_CATEGORIES zone
4942 if ($this->tree
[3] == "QUESTION_CATEGORIES") {
4943 //if (trim($this->content)) //Debug
4944 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4945 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4946 //Acumulate data to info (content + close tag)
4947 //Reconvert: strip htmlchars again and trim to generate xml data
4948 if (!isset($this->temp
)) {
4951 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
4952 //If we've finished a mod, xmlize it an save to db
4953 if (($this->level
== 4) and ($tagName == "QUESTION_CATEGORY")) {
4954 //Prepend XML standard header to info gathered
4955 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
4956 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
4957 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
4958 $data = xmlize($xml_data,0);
4959 //echo strftime ("%X",time())."<p>"; //Debug
4960 //traverse_xmlize($data); //Debug
4961 //print_object ($GLOBALS['traverse_array']); //Debug
4962 //$GLOBALS['traverse_array']=""; //Debug
4963 //Now, save data to db. We'll use it later
4965 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
4967 $status = backup_putid($this->preferences
->backup_unique_code
,"question_categories",$category_id,
4969 //Create returning info
4970 $ret_info->id
= $category_id;
4971 $this->info
[] = $ret_info;
4977 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
4978 //Speed up a lot (avoid parse all)
4979 if ($tagName == "QUESTION_CATEGORIES" and $this->level
== 3) {
4980 $this->finished
= true;
4984 $this->tree
[$this->level
] = "";
4986 $this->content
= "";
4990 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
4991 function endElementScales($parser, $tagName) {
4992 //Check if we are into SCALES zone
4993 if ($this->tree
[3] == "SCALES") {
4994 //if (trim($this->content)) //Debug
4995 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4996 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
4997 //Acumulate data to info (content + close tag)
4998 //Reconvert: strip htmlchars again and trim to generate xml data
4999 if (!isset($this->temp
)) {
5002 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5003 //If we've finished a scale, xmlize it an save to db
5004 if (($this->level
== 4) and ($tagName == "SCALE")) {
5005 //Prepend XML standard header to info gathered
5006 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5007 //Call to xmlize for this portion of xml data (one SCALE)
5008 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5009 $data = xmlize($xml_data,0);
5010 //echo strftime ("%X",time())."<p>"; //Debug
5011 //traverse_xmlize($data); //Debug
5012 //print_object ($GLOBALS['traverse_array']); //Debug
5013 //$GLOBALS['traverse_array']=""; //Debug
5014 //Now, save data to db. We'll use it later
5015 //Get id and from data
5016 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
5018 $status = backup_putid($this->preferences
->backup_unique_code
,"scale",$scale_id,
5020 //Create returning info
5021 $ret_info->id
= $scale_id;
5022 $this->info
[] = $ret_info;
5028 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
5029 //Speed up a lot (avoid parse all)
5030 if ($tagName == "SCALES" and $this->level
== 3) {
5031 $this->finished
= true;
5035 $this->tree
[$this->level
] = "";
5037 $this->content
= "";
5041 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
5042 function endElementGroups($parser, $tagName) {
5043 //Check if we are into GROUPS zone
5044 if ($this->tree
[3] == "GROUPS") {
5045 //if (trim($this->content)) //Debug
5046 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5047 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5048 //Acumulate data to info (content + close tag)
5049 //Reconvert: strip htmlchars again and trim to generate xml data
5050 if (!isset($this->temp
)) {
5053 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5054 //If we've finished a group, xmlize it an save to db
5055 if (($this->level
== 4) and ($tagName == "GROUP")) {
5056 //Prepend XML standard header to info gathered
5057 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5058 //Call to xmlize for this portion of xml data (one GROUP)
5059 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5060 $data = xmlize($xml_data,0);
5061 //echo strftime ("%X",time())."<p>"; //Debug
5062 //traverse_xmlize($data); //Debug
5063 //print_object ($GLOBALS['traverse_array']); //Debug
5064 //$GLOBALS['traverse_array']=""; //Debug
5065 //Now, save data to db. We'll use it later
5066 //Get id and from data
5067 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
5069 $status = backup_putid($this->preferences
->backup_unique_code
,"groups",$group_id,
5071 //Create returning info
5072 $ret_info = new Object();
5073 $ret_info->id
= $group_id;
5074 $this->info
[] = $ret_info;
5080 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
5081 //Speed up a lot (avoid parse all)
5082 if ($tagName == "GROUPS" and $this->level
== 3) {
5083 $this->finished
= true;
5087 $this->tree
[$this->level
] = "";
5089 $this->content
= "";
5093 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPINGS")
5094 function endElementGroupings($parser, $tagName) { //TODO:
5095 //Check if we are into GROUPS zone
5096 if ($this->tree
[3] == "GROUPINGS") {
5097 //Acumulate data to info (content + close tag)
5098 //Reconvert: strip htmlchars again and trim to generate xml data
5099 if (!isset($this->temp
)) {
5102 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5103 //If we've finished a group, xmlize it an save to db
5104 if (($this->level
== 4) and ($tagName == "GROUPING")) {
5105 //Prepend XML standard header to info gathered
5106 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5107 //Call to xmlize for this portion of xml data (one GROUPING)
5108 $data = xmlize($xml_data,0);
5109 //Now, save data to db. We'll use it later
5110 //Get id and from data
5111 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
5113 $status = backup_putid($this->preferences
->backup_unique_code
,"groupings",$grouping_id,
5115 //Create returning info
5116 $ret_info = new Object();
5117 $ret_info->id
= $grouping_id;
5118 $this->info
[] = $ret_info;
5124 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
5125 //Speed up a lot (avoid parse all)
5126 if ($tagName == "GROUPINGS" and $this->level
== 3) {
5127 $this->finished
= true;
5131 $this->tree
[$this->level
] = "";
5133 $this->content
= "";
5137 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
5138 function endElementEvents($parser, $tagName) {
5139 //Check if we are into EVENTS zone
5140 if ($this->tree
[3] == "EVENTS") {
5141 //if (trim($this->content)) //Debug
5142 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5143 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5144 //Acumulate data to info (content + close tag)
5145 //Reconvert: strip htmlchars again and trim to generate xml data
5146 if (!isset($this->temp
)) {
5149 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5150 //If we've finished a event, xmlize it an save to db
5151 if (($this->level
== 4) and ($tagName == "EVENT")) {
5152 //Prepend XML standard header to info gathered
5153 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5154 //Call to xmlize for this portion of xml data (one EVENT)
5155 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5156 $data = xmlize($xml_data,0);
5157 //echo strftime ("%X",time())."<p>"; //Debug
5158 //traverse_xmlize($data); //Debug
5159 //print_object ($GLOBALS['traverse_array']); //Debug
5160 //$GLOBALS['traverse_array']=""; //Debug
5161 //Now, save data to db. We'll use it later
5162 //Get id and from data
5163 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
5165 $status = backup_putid($this->preferences
->backup_unique_code
,"event",$event_id,
5167 //Create returning info
5168 $ret_info->id
= $event_id;
5169 $this->info
[] = $ret_info;
5175 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
5176 //Speed up a lot (avoid parse all)
5177 if ($tagName == "EVENTS" and $this->level
== 3) {
5178 $this->finished
= true;
5182 $this->tree
[$this->level
] = "";
5184 $this->content
= "";
5188 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
5189 function endElementModules($parser, $tagName) {
5190 //Check if we are into MODULES zone
5191 if ($this->tree
[3] == "MODULES") {
5192 //if (trim($this->content)) //Debug
5193 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5194 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5195 //Acumulate data to info (content + close tag)
5196 //Reconvert: strip htmlchars again and trim to generate xml data
5197 if (!isset($this->temp
)) {
5200 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5201 //If we've finished a mod, xmlize it an save to db
5202 if (($this->level
== 4) and ($tagName == "MOD")) {
5203 //Prepend XML standard header to info gathered
5204 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5205 //Call to xmlize for this portion of xml data (one MOD)
5206 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5207 $data = xmlize($xml_data,0);
5208 //echo strftime ("%X",time())."<p>"; //Debug
5209 //traverse_xmlize($data); //Debug
5210 //print_object ($GLOBALS['traverse_array']); //Debug
5211 //$GLOBALS['traverse_array']=""; //Debug
5212 //Now, save data to db. We'll use it later
5213 //Get id and modtype from data
5214 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
5215 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
5216 //Only if we've selected to restore it
5217 if (!empty($this->preferences
->mods
[$mod_type]->restore
)) {
5219 $status = backup_putid($this->preferences
->backup_unique_code
,$mod_type,$mod_id,
5221 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
5222 //Create returning info
5223 $ret_info->id
= $mod_id;
5224 $ret_info->modtype
= $mod_type;
5225 $this->info
[] = $ret_info;
5234 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
5235 //Speed up a lot (avoid parse all)
5236 if ($tagName == "MODULES" and $this->level
== 3) {
5237 $this->finished
= true;
5241 $this->tree
[$this->level
] = "";
5243 $this->content
= "";
5247 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
5248 function endElementLogs($parser, $tagName) {
5249 //Check if we are into LOGS zone
5250 if ($this->tree
[3] == "LOGS") {
5251 //if (trim($this->content)) //Debug
5252 // echo "C".str_repeat(" ",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5253 //echo $this->level.str_repeat(" ",$this->level*2)."</".$tagName."><br />\n"; //Debug
5254 //Acumulate data to info (content + close tag)
5255 //Reconvert: strip htmlchars again and trim to generate xml data
5256 if (!isset($this->temp
)) {
5259 $this->temp
.= htmlspecialchars(trim($this->content
))."</".$tagName.">";
5260 //If we've finished a log, xmlize it an save to db
5261 if (($this->level
== 4) and ($tagName == "LOG")) {
5262 //Prepend XML standard header to info gathered
5263 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp
;
5264 //Call to xmlize for this portion of xml data (one LOG)
5265 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5266 $data = xmlize($xml_data,0);
5267 //echo strftime ("%X",time())."<p>"; //Debug
5268 //traverse_xmlize($data); //Debug
5269 //print_object ($GLOBALS['traverse_array']); //Debug
5270 //$GLOBALS['traverse_array']=""; //Debug
5271 //Now, save data to db. We'll use it later
5272 //Get id and modtype from data
5273 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
5274 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
5275 //We only save log entries from backup file if they are:
5278 // - Module logs about one restored module
5279 if ($log_module == "course" or
5280 $log_module == "user" or
5281 $this->preferences
->mods
[$log_module]->restore
) {
5285 $status = backup_putid($this->preferences
->backup_unique_code
,"log",$log_id,
5287 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
5288 //Create returning info
5289 $this->info
= $this->counter
;
5296 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
5297 //Speed up a lot (avoid parse all)
5298 if ($tagName == "LOGS" and $this->level
== 3) {
5299 $this->finished
= true;
5304 $this->tree
[$this->level
] = "";
5306 $this->content
= "";
5310 //This is the endTag default handler we use when todo is undefined
5311 function endElement($parser, $tagName) {
5312 if (trim($this->content
)) //Debug
5313 echo "C".str_repeat(" ",($this->level+
2)*2).$this->getContents()."<br />\n"; //Debug
5314 echo $this->level
.str_repeat(" ",$this->level
*2)."</".$tagName."><br />\n"; //Debug
5317 $this->tree
[$this->level
] = "";
5319 $this->content
= "";
5322 //This is the handler to read data contents (simple accumule it)
5323 function characterData($parser, $data) {
5324 $this->content
.= $data;
5328 //This function executes the MoodleParser
5329 function restore_read_xml ($xml_file,$todo,$preferences) {
5333 $xml_parser = xml_parser_create('UTF-8');
5334 $moodle_parser = new MoodleParser();
5335 $moodle_parser->todo
= $todo;
5336 $moodle_parser->preferences
= $preferences;
5337 xml_set_object($xml_parser,$moodle_parser);
5338 //Depending of the todo we use some element_handler or another
5339 if ($todo == "INFO") {
5340 //Define handlers to that zone
5341 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
5342 } else if ($todo == "ROLES") {
5343 // Define handlers to that zone
5344 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
5345 } else if ($todo == "COURSE_HEADER") {
5346 //Define handlers to that zone
5347 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
5348 } else if ($todo == 'BLOCKS') {
5349 //Define handlers to that zone
5350 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
5351 } else if ($todo == "SECTIONS") {
5352 //Define handlers to that zone
5353 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
5354 } else if ($todo == 'FORMATDATA') {
5355 //Define handlers to that zone
5356 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
5357 } else if ($todo == "METACOURSE") {
5358 //Define handlers to that zone
5359 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
5360 } else if ($todo == "GRADEBOOK") {
5361 //Define handlers to that zone
5362 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
5363 } else if ($todo == "USERS") {
5364 //Define handlers to that zone
5365 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
5366 } else if ($todo == "MESSAGES") {
5367 //Define handlers to that zone
5368 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
5369 } else if ($todo == "QUESTIONS") {
5370 //Define handlers to that zone
5371 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
5372 } else if ($todo == "SCALES") {
5373 //Define handlers to that zone
5374 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
5375 } else if ($todo == "GROUPS") {
5376 //Define handlers to that zone
5377 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
5378 } else if ($todo == "GROUPINGS") {
5379 //Define handlers to that zone
5380 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
5381 } else if ($todo == "EVENTS") {
5382 //Define handlers to that zone
5383 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
5384 } else if ($todo == "MODULES") {
5385 //Define handlers to that zone
5386 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
5387 } else if ($todo == "LOGS") {
5388 //Define handlers to that zone
5389 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
5391 //Define default handlers (must no be invoked when everything become finished)
5392 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
5394 xml_set_character_data_handler($xml_parser, "characterData");
5395 $fp = fopen($xml_file,"r")
5398 while ($data = fread($fp, 4096) and !$moodle_parser->finished
)
5399 xml_parse($xml_parser, $data, feof($fp))
5400 or die(sprintf("XML error: %s at line %d",
5401 xml_error_string(xml_get_error_code($xml_parser)),
5402 xml_get_current_line_number($xml_parser)));
5405 //Get info from parser
5406 $info = $moodle_parser->info
;
5409 xml_parser_free($xml_parser);
5411 if ($status && !empty($info)) {
5419 * @param string $errorstr passed by reference, if silent is true,
5420 * errorstr will be populated and this function will return false rather than calling error() or notify()
5421 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
5422 * redirect to the next step in the restore process, instead will return $backup_unique_code
5424 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
5426 global $CFG, $SESSION;
5428 //Prepend dataroot to variable to have the absolute path
5429 $file = $CFG->dataroot
."/".$file;
5431 if (!defined('RESTORE_SILENTLY')) {
5432 //Start the main table
5433 echo "<table cellpadding=\"5\">";
5440 //Check the file exists
5441 if (!is_file($file)) {
5442 if (!defined('RESTORE_SILENTLY')) {
5443 error ("File not exists ($file)");
5445 $errorstr = "File not exists ($file)";
5450 //Check the file name ends with .zip
5451 if (!substr($file,-4) == ".zip") {
5452 if (!defined('RESTORE_SILENTLY')) {
5453 error ("File has an incorrect extension");
5455 $errorstr = 'File has an incorrect extension';
5460 //Now calculate the unique_code for this restore
5461 $backup_unique_code = time();
5463 //Now check and create the backup dir (if it doesn't exist)
5464 if (!defined('RESTORE_SILENTLY')) {
5465 echo "<li>".get_string("creatingtemporarystructures").'</li>';
5467 $status = check_and_create_backup_dir($backup_unique_code);
5470 $status = clear_backup_dir($backup_unique_code);
5473 //Now delete old data and directories under dataroot/temp/backup
5475 if (!defined('RESTORE_SILENTLY')) {
5476 echo "<li>".get_string("deletingolddata").'</li>';
5478 $status = backup_delete_old_data();
5481 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
5483 if (!defined('RESTORE_SILENTLY')) {
5484 echo "<li>".get_string("copyingzipfile").'</li>';
5486 if (! $status = backup_copy_file($file,$CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
5487 if (!defined('RESTORE_SILENTLY')) {
5488 notify("Error copying backup file. Invalid name or bad perms.");
5490 $errorstr = "Error copying backup file. Invalid name or bad perms";
5496 //Now unzip the file
5498 if (!defined('RESTORE_SILENTLY')) {
5499 echo "<li>".get_string("unzippingbackup").'</li>';
5501 if (! $status = restore_unzip ($CFG->dataroot
."/temp/backup/".$backup_unique_code."/".basename($file))) {
5502 if (!defined('RESTORE_SILENTLY')) {
5503 notify("Error unzipping backup file. Invalid zip file.");
5505 $errorstr = "Error unzipping backup file. Invalid zip file.";
5511 //Check for Blackboard backups and convert
5513 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
5514 if (!defined('RESTORE_SILENTLY')) {
5515 echo "<li>".get_string("checkingforbbexport");
5517 $status = blackboard_convert($CFG->dataroot
."/temp/backup/".$backup_unique_code);
5520 //Now check for the moodle.xml file
5522 $xml_file = $CFG->dataroot
."/temp/backup/".$backup_unique_code."/moodle.xml";
5523 if (!defined('RESTORE_SILENTLY')) {
5524 echo "<li>".get_string("checkingbackup").'</li>';
5526 if (! $status = restore_check_moodle_file ($xml_file)) {
5527 if (!is_file($xml_file)) {
5528 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
5530 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
5532 if (!defined('RESTORE_SILENTLY')) {
5541 $course_header = "";
5543 //Now read the info tag (all)
5545 if (!defined('RESTORE_SILENTLY')) {
5546 echo "<li>".get_string("readinginfofrombackup").'</li>';
5548 //Reading info from file
5549 $info = restore_read_xml_info ($xml_file);
5550 //Reading course_header from file
5551 $course_header = restore_read_xml_course_header ($xml_file);
5554 if (!defined('RESTORE_SILENTLY')) {
5558 //End the main table
5563 //We compare Moodle's versions
5564 if ($CFG->version
< $info->backup_moodle_version
&& $status) {
5565 $message->serverversion
= $CFG->version
;
5566 $message->serverrelease
= $CFG->release
;
5567 $message->backupversion
= $info->backup_moodle_version
;
5568 $message->backuprelease
= $info->backup_moodle_release
;
5569 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
5573 //Now we print in other table, the backup and the course it contains info
5574 if ($info and $course_header and $status) {
5575 //First, the course info
5576 if (!defined('RESTORE_SILENTLY')) {
5577 $status = restore_print_course_header($course_header);
5579 //Now, the backup info
5581 if (!defined('RESTORE_SILENTLY')) {
5582 $status = restore_print_info($info);
5587 //Save course header and info into php session
5589 $SESSION->info
= $info;
5590 $SESSION->course_header
= $course_header;
5593 //Finally, a little form to continue
5594 //with some hidden fields
5596 if (!defined('RESTORE_SILENTLY')) {
5597 echo "<br /><center>";
5598 $hidden["backup_unique_code"] = $backup_unique_code;
5599 $hidden["launch"] = "form";
5600 $hidden["file"] = $file;
5601 $hidden["id"] = $id;
5602 print_single_button("restore.php", $hidden, get_string("continue"),"post");
5606 if (empty($noredirect)) {
5607 redirect($CFG->wwwroot
.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
5609 return $backup_unique_code;
5615 if (!defined('RESTORE_SILENTLY')) {
5616 error ("An error has ocurred");
5618 $errorstr = "An error has occured"; // helpful! :P
5625 function restore_setup_for_check(&$restore,$backup_unique_code) {
5627 $restore->backup_unique_code
=$backup_unique_code;
5628 $restore->users
= 2; // yuk
5629 $restore->course_files
= $SESSION->restore
->restore_course_files
;
5630 if ($allmods = get_records("modules")) {
5631 foreach ($allmods as $mod) {
5632 $modname = $mod->name
;
5633 $var = "restore_".$modname;
5634 //Now check that we have that module info in the backup file
5635 if (isset($SESSION->info
->mods
[$modname]) && $SESSION->info
->mods
[$modname]->backup
== "true") {
5643 function backup_to_restore_array($backup,$k=0) {
5644 if (is_array($backup) ) {
5645 foreach ($backup as $key => $value) {
5646 $newkey = str_replace('backup','restore',$key);
5647 $restore[$newkey] = backup_to_restore_array($value,$key);
5650 else if (is_object($backup)) {
5651 $tmp = get_object_vars($backup);
5652 foreach ($tmp as $key => $value) {
5653 $newkey = str_replace('backup','restore',$key);
5654 $restore->$newkey = backup_to_restore_array($value,$key);
5658 $newkey = str_replace('backup','restore',$k);
5665 * compatibility function
5666 * checks for per-instance backups AND
5667 * older per-module backups
5668 * and returns whether userdata has been selected.
5670 function restore_userdata_selected($restore,$modname,$modid) {
5671 // check first for per instance array
5672 if (!empty($restore->mods
[$modname]->granular
)) { // supports per instance
5673 return array_key_exists($modid,$restore->mods
[$modname]->instances
)
5674 && !empty($restore->mods
[$modname]->instances
[$modid]->userinfo
);
5676 return !empty($restore->mods
[$modname]->userinfo
);
5679 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
5684 //Checks for the required files/functions to restore every module
5686 if ($allmods = get_records("modules") ) {
5687 foreach ($allmods as $mod) {
5688 $modname = $mod->name
;
5689 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
5690 //If file exists and we have selected to restore that type of module
5691 if ((file_exists($modfile)) and ($restore->mods
[$modname]->restore
)) {
5692 include_once($modfile);
5697 if (!defined('RESTORE_SILENTLY')) {
5698 //Start the main table
5699 echo "<table cellpadding=\"5\">";
5706 //Localtion of the xml file
5707 $xml_file = $CFG->dataroot
."/temp/backup/".$restore->backup_unique_code
."/moodle.xml";
5709 //If we've selected to restore into new course
5710 //create it (course)
5711 //Saving conversion id variables into backup_tables
5712 if ($restore->restoreto
== 2) {
5713 if (!defined('RESTORE_SILENTLY')) {
5714 echo '<li>'.get_string('creatingnewcourse') . '</li>';
5716 $oldidnumber = $course_header->course_idnumber
;
5717 if (!$status = restore_create_new_course($restore,$course_header)) {
5718 if (!defined('RESTORE_SILENTLY')) {
5719 notify("Error while creating the new empty course.");
5721 $errorstr = "Error while creating the new empty course.";
5726 //Print course fullname and shortname and category
5728 if (!defined('RESTORE_SILENTLY')) {
5730 echo "<li>".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
5731 echo "<li>".get_string("category").": ".$course_header->category
->name
.'</li>';
5732 if (!empty($oldidnumber)) {
5733 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
5736 //Put the destination course_id
5738 $restore->course_id
= $course_header->course_id
;
5741 if ($status = restore_open_html($restore,$course_header)){
5742 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
5746 $course = get_record("course","id",$restore->course_id
);
5748 if (!defined('RESTORE_SILENTLY')) {
5749 echo "<li>".get_string("usingexistingcourse");
5751 echo "<li>".get_string("from").": ".$course_header->course_fullname
." (".$course_header->course_shortname
.")".'</li>';
5752 echo "<li>".get_string("to").": ".$course->fullname
." (".$course->shortname
.")".'</li>';
5753 if (($restore->deleting
)) {
5754 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
5756 echo "<li>".get_string("addingdatatoexisting").'</li>';
5760 //If we have selected to restore deleting, we do it now.
5761 if ($restore->deleting
) {
5762 if (!defined('RESTORE_SILENTLY')) {
5763 echo "<li>".get_string("deletingolddata").'</li>';
5765 $status = remove_course_contents($restore->course_id
,false) and
5766 delete_dir_contents($CFG->dataroot
."/".$restore->course_id
,"backupdata");
5768 //Now , this situation is equivalent to the "restore to new course" one (we
5769 //have a course record and nothing more), so define it as "to new course"
5770 $restore->restoreto
= 2;
5772 if (!defined('RESTORE_SILENTLY')) {
5773 notify("An error occurred while deleting some of the course contents.");
5775 $errrostr = "An error occurred while deleting some of the course contents.";
5781 if (!defined('RESTORE_SILENTLY')) {
5782 notify("Error opening existing course.");
5785 $errorstr = "Error opening existing course.";
5791 //Now create the course_sections and their associated course_modules
5794 if ($restore->restoreto
== 2) {
5795 if (!defined('RESTORE_SILENTLY')) {
5796 echo "<li>".get_string("creatingsections");
5798 if (!$status = restore_create_sections($restore,$xml_file)) {
5799 if (!defined('RESTORE_SILENTLY')) {
5800 notify("Error creating sections in the existing course.");
5802 $errorstr = "Error creating sections in the existing course.";
5806 if (!defined('RESTORE_SILENTLY')) {
5809 //Into existing course
5810 } else if ($restore->restoreto
== 0 or $restore->restoreto
== 1) {
5811 if (!defined('RESTORE_SILENTLY')) {
5812 echo "<li>".get_string("checkingsections");
5814 if (!$status = restore_create_sections($restore,$xml_file)) {
5815 if (!defined('RESTORE_SILENTLY')) {
5816 notify("Error creating sections in the existing course.");
5818 $errorstr = "Error creating sections in the existing course.";
5822 if (!defined('RESTORE_SILENTLY')) {
5827 if (!defined('RESTORE_SILENTLY')) {
5828 notify("Neither a new course or an existing one was specified.");
5831 $errorstr = "Neither a new course or an existing one was specified.";
5837 //Now create users as needed
5838 if ($status and ($restore->users
== 0 or $restore->users
== 1)) {
5839 if (!defined('RESTORE_SILENTLY')) {
5840 echo "<li>".get_string("creatingusers")."<br />";
5842 if (!$status = restore_create_users($restore,$xml_file)) {
5843 if (!defined('RESTORE_SILENTLY')) {
5844 notify("Could not restore users.");
5846 $errorstr = "Could not restore users.";
5851 //Now print info about the work done
5853 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
5854 where backup_code = '$restore->backup_unique_code' and
5855 table_name = 'user'");
5863 //Iterate, filling counters
5864 foreach ($recs as $rec) {
5865 //Get full record, using backup_getids
5866 $record = backup_getid($restore->backup_unique_code
,"user",$rec->old_id
);
5867 if (strpos($record->info
,"new") !== false) {
5870 if (strpos($record->info
,"exists") !== false) {
5873 if (strpos($record->info
,"student") !== false) {
5875 } else if (strpos($record->info
,"teacher") !== false) {
5880 if ($counter %
10 == 0) {
5881 if (!defined('RESTORE_SILENTLY')) {
5883 if ($counter %
200 == 0) {
5890 if (!defined('RESTORE_SILENTLY')) {
5891 //Now print information gathered
5892 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
5894 echo "<li>".get_string("students").": ".$student_count.'</li>';
5895 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
5899 if (!defined('RESTORE_SILENTLY')) {
5900 notify("No users were found!");
5901 } // no need to return false here, it's recoverable.
5906 //Now create metacourse info
5907 if ($status and $restore->metacourse
) {
5908 //Only to new courses!
5909 if ($restore->restoreto
== 2) {
5910 if (!defined('RESTORE_SILENTLY')) {
5911 echo "</li><li>".get_string("creatingmetacoursedata");
5913 if (!$status = restore_create_metacourse($restore,$xml_file)) {
5914 if (!defined('RESTORE_SILENTLY')) {
5915 notify("Error creating metacourse in the course.");
5917 $errorstr = "Error creating metacourse in the course.";
5921 if (!defined('RESTORE_SILENTLY')) {
5928 //Now create categories and questions as needed
5929 if ($status and ($restore->mods
['quiz']->restore
)) {
5930 include_once("$CFG->dirroot/question/restorelib.php");
5931 if (!defined('RESTORE_SILENTLY')) {
5932 echo "<li>".get_string("creatingcategoriesandquestions");
5935 if (!$status = restore_create_questions($restore,$xml_file)) {
5936 if (!defined('RESTORE_SILENTLY')) {
5937 notify("Could not restore categories and questions!");
5939 $errorstr = "Could not restore categories and questions!";
5943 if (!defined('RESTORE_SILENTLY')) {
5948 //Now create user_files as needed
5949 if ($status and ($restore->user_files
)) {
5950 if (!defined('RESTORE_SILENTLY')) {
5951 echo "<li>".get_string("copyinguserfiles");
5953 if (!$status = restore_user_files($restore)) {
5954 if (!defined('RESTORE_SILENTLY')) {
5955 notify("Could not restore user files!");
5957 $errorstr = "Could not restore user files!";
5961 //If all is ok (and we have a counter)
5962 if ($status and ($status !== true)) {
5963 //Inform about user dirs created from backup
5964 if (!defined('RESTORE_SILENTLY')) {
5966 echo "<li>".get_string("userzones").": ".$status;
5970 if (!defined('RESTORE_SILENTLY')) {
5975 //Now create course files as needed
5976 if ($status and ($restore->course_files
)) {
5977 if (!defined('RESTORE_SILENTLY')) {
5978 echo "<li>".get_string("copyingcoursefiles")."</li>";
5980 if (!$status = restore_course_files($restore)) {
5981 if (empty($status)) {
5982 notify("Could not restore course files!");
5984 $errorstr = "Could not restore course files!";
5988 //If all is ok (and we have a counter)
5989 if ($status and ($status !== true)) {
5990 //Inform about user dirs created from backup
5991 if (!defined('RESTORE_SILENTLY')) {
5993 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
5999 //Now create messages as needed
6000 if ($status and ($restore->messages
)) {
6001 if (!defined('RESTORE_SILENTLY')) {
6002 echo "<li>".get_string("creatingmessagesinfo");
6004 if (!$status = restore_create_messages($restore,$xml_file)) {
6005 if (!defined('RESTORE_SILENTLY')) {
6006 notify("Could not restore messages!");
6008 $errorstr = "Could not restore messages!";
6012 if (!defined('RESTORE_SILENTLY')) {
6017 //Now create scales as needed
6019 if (!defined('RESTORE_SILENTLY')) {
6020 echo "<li>".get_string("creatingscales");
6022 if (!$status = restore_create_scales($restore,$xml_file)) {
6023 if (!defined('RESTORE_SILENTLY')) {
6024 notify("Could not restore custom scales!");
6026 $errorstr = "Could not restore custom scales!";
6030 if (!defined('RESTORE_SILENTLY')) {
6035 //Now create groups as needed
6037 if (!defined('RESTORE_SILENTLY')) {
6038 echo "<li>".get_string("creatinggroups");
6040 if (!$status = restore_create_groups($restore,$xml_file)) {
6041 if (!defined('RESTORE_SILENTLY')) {
6042 notify("Could not restore groups!");
6044 $errorstr = "Could not restore groups!";
6048 if (!defined('RESTORE_SILENTLY')) {
6053 //Now create groupings as needed
6055 if (!defined('RESTORE_SILENTLY')) {
6056 echo "<li>".get_string("creatinggroupings");
6058 if (!$status = restore_create_groupings($restore,$xml_file)) {
6059 if (!defined('RESTORE_SILENTLY')) {
6060 notify("Could not restore groupings!");
6062 $errorstr = "Could not restore groupings!";
6066 if (!defined('RESTORE_SILENTLY')) {
6071 //Now create events as needed
6073 if (!defined('RESTORE_SILENTLY')) {
6074 echo "<li>".get_string("creatingevents");
6076 if (!$status = restore_create_events($restore,$xml_file)) {
6077 if (!defined('RESTORE_SILENTLY')) {
6078 notify("Could not restore course events!");
6080 $errorstr = "Could not restore course events!";
6084 if (!defined('RESTORE_SILENTLY')) {
6089 //Now create course modules as needed
6091 if (!defined('RESTORE_SILENTLY')) {
6092 echo "<li>".get_string("creatingcoursemodules");
6094 if (!$status = restore_create_modules($restore,$xml_file)) {
6095 if (!defined('RESTORE_SILENTLY')) {
6096 notify("Could not restore modules!");
6098 $errorstr = "Could not restore modules!";
6102 if (!defined('RESTORE_SILENTLY')) {
6107 //Now create gradebook as needed -- AFTER modules!!!
6109 if (!defined('RESTORE_SILENTLY')) {
6110 echo "<li>".get_string("creatinggradebook");
6112 if (!$status = restore_create_gradebook($restore,$xml_file)) {
6113 if (!defined('RESTORE_SILENTLY')) {
6114 notify("Could not restore gradebook!");
6116 $errorstr = "Could not restore gradebook!";
6120 if (!defined('RESTORE_SILENTLY')) {
6125 //Bring back the course blocks -- do it AFTER the modules!!!
6127 //If we are deleting and bringing into a course or making a new course, same situation
6128 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
6129 if (!defined('RESTORE_SILENTLY')) {
6130 echo '<li>'.get_string('creatingblocks');
6132 $course_header->blockinfo
= !empty($course_header->blockinfo
) ?
$course_header->blockinfo
: NULL;
6133 if (!$status = restore_create_blocks($restore, $info->backup_block_format
, $course_header->blockinfo
, $xml_file)) {
6134 if (!defined('RESTORE_SILENTLY')) {
6135 notify('Error while creating the course blocks');
6137 $errorstr = "Error while creating the course blocks";
6141 if (!defined('RESTORE_SILENTLY')) {
6148 //If we are deleting and bringing into a course or making a new course, same situation
6149 if($restore->restoreto
== 0 ||
$restore->restoreto
== 2) {
6150 if (!defined('RESTORE_SILENTLY')) {
6151 echo '<li>'.get_string('courseformatdata');
6153 if (!$status = restore_set_format_data($restore, $xml_file)) {
6154 $error = "Error while setting the course format data";
6155 if (!defined('RESTORE_SILENTLY')) {
6162 if (!defined('RESTORE_SILENTLY')) {
6168 //Now create log entries as needed
6169 if ($status and ($restore->logs
)) {
6170 if (!defined('RESTORE_SILENTLY')) {
6171 echo "<li>".get_string("creatinglogentries");
6173 if (!$status = restore_create_logs($restore,$xml_file)) {
6174 if (!defined('RESTORE_SILENTLY')) {
6175 notify("Could not restore logs!");
6177 $errorstr = "Could not restore logs!";
6181 if (!defined('RESTORE_SILENTLY')) {
6186 //Now, if all is OK, adjust the instance field in course_modules !!
6188 if (!defined('RESTORE_SILENTLY')) {
6189 echo "<li>".get_string("checkinginstances");
6191 if (!$status = restore_check_instances($restore)) {
6192 if (!defined('RESTORE_SILENTLY')) {
6193 notify("Could not adjust instances in course_modules!");
6195 $errorstr = "Could not adjust instances in course_modules!";
6199 if (!defined('RESTORE_SILENTLY')) {
6204 //Now, if all is OK, adjust activity events
6206 if (!defined('RESTORE_SILENTLY')) {
6207 echo "<li>".get_string("refreshingevents");
6209 if (!$status = restore_refresh_events($restore)) {
6210 if (!defined('RESTORE_SILENTLY')) {
6211 notify("Could not refresh events for activities!");
6213 $errorstr = "Could not refresh events for activities!";
6217 if (!defined('RESTORE_SILENTLY')) {
6222 //Now, if all is OK, adjust inter-activity links
6224 if (!defined('RESTORE_SILENTLY')) {
6225 echo "<li>".get_string("decodinginternallinks");
6227 if (!$status = restore_decode_content_links($restore)) {
6228 if (!defined('RESTORE_SILENTLY')) {
6229 notify("Could not refresh events for activities!");
6231 $errorstr = "Could not refresh events for activities!";
6235 if (!defined('RESTORE_SILENTLY')) {
6240 //Now, with backup files prior to version 2005041100,
6241 //convert all the wiki texts in the course to markdown
6242 if ($status && $restore->backup_version
< 2005041100) {
6243 if (!defined('RESTORE_SILENTLY')) {
6244 echo "<li>".get_string("convertingwikitomarkdown");
6246 if (!$status = restore_convert_wiki2markdown($restore)) {
6247 if (!defined('RESTORE_SILENTLY')) {
6248 notify("Could not convert wiki texts to markdown!");
6250 $errorstr = "Could not convert wiki texts to markdown!";
6254 if (!defined('RESTORE_SILENTLY')) {
6259 /*******************************************************************************
6260 ************* Restore of Roles and Capabilities happens here ******************
6261 *******************************************************************************/
6263 $status = restore_create_roles($restore, $xml_file);
6264 $status = restore_roles_settings($restore, $xml_file);
6266 //Now if all is OK, update:
6267 // - course modinfo field
6268 // - categories table
6269 // - add user as teacher
6271 if (!defined('RESTORE_SILENTLY')) {
6272 echo "<li>".get_string("checkingcourse");
6275 rebuild_course_cache($restore->course_id
);
6277 $course = get_record("course","id",$restore->course_id
);
6278 fix_course_sortorder();
6279 // Check if the user has course update capability in the newly restored course
6280 // there is no need to load his capabilities again, because restore_roles_settings
6281 // would have loaded it anyway, if there is any assignments.
6283 $newcontext = get_context_instance(CONTEXT_COURSE
, $restore->course_id
);
6284 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
6285 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW
, get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
6286 if ($legacyteacher = array_shift($legacyteachers)) {
6287 role_assign($legacyteacher->id
, $USER->id
, 0, $newcontext->id
);
6290 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
6293 if (!defined('RESTORE_SILENTLY')) {
6298 //Cleanup temps (files and db)
6300 if (!defined('RESTORE_SILENTLY')) {
6301 echo "<li>".get_string("cleaningtempdata");
6303 if (!$status = clean_temp_data ($restore)) {
6304 if (!defined('RESTORE_SILENTLY')) {
6305 notify("Could not clean up temporary data from files and database");
6307 $errorstr = "Could not clean up temporary data from files and database";
6311 if (!defined('RESTORE_SILENTLY')) {
6316 if ($status = restore_close_html($restore)){
6317 echo '<li>Closing the Restorelog.html file.</li>';
6320 if (!defined('RESTORE_SILENTLY')) {
6324 //End the main table
6331 //Create, open and write header of the html log file
6332 function restore_open_html($restore,$course_header) {
6338 //Open file for writing
6339 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
6340 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
6341 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
6343 $status = check_dir_exists($dest_dir,true);
6344 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
6345 //Add the stylesheet
6346 $stylesheetshtml = '';
6347 foreach ($CFG->stylesheets
as $stylesheet) {
6348 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
6350 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
6351 $language = str_replace('_utf8','',$CFG->lang
);
6353 $languagehtml .= ' lang="'.$language.'" xml:lang="'.$language.'"';
6354 //Write the header in the new logging file
6355 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
6356 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
6357 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
6358 fwrite ($restorelog_file,"<head>");
6359 fwrite ($restorelog_file,$stylesheetshtml);
6360 fwrite ($restorelog_file,"<title>".$course_header->course_shortname
." Restored </title>");
6361 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
6362 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname
." The FullName is now - ".$course_header->course_fullname
."<br/><br/>");
6363 $startdate = addslashes($course_header->course_startdate
);
6364 $date = usergetdate($startdate);
6365 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
6366 $startdate +
= $restore->course_startdateoffset
;
6367 $date = usergetdate($startdate);
6368 fwrite ($restorelog_file," This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
6371 return $restorelog_file;
6376 //Create & close footer of the html log file
6377 function restore_close_html($restore) {
6383 //Open file for writing
6384 //First, check that course_id/backupdata folder exists in CFG->dataroot
6385 $dest_dir = $CFG->dataroot
."/".$restore->course_id
."/backupdata";
6386 $status = check_dir_exists($dest_dir, true, true);
6387 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
6388 //Write the footer to close the logging file
6389 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
6390 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
6393 return $restorelog_file;
6399 /********************** Roles and Capabilities Related Functions *******************************/
6401 /* Yu: Note recovering of role assignments/overrides need to take place after
6402 users have been recovered, i.e. after we get their new_id, and after all
6403 roles have been recreated or mapped. Contexts can be created on the fly.
6404 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
6405 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
6406 once roles and users have been restored.
6410 * This function restores all the needed roles for this course
6411 * i.e. roles with an assignment in any of the mods or blocks,
6412 * roles assigned on any user (e.g. parent role) and roles
6413 * assigned at course levle
6414 * This function should check for duplicate roles first
6415 * It isn't now, just overwriting
6417 function restore_create_roles($restore, $xmlfile) {
6418 if (!defined('RESTORE_SILENTLY')) {
6419 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
6421 $info = restore_read_xml_roles($xmlfile);
6423 $sitecontext = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
6425 // the following code creates new roles
6426 // but we could use more intelligent detection, and role mapping
6427 // get role mapping info from $restore
6428 $rolemappings = array();
6430 if (!empty($restore->rolesmapping
)) {
6431 $rolemappings = $restore->rolesmapping
;
6433 if (isset($info->roles
) && $info->roles
) {
6434 foreach ($info->roles
as $oldroleid=>$roledata) {
6436 /// first we check if the roles are in the mappings
6437 // if so, we just do a mapping i.e. update oldids table
6438 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
6439 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
6440 $rolemappings[$oldroleid]); // adding a new id
6444 // code to make new role name/short name if same role name or shortname exists
6445 $fullname = $roledata->name
;
6446 $shortname = $roledata->shortname
;
6447 $currentfullname = "";
6448 $currentshortname = "";
6453 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
6454 $suffixshort = "_".$counter;
6459 $currentfullname = $fullname.$suffixfull;
6460 // Limit the size of shortname - database column accepts <= 15 chars
6461 $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
6462 $coursefull = get_record("role","name",addslashes($currentfullname));
6463 $courseshort = get_record("role","shortname",addslashes($currentshortname));
6465 } while ($coursefull ||
$courseshort);
6467 $roledata->name
= $currentfullname;
6468 $roledata->shortname
= $currentshortname;
6470 // done finding a unique name
6472 $newroleid = create_role(addslashes($roledata->name
),addslashes($roledata->shortname
),'');
6473 $status = backup_putid($restore->backup_unique_code
,"role",$oldroleid,
6474 $newroleid); // adding a new id
6475 foreach ($roledata->capabilities
as $capability) {
6477 $roleinfo = new object();
6478 $roleinfo = (object)$capability;
6479 $roleinfo->contextid
= $sitecontext->id
;
6480 $roleinfo->capability
= $capability->name
;
6481 $roleinfo->roleid
= $newroleid;
6483 insert_record('role_capabilities', $roleinfo);
6492 * this function restores role assignments and role overrides
6493 * in course/user/block/mod level, it passed through
6494 * the xml file again
6496 function restore_roles_settings($restore, $xmlfile) {
6497 // data pulls from course, mod, user, and blocks
6499 /*******************************************************
6500 * Restoring from course level assignments *
6501 *******************************************************/
6502 if (!defined('RESTORE_SILENTLY')) {
6503 echo "<li>".get_string("creatingcourseroles").'</li>';
6505 $course = restore_read_xml_course_header($xmlfile);
6507 if (!empty($course->roleassignments
)) {
6508 $courseassignments = $course->roleassignments
;
6510 foreach ($courseassignments as $oldroleid => $courseassignment) {
6511 restore_write_roleassignments($restore, $courseassignment->assignments
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
6514 /*****************************************************
6515 * Restoring from course level overrides *
6516 *****************************************************/
6518 if (!empty($course->roleoverrides
)) {
6519 $courseoverrides = $course->roleoverrides
;
6520 foreach ($courseoverrides as $oldroleid => $courseoverride) {
6521 // if not importing into exiting course, or creating new role, we are ok
6522 // local course overrides to be respected (i.e. restored course overrides ignored)
6523 if ($restore->restoreto
!= 1 ||
empty($restore->rolesmapping
[$oldroleid])) {
6524 restore_write_roleoverrides($restore, $courseoverride->overrides
, "course", CONTEXT_COURSE
, $course->course_id
, $oldroleid);
6529 /*******************************************************
6530 * Restoring role assignments/overrdies *
6531 * from module level assignments *
6532 *******************************************************/
6534 if (!defined('RESTORE_SILENTLY')) {
6535 echo "<li>".get_string("creatingmodroles").'</li>';
6537 $sections = restore_read_xml_sections($xmlfile);
6538 $secs = $sections->sections
;
6540 foreach ($secs as $section) {
6541 if (isset($section->mods
)) {
6542 foreach ($section->mods
as $modid=>$mod) {
6543 if (isset($mod->roleassignments
)) {
6544 foreach ($mod->roleassignments
as $oldroleid=>$modassignment) {
6545 restore_write_roleassignments($restore, $modassignment->assignments
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
6548 if (isset($mod->roleoverrides
)) {
6549 foreach ($mod->roleoverrides
as $oldroleid=>$modoverride) {
6550 restore_write_roleoverrides($restore, $modoverride->overrides
, "course_modules", CONTEXT_MODULE
, $modid, $oldroleid);
6557 /*************************************************
6558 * Restoring assignments from blocks level *
6559 * role assignments/overrides *
6560 *************************************************/
6562 if ($restore->restoreto
!= 1) { // skip altogether if restoring to exisitng course by adding
6563 if (!defined('RESTORE_SILENTLY')) {
6564 echo "<li>".get_string("creatingblocksroles").'</li>';
6566 $blocks = restore_read_xml_blocks($xmlfile);
6567 if (isset($blocks->instances
)) {
6568 foreach ($blocks->instances
as $instance) {
6569 if (isset($instance->roleassignments
)) {
6570 foreach ($instance->roleassignments
as $oldroleid=>$blockassignment) {
6571 restore_write_roleassignments($restore, $blockassignment->assignments
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
6575 if (isset($instance->roleoverrides
)) {
6576 foreach ($instance->roleoverrides
as $oldroleid=>$blockoverride) {
6577 restore_write_roleoverrides($restore, $blockoverride->overrides
, "block_instance", CONTEXT_BLOCK
, $instance->id
, $oldroleid);
6583 /************************************************
6584 * Restoring assignments from userid level *
6585 * role assignments/overrides *
6586 ************************************************/
6587 if (!defined('RESTORE_SILENTLY')) {
6588 echo "<li>".get_string("creatinguserroles").'</li>';
6590 $info = restore_read_xml_users($restore, $xmlfile);
6591 if (!empty($info->users
)) {
6592 //For each user, take its info from backup_ids
6593 foreach ($info->users
as $userid) {
6594 $rec = backup_getid($restore->backup_unique_code
,"user",$userid);
6595 if (isset($rec->info
->roleassignments
)) {
6596 foreach ($rec->info
->roleassignments
as $oldroleid=>$userassignment) {
6597 restore_write_roleassignments($restore, $userassignment->assignments
, "user", CONTEXT_USER
, $userid, $oldroleid);
6600 if (isset($rec->info
->roleoverrides
)) {
6601 foreach ($rec->info
->roleoverrides
as $oldroleid=>$useroverride) {
6602 restore_write_roleoverrides($restore, $useroverride->overrides
, "user", CONTEXT_USER
, $userid, $oldroleid);
6611 // auxillary function to write role assignments read from xml to db
6612 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
6614 $role = backup_getid($restore->backup_unique_code
, "role", $oldroleid);
6616 foreach ($assignments as $assignment) {
6618 $olduser = backup_getid($restore->backup_unique_code
,"user",$assignment->userid
);
6619 if (!$olduser ||
$olduser->info
== "notincourse") { // it's possible that user is not in the course
6622 $assignment->userid
= $olduser->new_id
; // new userid here
6623 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$assignment->modifierid
);
6624 $assignment->modifierid
= !empty($oldmodifier->new_id
) ?
$oldmodifier->new_id
: 0; // new modifier id here
6625 $assignment->roleid
= $role->new_id
; // restored new role id
6627 // hack to make the correct contextid for course level imports
6628 if ($contextlevel == CONTEXT_COURSE
) {
6629 $oldinstance->new_id
= $restore->course_id
;
6631 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
6634 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
6635 $assignment->contextid
= $newcontext->id
; // new context id
6636 // might already have same assignment
6637 role_assign($assignment->roleid
, $assignment->userid
, 0, $assignment->contextid
, $assignment->timestart
, $assignment->timeend
, $assignment->hidden
, $assignment->enrol
);
6642 // auxillary function to write role assignments read from xml to db
6643 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
6645 // it is possible to have an override not relevant to this course context.
6646 // should be ignored(?)
6647 if (!$role = backup_getid($restore->backup_unique_code
, "role", $oldroleid)) {
6651 foreach ($overrides as $override) {
6652 $override->capability
= $override->name
;
6653 $oldmodifier = backup_getid($restore->backup_unique_code
,"user",$override->modifierid
);
6654 $override->modifierid
= $oldmodifier->new_id?
$oldmodifier->new_id
:0; // new modifier id here
6655 $override->roleid
= $role->new_id
; // restored new role id
6657 // hack to make the correct contextid for course level imports
6658 if ($contextlevel == CONTEXT_COURSE
) {
6659 $oldinstance->new_id
= $restore->course_id
;
6661 $oldinstance = backup_getid($restore->backup_unique_code
,$table,$oldid);
6664 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id
);
6665 $override->contextid
= $newcontext->id
; // new context id
6666 // might already have same override
6667 if (!get_record('role_capabilities', 'capability', $override->capability
, 'roleid', $override->roleid
, 'contextid', $override->contextid
)) {
6668 insert_record('role_capabilities', $override);
6672 //write activity date changes to the html log file, and update date values in the the xml array
6673 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
6678 // loop through time fields in $TAGS
6679 foreach ($TAGS as $TAG) {
6681 // check $TAG has a sensible value
6682 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
6684 if ($openlog==false) {
6685 $openlog = true; // only come through here once
6687 // open file for writing
6688 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
6689 check_dir_exists($course_dir, true);
6690 $restorelog = fopen("$course_dir/restorelog.html", "a");
6692 // start output for this record
6693 $msg = new stdClass();
6694 $msg->recordtype
= $recordtype;
6695 $msg->recordname
= $xml[$NAMETAG][0]['#'];
6696 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
6699 // write old date to $restorelog
6700 $value = $xml[$TAG][0]['#'];
6701 $date = usergetdate($value);
6703 $msg = new stdClass();
6705 $msg->weekday
= $date['weekday'];
6706 $msg->mday
= $date['mday'];
6707 $msg->month
= $date['month'];
6708 $msg->year
= $date['year'];
6709 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
6711 // write new date to $restorelog
6712 $value +
= $restore->course_startdateoffset
;
6713 $date = usergetdate($value);
6715 $msg = new stdClass();
6717 $msg->weekday
= $date['weekday'];
6718 $msg->mday
= $date['mday'];
6719 $msg->month
= $date['month'];
6720 $msg->year
= $date['year'];
6721 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
6723 // update $value in $xml tree for calling module
6724 $xml[$TAG][0]['#'] = "$value";
6727 // close the restore log, if it was opened
6729 fclose($restorelog);