MDL-11515:
[moodle-linuxchix.git] / backup / restorelib.php
blob140738eed4ea68ea7bdd673ff81d7f836b4a3c03
1 <?php //$Id$
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) {
16 $status = true;
18 //Check if it exists
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
25 if ($status) {
26 $status = strpos($first_chars,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
27 if ($status !== false) {
28 $status = strpos($first_chars,"<MOODLE_BACKUP>");
33 return $status;
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) {
40 global $CFG;
41 $status = true;
43 //Take all modules in backup
44 $modules = $restore->mods;
45 //Iterate
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);
58 return $status;
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) {
66 global $CFG;
68 $status = true;
70 if (!defined('RESTORE_SILENTLY')) {
71 echo "<ul>";
74 // Restore links in modules.
75 foreach ($restore->mods as $name => $info) {
76 //If the module is being restored
77 if (isset($info->restore) && $info->restore == 1) {
78 //Check if the xxxx_decode_content_links_caller exists
79 include_once("$CFG->dirroot/mod/$name/restorelib.php");
80 $function_name = $name."_decode_content_links_caller";
81 if (function_exists($function_name)) {
82 if (!defined('RESTORE_SILENTLY')) {
83 echo "<li>".get_string ("from")." ".get_string("modulenameplural",$name);
85 $status = $function_name($restore);
86 if (!defined('RESTORE_SILENTLY')) {
87 echo '</li>';
93 // TODO: process all html text also in blocks too
95 // Restore links in questions.
96 require_once("$CFG->dirroot/question/restorelib.php");
97 if (!defined('RESTORE_SILENTLY')) {
98 echo '<li>' . get_string('from') . ' ' . get_string('questions', 'quiz');
100 $status = question_decode_content_links_caller($restore);
101 if (!defined('RESTORE_SILENTLY')) {
102 echo '</li>';
105 if (!defined('RESTORE_SILENTLY')) {
106 echo "</ul>";
109 return $status;
112 //This function is called from all xxxx_decode_content_links_caller(),
113 //its task is to ask all modules (maybe other linkable objects) to restore
114 //links to them.
115 function restore_decode_content_links_worker($content,$restore) {
116 foreach($restore->mods as $name => $info) {
117 $function_name = $name."_decode_content_links";
118 if (function_exists($function_name)) {
119 $content = $function_name($content,$restore);
122 return $content;
125 //This function converts all the wiki texts in the restored course
126 //to the Markdown format. Used only for backup files prior 2005041100.
127 //It calls every module xxxx_convert_wiki2markdown function
128 function restore_convert_wiki2markdown($restore) {
130 $status = true;
132 if (!defined('RESTORE_SILENTLY')) {
133 echo "<ul>";
135 foreach ($restore->mods as $name => $info) {
136 //If the module is being restored
137 if ($info->restore == 1) {
138 //Check if the xxxx_restore_wiki2markdown exists
139 $function_name = $name."_restore_wiki2markdown";
140 if (function_exists($function_name)) {
141 $status = $function_name($restore);
142 if (!defined('RESTORE_SILENTLY')) {
143 echo "<li>".get_string("modulenameplural",$name);
144 echo '</li>';
149 if (!defined('RESTORE_SILENTLY')) {
150 echo "</ul>";
152 return $status;
155 //This function receives a wiki text in the restore process and
156 //return it with every link to modules " modulename:moduleid"
157 //converted if possible. See the space before modulename!!
158 function restore_decode_wiki_content($content,$restore) {
160 global $CFG;
162 $result = $content;
164 $searchstring='/ ([a-zA-Z]+):([0-9]+)\(([^)]+)\)/';
165 //We look for it
166 preg_match_all($searchstring,$content,$foundset);
167 //If found, then we are going to look for its new id (in backup tables)
168 if ($foundset[0]) {
169 //print_object($foundset); //Debug
170 //Iterate over foundset[2]. They are the old_ids
171 foreach($foundset[2] as $old_id) {
172 //We get the needed variables here (course id)
173 $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id);
174 //Personalize the searchstring
175 $searchstring='/ ([a-zA-Z]+):'.$old_id.'\(([^)]+)\)/';
176 //If it is a link to this course, update the link to its new location
177 if($rec->new_id) {
178 //Now replace it
179 $result= preg_replace($searchstring,' $1:'.$rec->new_id.'($2)',$result);
180 } else {
181 //It's a foreign link so redirect it to its original URL
182 $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/$1/view.php?id='.$old_id.'($2)',$result);
186 return $result;
190 //This function read the xml file and store it data from the info zone in an object
191 function restore_read_xml_info ($xml_file) {
193 //We call the main read_xml function, with todo = INFO
194 $info = restore_read_xml ($xml_file,"INFO",false);
196 return $info;
199 //This function read the xml file and store it data from the course header zone in an object
200 function restore_read_xml_course_header ($xml_file) {
202 //We call the main read_xml function, with todo = COURSE_HEADER
203 $info = restore_read_xml ($xml_file,"COURSE_HEADER",false);
205 return $info;
208 //This function read the xml file and store its data from the blocks in a object
209 function restore_read_xml_blocks ($xml_file) {
211 //We call the main read_xml function, with todo = BLOCKS
212 $info = restore_read_xml ($xml_file,'BLOCKS',false);
214 return $info;
217 //This function read the xml file and store its data from the sections in a object
218 function restore_read_xml_sections ($xml_file) {
220 //We call the main read_xml function, with todo = SECTIONS
221 $info = restore_read_xml ($xml_file,"SECTIONS",false);
223 return $info;
226 //This function read the xml file and store its data from the course format in an object
227 function restore_read_xml_formatdata ($xml_file) {
229 //We call the main read_xml function, with todo = FORMATDATA
230 $info = restore_read_xml ($xml_file,'FORMATDATA',false);
232 return $info;
235 //This function read the xml file and store its data from the metacourse in a object
236 function restore_read_xml_metacourse ($xml_file) {
238 //We call the main read_xml function, with todo = METACOURSE
239 $info = restore_read_xml ($xml_file,"METACOURSE",false);
241 return $info;
244 //This function read the xml file and store its data from the gradebook in a object
245 function restore_read_xml_gradebook ($restore, $xml_file) {
247 //We call the main read_xml function, with todo = GRADEBOOK
248 $info = restore_read_xml ($xml_file,"GRADEBOOK",$restore);
250 return $info;
253 //This function read the xml file and store its data from the users in
254 //backup_ids->info db (and user's id in $info)
255 function restore_read_xml_users ($restore,$xml_file) {
257 //We call the main read_xml function, with todo = USERS
258 $info = restore_read_xml ($xml_file,"USERS",$restore);
260 return $info;
263 //This function read the xml file and store its data from the messages in
264 //backup_ids->message backup_ids->message_read and backup_ids->contact and db (and their counters in info)
265 function restore_read_xml_messages ($restore,$xml_file) {
267 //We call the main read_xml function, with todo = MESSAGES
268 $info = restore_read_xml ($xml_file,"MESSAGES",$restore);
270 return $info;
274 //This function read the xml file and store its data from the questions in
275 //backup_ids->info db (and category's id in $info)
276 function restore_read_xml_questions ($restore,$xml_file) {
278 //We call the main read_xml function, with todo = QUESTIONS
279 $info = restore_read_xml ($xml_file,"QUESTIONS",$restore);
281 return $info;
284 //This function read the xml file and store its data from the scales in
285 //backup_ids->info db (and scale's id in $info)
286 function restore_read_xml_scales ($restore,$xml_file) {
288 //We call the main read_xml function, with todo = SCALES
289 $info = restore_read_xml ($xml_file,"SCALES",$restore);
291 return $info;
294 //This function read the xml file and store its data from the groups in
295 //backup_ids->info db (and group's id in $info)
296 function restore_read_xml_groups ($restore,$xml_file) {
298 //We call the main read_xml function, with todo = GROUPS
299 $info = restore_read_xml ($xml_file,"GROUPS",$restore);
301 return $info;
304 //This function read the xml file and store its data from the groupings in
305 //backup_ids->info db (and grouping's id in $info)
306 function restore_read_xml_groupings ($restore,$xml_file) {
308 //We call the main read_xml function, with todo = GROUPINGS
309 $info = restore_read_xml ($xml_file,"GROUPINGS",$restore);
311 return $info;
314 //This function read the xml file and store its data from the groupings in
315 //backup_ids->info db (and grouping's id in $info)
316 function restore_read_xml_groupings_groups ($restore,$xml_file) {
318 //We call the main read_xml function, with todo = GROUPINGS
319 $info = restore_read_xml ($xml_file,"GROUPINGSGROUPS",$restore);
321 return $info;
324 //This function read the xml file and store its data from the events (course) in
325 //backup_ids->info db (and event's id in $info)
326 function restore_read_xml_events ($restore,$xml_file) {
328 //We call the main read_xml function, with todo = EVENTS
329 $info = restore_read_xml ($xml_file,"EVENTS",$restore);
331 return $info;
334 //This function read the xml file and store its data from the modules in
335 //backup_ids->info
336 function restore_read_xml_modules ($restore,$xml_file) {
338 //We call the main read_xml function, with todo = MODULES
339 $info = restore_read_xml ($xml_file,"MODULES",$restore);
341 return $info;
344 //This function read the xml file and store its data from the logs in
345 //backup_ids->info
346 function restore_read_xml_logs ($restore,$xml_file) {
348 //We call the main read_xml function, with todo = LOGS
349 $info = restore_read_xml ($xml_file,"LOGS",$restore);
351 return $info;
354 function restore_read_xml_roles ($xml_file) {
355 //We call the main read_xml function, with todo = ROLES
356 $info = restore_read_xml ($xml_file,"ROLES",false);
358 return $info;
361 //This function prints the contents from the info parammeter passed
362 function restore_print_info ($info) {
364 global $CFG;
366 $status = true;
367 if ($info) {
368 $table = new object();
369 //This is tha align to every ingo table
370 $table->align = array ("right","left");
371 //This is the nowrap clause
372 $table->wrap = array ("","nowrap");
373 //The width
374 $table->width = "70%";
375 //Put interesting info in table
376 //The backup original name
377 $tab[0][0] = "<b>".get_string("backuporiginalname").":</b>";
378 $tab[0][1] = $info->backup_name;
379 //The moodle version
380 $tab[1][0] = "<b>".get_string("moodleversion").":</b>";
381 $tab[1][1] = $info->backup_moodle_release." (".$info->backup_moodle_version.")";
382 //The backup version
383 $tab[2][0] = "<b>".get_string("backupversion").":</b>";
384 $tab[2][1] = $info->backup_backup_release." (".$info->backup_backup_version.")";
385 //The backup date
386 $tab[3][0] = "<b>".get_string("backupdate").":</b>";
387 $tab[3][1] = userdate($info->backup_date);
388 //Print title
389 print_heading(get_string("backup").":");
390 $table->data = $tab;
391 //Print backup general info
392 print_table($table);
394 if ($info->backup_backup_version <= 2005070500) {
395 notify(get_string('backupnonisowarning')); // Message informing that this backup may not work!
398 //Now backup contents in another table
399 $tab = array();
400 //First mods info
401 $mods = $info->mods;
402 $elem = 0;
403 foreach ($mods as $key => $mod) {
404 $tab[$elem][0] = "<b>".get_string("modulenameplural",$key).":</b>";
405 if ($mod->backup == "false") {
406 $tab[$elem][1] = get_string("notincluded");
407 } else {
408 if ($mod->userinfo == "true") {
409 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
410 } else {
411 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
413 if (isset($mod->instances) && is_array($mod->instances) && count($mod->instances)) {
414 foreach ($mod->instances as $instance) {
415 if ($instance->backup) {
416 $elem++;
417 $tab[$elem][0] = $instance->name;
418 if ($instance->userinfo == 'true') {
419 $tab[$elem][1] = get_string("included")." ".get_string("withuserdata");
420 } else {
421 $tab[$elem][1] = get_string("included")." ".get_string("withoutuserdata");
427 $elem++;
429 //Metacourse info
430 $tab[$elem][0] = "<b>".get_string("metacourse").":</b>";
431 if ($info->backup_metacourse == "true") {
432 $tab[$elem][1] = get_string("yes");
433 } else {
434 $tab[$elem][1] = get_string("no");
436 $elem++;
437 //Users info
438 $tab[$elem][0] = "<b>".get_string("users").":</b>";
439 $tab[$elem][1] = get_string($info->backup_users);
440 $elem++;
441 //Logs info
442 $tab[$elem][0] = "<b>".get_string("logs").":</b>";
443 if ($info->backup_logs == "true") {
444 $tab[$elem][1] = get_string("yes");
445 } else {
446 $tab[$elem][1] = get_string("no");
448 $elem++;
449 //User Files info
450 $tab[$elem][0] = "<b>".get_string("userfiles").":</b>";
451 if ($info->backup_user_files == "true") {
452 $tab[$elem][1] = get_string("yes");
453 } else {
454 $tab[$elem][1] = get_string("no");
456 $elem++;
457 //Course Files info
458 $tab[$elem][0] = "<b>".get_string("coursefiles").":</b>";
459 if ($info->backup_course_files == "true") {
460 $tab[$elem][1] = get_string("yes");
461 } else {
462 $tab[$elem][1] = get_string("no");
464 $elem++;
465 //site Files info
466 $tab[$elem][0] = "<b>".get_string("sitefiles").":</b>";
467 if (isset($info->backup_site_files) && $info->backup_site_files == "true") {
468 $tab[$elem][1] = get_string("yes");
469 } else {
470 $tab[$elem][1] = get_string("no");
472 $elem++;
473 //Messages info (only showed if present)
474 if ($info->backup_messages == 'true') {
475 $tab[$elem][0] = "<b>".get_string('messages','message').":</b>";
476 $tab[$elem][1] = get_string('yes');
477 $elem++;
478 } else {
479 //Do nothing
481 $table->data = $tab;
482 //Print title
483 print_heading(get_string("backupdetails").":");
484 //Print backup general info
485 print_table($table);
486 } else {
487 $status = false;
490 return $status;
493 //This function prints the contents from the course_header parammeter passed
494 function restore_print_course_header ($course_header) {
496 $status = true;
497 if ($course_header) {
498 $table = new object();
499 //This is tha align to every ingo table
500 $table->align = array ("right","left");
501 //The width
502 $table->width = "70%";
503 //Put interesting course header in table
504 //The course name
505 $tab[0][0] = "<b>".get_string("name").":</b>";
506 $tab[0][1] = $course_header->course_fullname." (".$course_header->course_shortname.")";
507 //The course summary
508 $tab[1][0] = "<b>".get_string("summary").":</b>";
509 $tab[1][1] = $course_header->course_summary;
510 $table->data = $tab;
511 //Print title
512 print_heading(get_string("course").":");
513 //Print backup course header info
514 print_table($table);
515 } else {
516 $status = false;
518 return $status;
521 //This function create a new course record.
522 //When finished, course_header contains the id of the new course
523 function restore_create_new_course($restore,&$course_header) {
525 global $CFG;
527 $status = true;
529 $fullname = $course_header->course_fullname;
530 $shortname = $course_header->course_shortname;
531 $currentfullname = "";
532 $currentshortname = "";
533 $counter = 0;
534 //Iteratere while the name exists
535 do {
536 if ($counter) {
537 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
538 $suffixshort = "_".$counter;
539 } else {
540 $suffixfull = "";
541 $suffixshort = "";
543 $currentfullname = $fullname.$suffixfull;
544 // Limit the size of shortname - database column accepts <= 100 chars
545 $currentshortname = substr($shortname, 0, 100 - strlen($suffixshort)).$suffixshort;
546 $coursefull = get_record("course","fullname",addslashes($currentfullname));
547 $courseshort = get_record("course","shortname",addslashes($currentshortname));
548 $counter++;
549 } while ($coursefull || $courseshort);
551 //New name = currentname
552 $course_header->course_fullname = $currentfullname;
553 $course_header->course_shortname = $currentshortname;
555 // first try to get it from restore
556 if ($restore->restore_restorecatto) {
557 $category = get_record('course_categories', 'id', $restore->restore_restorecatto);
560 // else we try to get it from the xml file
561 //Now calculate the category
562 if (!$category) {
563 $category = get_record("course_categories","id",$course_header->category->id,
564 "name",addslashes($course_header->category->name));
567 //If no exists, try by name only
568 if (!$category) {
569 $category = get_record("course_categories","name",addslashes($course_header->category->name));
572 //If no exists, get category id 1
573 if (!$category) {
574 $category = get_record("course_categories","id","1");
577 //If category 1 doesn'exists, lets create the course category (get it from backup file)
578 if (!$category) {
579 $ins_category = new object();
580 $ins_category->name = addslashes($course_header->category->name);
581 $ins_category->parent = 0;
582 $ins_category->sortorder = 0;
583 $ins_category->coursecount = 0;
584 $ins_category->visible = 0; //To avoid interferences with the rest of the site
585 $ins_category->timemodified = time();
586 $newid = insert_record("course_categories",$ins_category);
587 $category->id = $newid;
588 $category->name = $course_header->category->name;
590 //If exists, put new category id
591 if ($category) {
592 $course_header->category->id = $category->id;
593 $course_header->category->name = $category->name;
594 //Error, cannot locate category
595 } else {
596 $course_header->category->id = 0;
597 $course_header->category->name = get_string("unknowncategory");
598 $status = false;
601 //Create the course_object
602 if ($status) {
603 $course = new object();
604 $course->category = addslashes($course_header->category->id);
605 $course->password = addslashes($course_header->course_password);
606 $course->fullname = addslashes($course_header->course_fullname);
607 $course->shortname = addslashes($course_header->course_shortname);
608 $course->idnumber = addslashes($course_header->course_idnumber);
609 $course->idnumber = ''; //addslashes($course_header->course_idnumber); // we don't want this at all.
610 $course->summary = backup_todb($course_header->course_summary);
611 $course->format = addslashes($course_header->course_format);
612 $course->showgrades = addslashes($course_header->course_showgrades);
613 $course->newsitems = addslashes($course_header->course_newsitems);
614 $course->teacher = addslashes($course_header->course_teacher);
615 $course->teachers = addslashes($course_header->course_teachers);
616 $course->student = addslashes($course_header->course_student);
617 $course->students = addslashes($course_header->course_students);
618 $course->guest = addslashes($course_header->course_guest);
619 $course->startdate = addslashes($course_header->course_startdate);
620 $course->startdate += $restore->course_startdateoffset;
621 $course->numsections = addslashes($course_header->course_numsections);
622 //$course->showrecent = addslashes($course_header->course_showrecent); INFO: This is out in 1.3
623 $course->maxbytes = addslashes($course_header->course_maxbytes);
624 $course->showreports = addslashes($course_header->course_showreports);
625 if (isset($course_header->course_groupmode)) {
626 $course->groupmode = addslashes($course_header->course_groupmode);
628 if (isset($course_header->course_groupmodeforce)) {
629 $course->groupmodeforce = addslashes($course_header->course_groupmodeforce);
631 if (isset($course_header->course_defaultgroupingid)) {
632 //keep the original now - convert after groupings restored
633 $course->defaultgroupingid = addslashes($course_header->course_defaultgroupingid);
635 $course->lang = addslashes($course_header->course_lang);
636 $course->theme = addslashes($course_header->course_theme);
637 $course->cost = addslashes($course_header->course_cost);
638 $course->currency = isset($course_header->course_currency)?addslashes($course_header->course_currency):'';
639 $course->marker = addslashes($course_header->course_marker);
640 $course->visible = addslashes($course_header->course_visible);
641 $course->hiddensections = addslashes($course_header->course_hiddensections);
642 $course->timecreated = addslashes($course_header->course_timecreated);
643 $course->timemodified = addslashes($course_header->course_timemodified);
644 $course->metacourse = addslashes($course_header->course_metacourse);
645 $course->expirynotify = isset($course_header->course_expirynotify) ? addslashes($course_header->course_expirynotify):0;
646 $course->notifystudents = isset($course_header->course_notifystudents) ? addslashes($course_header->course_notifystudents) : 0;
647 $course->expirythreshold = isset($course_header->course_expirythreshold) ? addslashes($course_header->course_expirythreshold) : 0;
648 $course->enrollable = isset($course_header->course_enrollable) ? addslashes($course_header->course_enrollable) : 1;
649 $course->enrolstartdate = isset($course_header->course_enrolstartdate) ? addslashes($course_header->course_enrolstartdate) : 0;
650 if ($course->enrolstartdate) { //Roll course dates
651 $course->enrolstartdate += $restore->course_startdateoffset;
653 $course->enrolenddate = isset($course_header->course_enrolenddate) ? addslashes($course_header->course_enrolenddate) : 0;
654 if ($course->enrolenddate) { //Roll course dates
655 $course->enrolenddate += $restore->course_startdateoffset;
657 $course->enrolperiod = addslashes($course_header->course_enrolperiod);
658 //Calculate sortorder field
659 $sortmax = get_record_sql('SELECT MAX(sortorder) AS max
660 FROM ' . $CFG->prefix . 'course
661 WHERE category=' . $course->category);
662 if (!empty($sortmax->max)) {
663 $course->sortorder = $sortmax->max + 1;
664 unset($sortmax);
665 } else {
666 $course->sortorder = 100;
669 //Now, recode some languages (Moodle 1.5)
670 if ($course->lang == 'ma_nt') {
671 $course->lang = 'mi_nt';
674 //Disable course->metacourse if avoided in restore config
675 if (!$restore->metacourse) {
676 $course->metacourse = 0;
679 //Check if the theme exists in destination server
680 $themes = get_list_of_themes();
681 if (!in_array($course->theme, $themes)) {
682 $course->theme = '';
685 //Now insert the record
686 $newid = insert_record("course",$course);
687 if ($newid) {
688 //save old and new course id
689 backup_putid ($restore->backup_unique_code,"course",$course_header->course_id,$newid);
690 //Replace old course_id in course_header
691 $course_header->course_id = $newid;
692 } else {
693 $status = false;
697 return $status;
702 //This function creates all the block stuff when restoring courses
703 //It calls selectively to restore_create_block_instances() for 1.5
704 //and above backups. Upwards compatible with old blocks.
705 function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) {
707 $status = true;
709 delete_records('block_instance', 'pageid', $restore->course_id, 'pagetype', PAGE_COURSE_VIEW);
710 if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5
711 if (empty($blockinfo)) {
712 // Looks like it's from Moodle < 1.3. Let's give the course default blocks...
713 $newpage = page_create_object(PAGE_COURSE_VIEW, $restore->course_id);
714 blocks_repopulate_page($newpage);
715 } else {
716 // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup
717 $blockrecords = get_records_select('block', '', '', 'name, id');
718 $temp_blocks_l = array();
719 $temp_blocks_r = array();
720 @list($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo);
721 $temp_blocks = array(BLOCK_POS_LEFT => explode(',', $temp_blocks_l), BLOCK_POS_RIGHT => explode(',', $temp_blocks_r));
722 foreach($temp_blocks as $blockposition => $blocks) {
723 $blockweight = 0;
724 foreach($blocks as $blockname) {
725 if(!isset($blockrecords[$blockname])) {
726 // We don't know anything about this block!
727 continue;
729 $blockinstance = new stdClass;
730 // Remove any - prefix before doing the name-to-id mapping
731 if(substr($blockname, 0, 1) == '-') {
732 $blockname = substr($blockname, 1);
733 $blockinstance->visible = 0;
734 } else {
735 $blockinstance->visible = 1;
737 $blockinstance->blockid = $blockrecords[$blockname]->id;
738 $blockinstance->pageid = $restore->course_id;
739 $blockinstance->pagetype = PAGE_COURSE_VIEW;
740 $blockinstance->position = $blockposition;
741 $blockinstance->weight = $blockweight;
742 if(!$status = insert_record('block_instance', $blockinstance)) {
743 $status = false;
745 ++$blockweight;
749 } else if($backup_block_format == 'instances') {
750 $status = restore_create_block_instances($restore,$xml_file);
753 return $status;
757 //This function creates all the block_instances from xml when restoring in a
758 //new course
759 function restore_create_block_instances($restore,$xml_file) {
761 $status = true;
762 //Check it exists
763 if (!file_exists($xml_file)) {
764 $status = false;
766 //Get info from xml
767 if ($status) {
768 $info = restore_read_xml_blocks($xml_file);
771 if(empty($info->instances)) {
772 return $status;
775 // First of all, iterate over the blocks to see which distinct pages we have
776 // in our hands and arrange the blocks accordingly.
777 $pageinstances = array();
778 foreach($info->instances as $instance) {
780 //pagetype and pageid black magic, we have to handle the case of blocks for the
781 //course, blocks from other pages in that course etc etc etc.
783 if($instance->pagetype == PAGE_COURSE_VIEW) {
784 // This one's easy...
785 $instance->pageid = $restore->course_id;
787 else {
788 $parts = explode('-', $instance->pagetype);
789 if($parts[0] == 'mod') {
790 if(!$restore->mods[$parts[1]]->restore) {
791 continue;
793 $getid = backup_getid($restore->backup_unique_code, $parts[1], $instance->pageid);
794 $instance->pageid = $getid->new_id;
796 else {
797 // Not invented here ;-)
798 continue;
802 if(!isset($pageinstances[$instance->pagetype])) {
803 $pageinstances[$instance->pagetype] = array();
805 if(!isset($pageinstances[$instance->pagetype][$instance->pageid])) {
806 $pageinstances[$instance->pagetype][$instance->pageid] = array();
809 $pageinstances[$instance->pagetype][$instance->pageid][] = $instance;
812 $blocks = get_records_select('block', '', '', 'name, id, multiple');
814 // For each type of page we have restored
815 foreach($pageinstances as $thistypeinstances) {
817 // For each page id of that type
818 foreach($thistypeinstances as $thisidinstances) {
820 $addedblocks = array();
821 $maxweights = array();
823 // For each block instance in that page
824 foreach($thisidinstances as $instance) {
826 if(!isset($blocks[$instance->name])) {
827 //We are trying to restore a block we don't have...
828 continue;
831 //If we have already added this block once and multiples aren't allowed, disregard it
832 if(!$blocks[$instance->name]->multiple && isset($addedblocks[$instance->name])) {
833 continue;
836 //If its the first block we add to a new position, start weight counter equal to 0.
837 if(empty($maxweights[$instance->position])) {
838 $maxweights[$instance->position] = 0;
841 //If the instance weight is greater than the weight counter (we skipped some earlier
842 //blocks most probably), bring it back in line.
843 if($instance->weight > $maxweights[$instance->position]) {
844 $instance->weight = $maxweights[$instance->position];
847 //Add this instance
848 $instance->blockid = $blocks[$instance->name]->id;
850 if ($newid = insert_record('block_instance', $instance)) {
851 if (!empty($instance->id)) { // this will only be set if we come from 1.7 and above backups
852 backup_putid ($restore->backup_unique_code,"block_instance",$instance->id,$newid);
854 } else {
855 $status = false;
856 break;
859 //Get an object for the block and tell it it's been restored so it can update dates
860 //etc. if necessary
861 $blockobj=block_instance($instance->name,$instance);
862 $blockobj->after_restore($restore);
864 //Now we can increment the weight counter
865 ++$maxweights[$instance->position];
867 //Keep track of block types we have already added
868 $addedblocks[$instance->name] = true;
874 return $status;
877 //This function creates all the course_sections and course_modules from xml
878 //when restoring in a new course or simply checks sections and create records
879 //in backup_ids when restoring in a existing course
880 function restore_create_sections(&$restore, $xml_file) {
882 global $CFG,$db;
884 $status = true;
885 //Check it exists
886 if (!file_exists($xml_file)) {
887 $status = false;
889 //Get info from xml
890 if ($status) {
891 $info = restore_read_xml_sections($xml_file);
893 //Put the info in the DB, recoding ids and saving the in backup tables
895 $sequence = "";
897 if ($info) {
898 //For each, section, save it to db
899 foreach ($info->sections as $key => $sect) {
900 $sequence = "";
901 $section = new object();
902 $section->course = $restore->course_id;
903 $section->section = $sect->number;
904 $section->summary = backup_todb($sect->summary);
905 $section->visible = $sect->visible;
906 $section->sequence = "";
907 //Now calculate the section's newid
908 $newid = 0;
909 if ($restore->restoreto == 2) {
910 //Save it to db (only if restoring to new course)
911 $newid = insert_record("course_sections",$section);
912 } else {
913 //Get section id when restoring in existing course
914 $rec = get_record("course_sections","course",$restore->course_id,
915 "section",$section->section);
916 //If that section doesn't exist, get section 0 (every mod will be
917 //asigned there
918 if(!$rec) {
919 $rec = get_record("course_sections","course",$restore->course_id,
920 "section","0");
922 //New check. If section 0 doesn't exist, insert it here !!
923 //Teorically this never should happen but, in practice, some users
924 //have reported this issue.
925 if(!$rec) {
926 $zero_sec = new object();
927 $zero_sec->course = $restore->course_id;
928 $zero_sec->section = 0;
929 $zero_sec->summary = "";
930 $zero_sec->sequence = "";
931 $newid = insert_record("course_sections",$zero_sec);
932 $rec->id = $newid;
933 $rec->sequence = "";
935 $newid = $rec->id;
936 $sequence = $rec->sequence;
938 if ($newid) {
939 //save old and new section id
940 backup_putid ($restore->backup_unique_code,"course_sections",$key,$newid);
941 } else {
942 $status = false;
944 //If all is OK, go with associated mods
945 if ($status) {
946 //If we have mods in the section
947 if (!empty($sect->mods)) {
948 //For each mod inside section
949 foreach ($sect->mods as $keym => $mod) {
950 // Yu: This part is called repeatedly for every instance,
951 // so it is necessary to set the granular flag and check isset()
952 // when the first instance of this type of mod is processed.
954 //if (!isset($restore->mods[$mod->type]->granular) && isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) {
956 if (!isset($restore->mods[$mod->type]->granular)) {
957 if (isset($restore->mods[$mod->type]->instances) && is_array($restore->mods[$mod->type]->instances)) {
958 // This defines whether we want to restore specific
959 // instances of the modules (granular restore), or
960 // whether we don't care and just want to restore
961 // all module instances (non-granular).
962 $restore->mods[$mod->type]->granular = true;
963 } else {
964 $restore->mods[$mod->type]->granular = false;
968 //Check if we've to restore this module (and instance)
969 if (!empty($restore->mods[$mod->type]->restore)) {
970 if (empty($restore->mods[$mod->type]->granular) // we don't care about per instance
971 || (array_key_exists($mod->instance,$restore->mods[$mod->type]->instances)
972 && !empty($restore->mods[$mod->type]->instances[$mod->instance]->restore))) {
974 //Get the module id from modules
975 $module = get_record("modules","name",$mod->type);
976 if ($module) {
977 $course_module = new object();
978 $course_module->course = $restore->course_id;
979 $course_module->module = $module->id;
980 $course_module->section = $newid;
981 $course_module->added = $mod->added;
982 $course_module->score = $mod->score;
983 $course_module->indent = $mod->indent;
984 $course_module->visible = $mod->visible;
985 $course_module->groupmode = $mod->groupmode;
986 if ($mod->groupingid and $grouping = backup_getid($restore->backup_unique_code,"groupings",$mod->groupingid)) {
987 $course_module->groupingid = $grouping->new_id;
988 } else {
989 $course_module->groupingid = 0;
991 $course_module->groupmembersonly = $mod->groupmembersonly;
992 $course_module->instance = 0;
993 //NOTE: The instance (new) is calculated and updated in db in the
994 // final step of the restore. We don't know it yet.
995 //print_object($course_module); //Debug
996 //Save it to db
998 $newidmod = insert_record("course_modules",$course_module);
999 if ($newidmod) {
1000 //save old and new module id
1001 //In the info field, we save the original instance of the module
1002 //to use it later
1003 backup_putid ($restore->backup_unique_code,"course_modules",
1004 $keym,$newidmod,$mod->instance);
1006 $restore->mods[$mod->type]->instances[$mod->instance]->restored_as_course_module = $newidmod;
1007 } else {
1008 $status = false;
1010 //Now, calculate the sequence field
1011 if ($status) {
1012 if ($sequence) {
1013 $sequence .= ",".$newidmod;
1014 } else {
1015 $sequence = $newidmod;
1018 } else {
1019 $status = false;
1026 //If all is OK, update sequence field in course_sections
1027 if ($status) {
1028 if (isset($sequence)) {
1029 $update_rec = new object();
1030 $update_rec->id = $newid;
1031 $update_rec->sequence = $sequence;
1032 $status = update_record("course_sections",$update_rec);
1036 } else {
1037 $status = false;
1039 return $status;
1042 //Called to set up any course-format specific data that may be in the file
1043 function restore_set_format_data($restore,$xml_file) {
1044 global $CFG,$db;
1046 $status = true;
1047 //Check it exists
1048 if (!file_exists($xml_file)) {
1049 return false;
1051 //Load data from XML to info
1052 if(!($info = restore_read_xml_formatdata($xml_file))) {
1053 return false;
1056 //Process format data if there is any
1057 if (isset($info->format_data)) {
1058 if(!$format=get_field('course','format','id',$restore->course_id)) {
1059 return false;
1061 // If there was any data then it must have a restore method
1062 $file=$CFG->dirroot."/course/format/$format/restorelib.php";
1063 if(!file_exists($file)) {
1064 return false;
1066 require_once($file);
1067 $function=$format.'_restore_format_data';
1068 if(!function_exists($function)) {
1069 return false;
1071 return $function($restore,$info->format_data);
1074 // If we got here then there's no data, but that's cool
1075 return true;
1078 //This function creates all the metacourse data from xml, notifying
1079 //about each incidence
1080 function restore_create_metacourse($restore,$xml_file) {
1082 global $CFG,$db;
1084 $status = true;
1085 //Check it exists
1086 if (!file_exists($xml_file)) {
1087 $status = false;
1089 //Get info from xml
1090 if ($status) {
1091 //Load data from XML to info
1092 $info = restore_read_xml_metacourse($xml_file);
1095 //Process info about metacourse
1096 if ($status and $info) {
1097 //Process child records
1098 if (!empty($info->childs)) {
1099 foreach ($info->childs as $child) {
1100 $dbcourse = false;
1101 $dbmetacourse = false;
1102 //Check if child course exists in destination server
1103 //(by id in the same server or by idnumber and shortname in other server)
1104 if ($restore->original_wwwroot == $CFG->wwwroot) {
1105 //Same server, lets see by id
1106 $dbcourse = get_record('course','id',$child->id);
1107 } else {
1108 //Different server, lets see by idnumber and shortname, and only ONE record
1109 $dbcount = count_records('course','idnumber',$child->idnumber,'shortname',$child->shortname);
1110 if ($dbcount == 1) {
1111 $dbcourse = get_record('course','idnumber',$child->idnumber,'shortname',$child->shortname);
1114 //If child course has been found, insert data
1115 if ($dbcourse) {
1116 $dbmetacourse->child_course = $dbcourse->id;
1117 $dbmetacourse->parent_course = $restore->course_id;
1118 $status = insert_record ('course_meta',$dbmetacourse);
1119 } else {
1120 //Child course not found, notice!
1121 if (!defined('RESTORE_SILENTLY')) {
1122 echo '<ul><li>'.get_string ('childcoursenotfound').' ('.$child->id.'/'.$child->idnumber.'/'.$child->shortname.')</li></ul>';
1126 //Now, recreate student enrolments...
1127 sync_metacourse($restore->course_id);
1129 //Process parent records
1130 if (!empty($info->parents)) {
1131 foreach ($info->parents as $parent) {
1132 $dbcourse = false;
1133 $dbmetacourse = false;
1134 //Check if parent course exists in destination server
1135 //(by id in the same server or by idnumber and shortname in other server)
1136 if ($restore->original_wwwroot == $CFG->wwwroot) {
1137 //Same server, lets see by id
1138 $dbcourse = get_record('course','id',$parent->id);
1139 } else {
1140 //Different server, lets see by idnumber and shortname, and only ONE record
1141 $dbcount = count_records('course','idnumber',$parent->idnumber,'shortname',$parent->shortname);
1142 if ($dbcount == 1) {
1143 $dbcourse = get_record('course','idnumber',$parent->idnumber,'shortname',$parent->shortname);
1146 //If parent course has been found, insert data if it is a metacourse
1147 if ($dbcourse) {
1148 if ($dbcourse->metacourse) {
1149 $dbmetacourse->parent_course = $dbcourse->id;
1150 $dbmetacourse->child_course = $restore->course_id;
1151 $status = insert_record ('course_meta',$dbmetacourse);
1152 //Now, recreate student enrolments in parent course
1153 sync_metacourse($dbcourse->id);
1154 } else {
1155 //Parent course isn't metacourse, notice!
1156 if (!defined('RESTORE_SILENTLY')) {
1157 echo '<ul><li>'.get_string ('parentcoursenotmetacourse').' ('.$parent->id.'/'.$parent->idnumber.'/'.$parent->shortname.')</li></ul>';
1160 } else {
1161 //Parent course not found, notice!
1162 if (!defined('RESTORE_SILENTLY')) {
1163 echo '<ul><li>'.get_string ('parentcoursenotfound').' ('.$parent->id.'/'.$parent->idnumber.'/'.$parent->shortname.')</li></ul>';
1170 return $status;
1173 //This function creates all the gradebook data from xml, notifying
1174 //about each incidence
1175 function restore_create_gradebook($restore,$xml_file) {
1177 global $CFG, $db, $SESSION;
1179 $status = true;
1180 //Check it exists
1181 if (!file_exists($xml_file)) {
1182 return false;
1185 // Get info from xml
1186 // info will contain the number of record to process
1187 $info = restore_read_xml_gradebook($restore, $xml_file);
1189 // If we have info, then process
1190 if ($info <= 0) {
1191 return $status;
1194 // Count how many we have
1195 $categoriescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_categories');
1196 $itemscount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_items');
1197 $outcomecount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_outcomes');
1198 $outcomescoursescount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_outcomes_courses');
1199 $gchcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_categories_history');
1200 $gghcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_grades_history');
1201 $gihcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_items_history');
1202 $gohcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_outcomes_history');
1204 // we need to know if all grade items that were backed up are being restored
1205 // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
1206 // i.e. the aggregated grades of that category
1208 $restoreall = true; // set to false if any grade_item is not selected/restored
1210 if ($recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'", "old_id", "old_id")) {
1211 foreach ($recs as $rec) {
1213 if ($data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id)) {
1215 $info = $data->info;
1216 // do not restore if this grade_item is a mod, and
1217 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1220 if ($itemtype == 'mod') {
1222 $iteminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1223 $itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1224 if (!restore_userdata_selected($restore, $itemmodule, $iteminstance)) {
1225 // module instance not selected when restored using granular
1226 // we are not restoring all grade items, set flag to false
1227 // so that we do not process grade categories and related grade items/grades
1228 $restoreall = false;
1229 break;
1236 // return if nothing to restore
1237 if (!$itemscount && !$categoriescount && !$outcomecount) {
1238 return $status;
1241 // Start ul
1242 if (!defined('RESTORE_SILENTLY')) {
1243 echo '<ul>';
1246 // fetch the course grade item
1248 require_once($CFG->libdir.'/grade/grade_item.php');
1249 require_once($CFG->libdir.'/grade/grade_category.php');
1250 require_once($CFG->libdir.'/gradelib.php');
1251 $courseitem = grade_item::fetch_course_item($restore->course_id);
1252 $coursecategory = grade_category::fetch_course_category($restore->course_id);
1254 // Number of records to get in every chunk
1255 $recordset_size = 2;
1256 // Flag to mark if we must continue
1257 $continue = true;
1259 // Process categories
1260 if ($categoriescount && $continue && $restoreall) {
1261 if (!defined('RESTORE_SILENTLY')) {
1262 echo '<li>'.get_string('gradecategories','grades').'</li>';
1264 $counter = 0;
1265 while ($counter < $categoriescount) {
1266 // Fetch recordset_size records in each iteration
1267 $recs = get_records_select("backup_ids","table_name = 'grade_categories' AND backup_code = '$restore->backup_unique_code'",
1268 "old_id",
1269 "old_id",
1270 $counter,
1271 $recordset_size);
1272 if ($recs) {
1273 foreach ($recs as $rec) {
1274 // Get the full record from backup_ids
1275 $data = backup_getid($restore->backup_unique_code,'grade_categories',$rec->old_id);
1276 if ($data) {
1277 // Now get completed xmlized object
1278 $info = $data->info;
1279 //traverse_xmlize($info); //Debug
1280 //print_object ($GLOBALS['traverse_array']); //Debug
1281 //$GLOBALS['traverse_array']=""; //Debug
1282 //Now build the GRADE_PREFERENCES record structure
1284 $dbrec->courseid = $restore->course_id;
1285 // categories are not backed up during import.
1286 // however, depth 1 categories needs to be skipped during restore into exisiting course
1288 // get the new grade category parent
1290 //if (!empty($info['GRADE_CATEGORY']['#']['PARENT']['0']['#']) && $info['GRADE_CATEGORY']['#']['PARENT']['0']['#'] != '$@NULL@$') {
1292 $parent = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_CATEGORY']['#']['PARENT']['0']['#']));
1293 if (isset($parent->new_id)) {
1294 $dbrec->parent = $parent->new_id;
1295 } else {
1296 // orphans should get adopted by course category
1297 $dbrec->parent = $coursecategory->id;
1301 $dbrec->fullname = backup_todb($info['GRADE_CATEGORY']['#']['FULLNAME']['0']['#']);
1302 $dbrec->aggregation = backup_todb($info['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#']);
1303 $dbrec->keephigh = backup_todb($info['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#']);
1304 $dbrec->droplow = backup_todb($info['GRADE_CATEGORY']['#']['DROPLOW']['0']['#']);
1305 $dbrec->aggregateoutcomes = backup_todb($info['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#']);
1307 //Structure is equal to db, insert record
1308 //if the fullname doesn't exist
1309 if (!$prerec = get_record('grade_categories','courseid',$dbrec->courseid,'fullname',$dbrec->fullname)) {
1310 $newid = insert_record('grade_categories',$dbrec);
1311 $status = backup_putid($restore->backup_unique_code,'grade_categories',$rec->old_id,$newid);
1312 // update this record so we can put in the right paths
1313 // this can only be done after we got the new id
1314 $dbrec->id = $newid;
1315 include_once($CFG->dirroot.'/lib/grade/grade_category.php');
1316 // rebuild the path, we need only parents info
1317 // the order of restoring should ensure that the parent and grandparent(s)
1318 // are already restored
1319 $dbrec->path = grade_category::build_path($dbrec);
1320 // this is not needed in the xml because
1321 // given this parent and grandparent(s) we can recalculate the depth
1322 $dbrec->depth = substr_count($dbrec->path, '/');
1323 update_record('grade_categories', $dbrec);
1324 } else {
1325 // if fullname already exists, we should keep the current grade category
1326 $status = backup_putid($restore->backup_unique_code,'grade_categories',$rec->old_id,$rec->oldid);
1329 //Increment counters
1330 $counter++;
1331 //Do some output
1332 if ($counter % 1 == 0) {
1333 if (!defined('RESTORE_SILENTLY')) {
1334 echo ".";
1335 if ($counter % 20 == 0) {
1336 echo "<br />";
1339 backup_flush(300);
1346 // process outcomes
1347 if ($outcomecount && $continue) {
1348 if (!defined('RESTORE_SILENTLY')) {
1349 echo '<li>'.get_string('gradeoutcomes','grades').'</li>';
1351 $counter = 0;
1352 while ($counter < $outcomecount) {
1353 //Fetch recordset_size records in each iteration
1354 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes' AND backup_code = '$restore->backup_unique_code'",
1355 "old_id",
1356 "old_id",
1357 $counter,
1358 $recordset_size);
1359 if ($recs) {
1360 foreach ($recs as $rec) {
1361 //Get the full record from backup_ids
1362 $data = backup_getid($restore->backup_unique_code,'grade_outcomes',$rec->old_id);
1363 if ($data) {
1364 //Now get completed xmlized object
1365 $info = $data->info;
1366 //traverse_xmlize($info); //Debug
1367 //print_object ($GLOBALS['traverse_array']); //Debug
1368 //$GLOBALS['traverse_array']=""; //Debug
1369 //Now build the GRADE_PREFERENCES record structure
1370 if ($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#']) {
1371 $dbrec->courseid = $restore->course_id;
1372 } else {
1373 $dbrec->courseid = NULL;
1375 $dbrec->shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']);
1376 $dbrec->fullname = backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#']);
1378 if ($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#']) {
1379 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#']));
1380 $dbrec->scaleid = $scale->new_id;
1383 $modifier = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#']));
1384 $dbrec->usermodified = $modifier->new_id;
1386 // Structure is equal to db, insert record
1387 // If the shortname doesn't exist
1389 if (empty($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#'])) {
1390 $prerec = get_record_sql("SELECT * FROM {$CFG->prefix}grade_outcomes
1391 WHERE courseid IS NULL
1392 AND shortname = '$dbrec->shortname'");
1393 } else {
1394 $prerec = get_record('grade_outcomes','courseid',$restore->course_id,'shortname',$dbrec->shortname);
1397 if (!$prerec) {
1398 $newid = insert_record('grade_outcomes',$dbrec);
1399 } else {
1400 $newid = $prerec->id;
1403 if ($newid) {
1404 backup_putid($restore->backup_unique_code,"grade_outcomes", $rec->old_id, $newid);
1407 //Increment counters
1408 $counter++;
1409 //Do some output
1410 if ($counter % 1 == 0) {
1411 if (!defined('RESTORE_SILENTLY')) {
1412 echo ".";
1413 if ($counter % 20 == 0) {
1414 echo "<br />";
1417 backup_flush(300);
1424 // process outcomescourses
1425 if ($outcomescoursescount && $continue) {
1426 if (!defined('RESTORE_SILENTLY')) {
1427 echo '<li>'.get_string('gradeoutcomescourses','grades').'</li>';
1429 $counter = 0;
1430 while ($counter < $outcomescoursescount) {
1431 //Fetch recordset_size records in each iteration
1432 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes_courses' AND backup_code = '$restore->backup_unique_code'",
1433 "old_id",
1434 "old_id",
1435 $counter,
1436 $recordset_size);
1437 if ($recs) {
1438 foreach ($recs as $rec) {
1439 //Get the full record from backup_ids
1440 $data = backup_getid($restore->backup_unique_code,'grade_outcomes_courses',$rec->old_id);
1441 if ($data) {
1442 //Now get completed xmlized object
1443 $info = $data->info;
1444 //traverse_xmlize($info); //Debug
1445 //print_object ($GLOBALS['traverse_array']); //Debug
1446 //$GLOBALS['traverse_array']=""; //Debug
1448 $oldoutcomesid = backup_todb($info['GRADE_OUTCOMES_COURSE']['#']['OUTCOMEID']['0']['#']);
1449 $newoutcome = backup_getid($restore->backup_unique_code,"grade_outcomes",$oldoutcomesid);
1450 unset($dbrec);
1451 $dbrec->courseid = $restore->course_id;
1452 $dbrec->outcomeid = $newoutcome->new_id;
1453 insert_record('grade_outcomes_courses', $dbrec);
1455 //Increment counters
1456 $counter++;
1457 //Do some output
1458 if ($counter % 1 == 0) {
1459 if (!defined('RESTORE_SILENTLY')) {
1460 echo ".";
1461 if ($counter % 20 == 0) {
1462 echo "<br />";
1465 backup_flush(300);
1472 // Process grade items (grade_grade)
1473 if ($itemscount && $continue) {
1474 if (!defined('RESTORE_SILENTLY')) {
1475 echo '<li>'.get_string('gradeitems','grades').'</li>';
1477 $counter = 0;
1478 $counteritems = 0;
1479 while ($counteritems < $itemscount) {
1481 //Fetch recordset_size records in each iteration
1482 $recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'",
1483 "old_id",
1484 "old_id",
1485 $counteritems,
1486 $recordset_size);
1488 if ($recs) {
1489 foreach ($recs as $rec) {
1490 //Get the full record from backup_ids
1491 $data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id);
1492 if ($data) {
1493 //Now get completed xmlized object
1494 $info = $data->info;
1495 //traverse_xmlize($info); //Debug
1496 //print_object ($GLOBALS['traverse_array']); //Debug
1497 //$GLOBALS['traverse_array']=""; //Debug
1499 $dbrec->courseid = $restore->course_id;
1501 if (isset($SESSION->restore->importing)) {
1502 // if we are importing, points all grade_items to the course category
1503 $coursecat = get_record('grade_categories', 'courseid', $restore->course_id, 'depth', 1);
1504 $dbrec->categoryid = $coursecat->id;
1505 } else if (!empty($info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']) && $info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']!='$@NULL@$') {
1506 $category = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']));
1507 if ($category->new_id) {
1508 $dbrec->categoryid = $category->new_id;
1509 } else {
1510 // this could be restoring into existing course, and grade item points to the old course grade item (category)
1511 // which was never imported. In this case we just point them to the new course item
1512 $dbrec->categoryid = $coursecategory->id;
1516 $dbrec->itemname = backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#']);
1517 $dbrec->itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1518 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1519 /// this needs to point to either the new mod id
1520 /// or the category id
1521 $iteminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1522 // do not restore if this grade_item is a mod, and
1523 if ($dbrec->itemtype == 'mod') {
1525 // iteminstance should point to new mod
1527 $mod = backup_getid($restore->backup_unique_code,$dbrec->itemmodule, $iteminstance);
1528 $dbrec->iteminstance = $mod->new_id;
1530 } else if ($dbrec->itemtype == 'category') {
1531 // the item instance should point to the new grade category
1533 // only proceed if we are restoring all grade items
1534 // need to skip for imports
1535 if ($restoreall && !isset($SESSION->restore->importing)) {
1536 $category = backup_getid($restore->backup_unique_code,'grade_categories', $iteminstance);
1537 $dbrec->iteminstance = $category->new_id;
1538 } else {
1539 // otherwise we can safely ignore this grade item and subsequent
1540 // grade_raws, grade_finals etc
1541 $counteritems++;
1542 continue;
1544 } elseif ($dbrec->itemtype == 'course') { // We don't restore course type to avoid duplicate course items
1546 if ($restoreall && !isset($SESSION->restore->importing) && $restore->restoreto == 2) {
1547 // TODO any special code needed here to restore course item without duplicating it?
1548 // find the course category with depth 1, and course id = current course id
1549 // this would have been already restored
1550 $counteritems++;
1551 continue;
1552 } else {
1553 $counteritems++;
1554 continue;
1558 $dbrec->itemnumber = backup_todb($info['GRADE_ITEM']['#']['ITEMNUMBER']['0']['#']);
1559 $dbrec->iteminfo = backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#']);
1560 $dbrec->idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#']);
1561 $dbrec->calculation = backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#']);
1562 $dbrec->grademax = backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#']);
1563 $dbrec->grademin = backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#']);
1564 /// needs to be restored first
1566 if (backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#'])) {
1567 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#']));
1568 $dbrec->scaleid = $scale->new_id;
1571 /// needs to be restored first
1572 $dbrec->outcomeid = backup_getid($restore->backup_unique_code,"grade_outcomes",backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#']));
1574 $dbrec->gradepass = backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#']);
1575 $dbrec->multfactor = backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#']);
1576 $dbrec->plusfactor = backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#']);
1577 $dbrec->hidden = backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#']);
1578 $dbrec->locked = backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#']);
1579 $dbrec->locktime = backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#']);
1580 $dbrec->needsupdate = backup_todb($info['GRADE_ITEM']['#']['NEEDSUPDATE']['0']['#']);
1581 $dbrec->timecreated = backup_todb($info['GRADE_ITEM']['#']['TIMECREATED']['0']['#']);
1582 $dbrec->timemodified = backup_todb($info['GRADE_ITEM']['#']['TIMEMODIFIED']['0']['#']);
1584 // get the current sortorder, add 1 to it and use that
1585 if ($lastitem = get_record_sql("SELECT sortorder, id FROM {$CFG->prefix}grade_items
1586 WHERE courseid = $restore->course_id
1587 ORDER BY sortorder DESC ", true)) {
1589 // we just need the first one
1590 $dbrec->sortorder = $lastitem->sortorder + 1;
1591 } else {
1592 // this is the first grade_item
1593 $dbrec->sortorder = 1;
1595 // always insert, since modules restored to existing courses are always inserted
1596 $itemid = insert_record('grade_items',$dbrec);
1597 if ($itemid) {
1598 backup_putid($restore->backup_unique_code,'grade_items', backup_todb($info['GRADE_ITEM']['#']['ID']['0']['#']), $itemid);
1601 // no need to restore grades if user data is not selected
1602 if ($dbrec->itemtype == 'mod' && !restore_userdata_selected($restore, $dbrec->itemmodule, $iteminstance)) {
1603 // module instance not selected when restored using granular
1604 // skip this item
1605 $counteritems++;
1606 continue;
1609 /// now, restore grade_grades
1610 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']) && ($grades = $info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'])) {
1611 //Iterate over items
1612 for($i = 0; $i < sizeof($grades); $i++) {
1613 $ite_info = $grades[$i];
1614 //traverse_xmlize($ite_info);
1615 //Debug
1616 //print_object ($GLOBALS['traverse_array']); //Debug
1617 //$GLOBALS['traverse_array']=""; //Debug
1618 //Now build the GRADE_ITEM record structure
1619 $grade = new object();
1620 $grade->itemid = $itemid;
1621 $user = backup_getid($restore->backup_unique_code,"user", backup_todb($ite_info['#']['USERID']['0']['#']));
1622 $grade->userid = $user->new_id;
1623 $grade->rawgrade = backup_todb($ite_info['#']['RAWGRADE']['0']['#']);
1624 $grade->rawgrademax = backup_todb($ite_info['#']['RAWGRADEMAX']['0']['#']);
1625 $grade->rawgrademin = backup_todb($ite_info['#']['RAWGRADEMIN']['0']['#']);
1626 // need to find scaleid
1627 if (backup_todb($ite_info['#']['RAWSCALEID']['0']['#'])) {
1628 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($ite_info['#']['RAWSCALEID']['0']['#']));
1629 $grade->rawscaleid = $scale->new_id;
1631 $grade->finalgrade = backup_todb($ite_info['#']['FINALGRADE']['0']['#']);
1632 $grade->hidden = backup_todb($ite_info['#']['HIDDEN']['0']['#']);
1633 $grade->locked = backup_todb($ite_info['#']['LOCKED']['0']['#']);
1634 $grade->locktime = backup_todb($ite_info['#']['LOCKTIME']['0']['#']);
1635 $grade->exported = backup_todb($ite_info['#']['EXPORTED']['0']['#']);
1636 $grade->overridden = backup_todb($ite_info['#']['OVERRIDDEN']['0']['#']);
1637 $grade->excluded = backup_todb($ite_info['#']['EXCLUDED']['0']['#']);
1638 $grade->feedback = backup_todb($ite_info['#']['FEEDBACK']['0']['#']);
1639 $grade->feedbackformat = backup_todb($ite_info['#']['FEEDBACKFORMAT']['0']['#']);
1640 $grade->information = backup_todb($ite_info['#']['INFORMATION']['0']['#']);
1641 $grade->informationformat = backup_todb($ite_info['#']['INFORMATIONFORMAT']['0']['#']);
1643 $newid = insert_record('grade_grades', $grade);
1645 if ($newid) {
1646 backup_putid($restore->backup_unique_code,"grade_grades", backup_todb($ite_info['#']['ID']['0']['#']), $newid);
1648 $counter++;
1649 if ($counter % 20 == 0) {
1650 if (!defined('RESTORE_SILENTLY')) {
1651 echo ".";
1652 if ($counter % 400 == 0) {
1653 echo "<br />";
1656 backup_flush(300);
1661 $counteritems++; // increment item count
1668 // process histories
1669 if ($gchcount && $continue && !isset($SESSION->restore->importing) && $restore->restore_gradebook_history) {
1670 if (!defined('RESTORE_SILENTLY')) {
1671 echo '<li>'.get_string('gradecategoryhistory','grades').'</li>';
1673 $counter = 0;
1674 while ($counter < $gchcount) {
1675 //Fetch recordset_size records in each iteration
1676 $recs = get_records_select("backup_ids","table_name = 'grade_categories_history' AND backup_code = '$restore->backup_unique_code'",
1677 "old_id",
1678 "old_id",
1679 $counter,
1680 $recordset_size);
1681 if ($recs) {
1682 foreach ($recs as $rec) {
1683 //Get the full record from backup_ids
1684 $data = backup_getid($restore->backup_unique_code,'grade_categories_history',$rec->old_id);
1685 if ($data) {
1686 //Now get completed xmlized object
1687 $info = $data->info;
1688 //traverse_xmlize($info); //Debug
1689 //print_object ($GLOBALS['traverse_array']); //Debug
1690 //$GLOBALS['traverse_array']=""; //Debug
1692 $oldobj = backup_getid($restore->backup_unique_code,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['OLDID']['0']['#']));
1693 if (empty($oldobj->new_id)) {
1694 // if the old object is not being restored, can't restoring its history
1695 $counter++;
1696 continue;
1698 $dbrec->oldid = $oldobj->new_id;
1699 $dbrec->action = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['ACTION']['0']['#']);
1700 $dbrec->source = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['SOURCE']['0']['#']);
1701 $dbrec->timemodified = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1703 // loggeduser might not be restored, e.g. admin
1704 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1705 $dbrec->loggeduser = $oldobj->new_id;
1708 // this item might not have a parent at all, do not skip it if no parent is specified
1709 if (backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#'])) {
1710 $oldobj = backup_getid($restore->backup_unique_code,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#']));
1711 if (empty($oldobj->new_id)) {
1712 // if the parent category not restored
1713 $counter++;
1714 continue;
1717 $dbrec->parent = $oldobj->new_id;
1718 $dbrec->depth = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DEPTH']['0']['#']);
1719 // path needs to be rebuilt
1720 if ($path = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PATH']['0']['#'])) {
1721 // to preserve the path and make it work, we need to replace the categories one by one
1722 // we first get the list of categories in current path
1723 if ($paths = explode("/", $path)) {
1724 $newpath = '';
1725 foreach ($paths as $catid) {
1726 if ($catid) {
1727 // find the new corresponding path
1728 $oldpath = backup_getid($restore->backup_unique_code,"grade_categories", $catid);
1729 $newpath .= "/$oldpath->new_id";
1732 $dbrec->path = $newpath;
1735 $dbrec->fullname = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['FULLNAME']['0']['#']);
1736 $dbrec->aggregation = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGRETGATION']['0']['#']);
1737 $dbrec->keephigh = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['KEEPHIGH']['0']['#']);
1738 $dbrec->droplow = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DROPLOW']['0']['#']);
1739 $dbrec->courseid = $restore->course_id;
1740 insert_record('grade_categories_history', $dbrec);
1741 unset($dbrec);
1744 //Increment counters
1745 $counter++;
1746 //Do some output
1747 if ($counter % 1 == 0) {
1748 if (!defined('RESTORE_SILENTLY')) {
1749 echo ".";
1750 if ($counter % 20 == 0) {
1751 echo "<br />";
1754 backup_flush(300);
1761 // process histories
1762 if ($gghcount && $continue && !isset($SESSION->restore->importing) && $restore->restore_gradebook_history) {
1763 if (!defined('RESTORE_SILENTLY')) {
1764 echo '<li>'.get_string('gradegradeshistory','grades').'</li>';
1766 $counter = 0;
1767 while ($counter < $gghcount) {
1768 //Fetch recordset_size records in each iteration
1769 $recs = get_records_select("backup_ids","table_name = 'grade_grades_history' AND backup_code = '$restore->backup_unique_code'",
1770 "old_id",
1771 "old_id",
1772 $counter,
1773 $recordset_size);
1774 if ($recs) {
1775 foreach ($recs as $rec) {
1776 //Get the full record from backup_ids
1777 $data = backup_getid($restore->backup_unique_code,'grade_grades_history',$rec->old_id);
1778 if ($data) {
1779 //Now get completed xmlized object
1780 $info = $data->info;
1781 //traverse_xmlize($info); //Debug
1782 //print_object ($GLOBALS['traverse_array']); //Debug
1783 //$GLOBALS['traverse_array']=""; //Debug
1785 $oldobj = backup_getid($restore->backup_unique_code,"grade_grades", backup_todb($info['GRADE_GRADES_HISTORY']['#']['OLDID']['0']['#']));
1786 if (empty($oldobj->new_id)) {
1787 // if the old object is not being restored, can't restoring its history
1788 $counter++;
1789 continue;
1791 $dbrec->oldid = $oldobj->new_id;
1792 $dbrec->action = backup_todb($info['GRADE_GRADES_HISTORY']['#']['ACTION']['0']['#']);
1793 $dbrec->source = backup_todb($info['GRADE_GRADES_HISTORY']['#']['SOURCE']['0']['#']);
1794 $dbrec->timemodified = backup_todb($info['GRADE_GRADES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1795 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1796 $dbrec->loggeduser = $oldobj->new_id;
1798 $oldobj = backup_getid($restore->backup_unique_code,"grade_items", backup_todb($info['GRADE_GRADES_HISTORY']['#']['ITEMID']['0']['#']));
1799 $dbrec->itemid = $oldobj->new_id;
1800 if (empty($dbrec->itemid)) {
1801 $counter++;
1802 continue; // grade item not being restored
1804 $oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERID']['0']['#']));
1805 $dbrec->userid = $oldobj->new_id;
1806 $dbrec->rawgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADE']['0']['#']);
1807 $dbrec->rawgrademax = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMAX']['0']['#']);
1808 $dbrec->rawgrademin = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMIN']['0']['#']);
1809 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERMODIFIED']['0']['#']))) {
1810 $dbrec->usermodified = $oldobj->new_id;
1812 $dbrec->finalgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['FINALGRADE']['0']['#']);
1813 $dbrec->hidden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['HIDDEN']['0']['#']);
1814 $dbrec->locked = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKED']['0']['#']);
1815 $dbrec->locktime = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKTIME']['0']['#']);
1816 $dbrec->exported = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXPORTED']['0']['#']);
1817 $dbrec->overridden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['OVERRIDDEN']['0']['#']);
1818 $dbrec->excluded = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXCLUDED']['0']['#']);
1819 $dbrec->feedback = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACK']['0']['#']);
1820 $dbrec->feedbackformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACKFORMAT']['0']['#']);
1821 $dbrec->information = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATION']['0']['#']);
1822 $dbrec->informationformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATIONFORMAT']['0']['#']);
1824 insert_record('grade_grades_history', $dbrec);
1825 unset($dbrec);
1828 //Increment counters
1829 $counter++;
1830 //Do some output
1831 if ($counter % 1 == 0) {
1832 if (!defined('RESTORE_SILENTLY')) {
1833 echo ".";
1834 if ($counter % 20 == 0) {
1835 echo "<br />";
1838 backup_flush(300);
1845 // process histories
1847 if ($gihcount && $continue && !isset($SESSION->restore->importing) && $restore->restore_gradebook_history) {
1848 if (!defined('RESTORE_SILENTLY')) {
1849 echo '<li>'.get_string('gradeitemshistory','grades').'</li>';
1851 $counter = 0;
1852 while ($counter < $gihcount) {
1853 //Fetch recordset_size records in each iteration
1854 $recs = get_records_select("backup_ids","table_name = 'grade_items_history' AND backup_code = '$restore->backup_unique_code'",
1855 "old_id",
1856 "old_id",
1857 $counter,
1858 $recordset_size);
1859 if ($recs) {
1860 foreach ($recs as $rec) {
1861 //Get the full record from backup_ids
1862 $data = backup_getid($restore->backup_unique_code,'grade_items_history',$rec->old_id);
1863 if ($data) {
1864 //Now get completed xmlized object
1865 $info = $data->info;
1866 //traverse_xmlize($info); //Debug
1867 //print_object ($GLOBALS['traverse_array']); //Debug
1868 //$GLOBALS['traverse_array']=""; //Debug
1871 $oldobj = backup_getid($restore->backup_unique_code,"grade_items", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OLDID']['0']['#']));
1872 if (empty($oldobj->new_id)) {
1873 // if the old object is not being restored, can't restoring its history
1874 $counter++;
1875 continue;
1877 $dbrec->oldid = $oldobj->new_id;
1878 $dbrec->action = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ACTION']['0']['#']);
1879 $dbrec->source = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SOURCE']['0']['#']);
1880 $dbrec->timemodified = backup_todb($info['GRADE_ITEM_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1881 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1882 $dbrec->loggeduser = $oldobj->new_id;
1884 $oldobj = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_ITEM_HISTORY']['#']['CATEGORYID']['0']['#']));
1885 $oldobj->categoryid = $category->new_id;
1886 if (empty($oldobj->categoryid)) {
1887 $counter++;
1888 continue; // category not restored
1891 $dbrec->itemname= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNAME']['0']['#']);
1892 $dbrec->itemtype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMTYPE']['0']['#']);
1893 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMMODULE']['0']['#']);
1895 // code from grade_items restore
1896 $iteminstance = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINSTANCE']['0']['#']);
1897 // do not restore if this grade_item is a mod, and
1898 if ($dbrec->itemtype == 'mod') {
1900 if (!restore_userdata_selected($restore, $dbrec->itemmodule, $iteminstance)) {
1901 // module instance not selected when restored using granular
1902 // skip this item
1903 $counter++;
1904 continue;
1907 // iteminstance should point to new mod
1909 $mod = backup_getid($restore->backup_unique_code,$dbrec->itemmodule, $iteminstance);
1910 $dbrec->iteminstance = $mod->new_id;
1912 } else if ($dbrec->itemtype == 'category') {
1913 // the item instance should point to the new grade category
1915 // only proceed if we are restoring all grade items
1916 if ($restoreall) {
1917 $category = backup_getid($restore->backup_unique_code,'grade_categories', $iteminstance);
1918 $dbrec->iteminstance = $category->new_id;
1919 } else {
1920 // otherwise we can safely ignore this grade item and subsequent
1921 // grade_raws, grade_finals etc
1922 continue;
1924 } elseif ($dbrec->itemtype == 'course') { // We don't restore course type to avoid duplicate course items
1925 if ($restoreall) {
1926 // TODO any special code needed here to restore course item without duplicating it?
1927 // find the course category with depth 1, and course id = current course id
1928 // this would have been already restored
1930 $cat = get_record('grade_categories', 'depth', 1, 'courseid', $restore->course_id);
1931 $dbrec->iteminstance = $cat->id;
1933 } else {
1934 $counter++;
1935 continue;
1939 $dbrec->itemnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNUMBER']['0']['#']);
1940 $dbrec->iteminfo = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINFO']['0']['#']);
1941 $dbrec->idnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['IDNUMBER']['0']['#']);
1942 $dbrec->calculation = backup_todb($info['GRADE_ITEM_HISTORY']['#']['CALCULATION']['0']['#']);
1943 $dbrec->gradetype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADETYPE']['0']['#']);
1944 $dbrec->grademax = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMAX']['0']['#']);
1945 $dbrec->grademin = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMIN']['0']['#']);
1946 if ($oldobj = backup_getid($restore->backup_unique_code,"scale", backup_todb($info['GRADE_ITEM_HISTORY']['#']['SCALEID']['0']['#']))) {
1947 // scaleid is optional
1948 $dbrec->scaleid = $oldobj->new_id;
1950 if ($oldobj = backup_getid($restore->backup_unique_code,"grade_outcomes", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OUTCOMEID']['0']['#']))) {
1951 // outcome is optional
1952 $dbrec->outcomeid = $oldobj->new_id;
1954 $dbrec->gradepass = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEPASS']['0']['#']);
1955 $dbrec->multfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['MULTFACTOR']['0']['#']);
1956 $dbrec->plusfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['PLUSFACTOR']['0']['#']);
1957 $dbrec->aggregationcoef = backup_todb($info['GRADE_ITEM_HISTORY']['#']['AGGREGATIONCOEF']['0']['#']);
1958 $dbrec->sortorder = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SORTORDER']['0']['#']);
1959 $dbrec->hidden = backup_todb($info['GRADE_ITEM_HISTORY']['#']['HIDDEN']['0']['#']);
1960 $dbrec->locked = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKED']['0']['#']);
1961 $dbrec->locktime = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKTIME']['0']['#']);
1962 $dbrec->needsupdate = backup_todb($info['GRADE_ITEM_HISTORY']['#']['NEEDSUPDATE']['0']['#']);
1964 insert_record('grade_items_history', $dbrec);
1965 unset($dbrec);
1968 //Increment counters
1969 $counter++;
1970 //Do some output
1971 if ($counter % 1 == 0) {
1972 if (!defined('RESTORE_SILENTLY')) {
1973 echo ".";
1974 if ($counter % 20 == 0) {
1975 echo "<br />";
1978 backup_flush(300);
1985 // process histories
1986 if ($gohcount && $continue && !isset($SESSION->restore->importing) && $restore->restore_gradebook_history) {
1987 if (!defined('RESTORE_SILENTLY')) {
1988 echo '<li>'.get_string('gradeoutcomeshistory','grades').'</li>';
1990 $counter = 0;
1991 while ($counter < $gohcount) {
1992 //Fetch recordset_size records in each iteration
1993 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes_history' AND backup_code = '$restore->backup_unique_code'",
1994 "old_id",
1995 "old_id",
1996 $counter,
1997 $recordset_size);
1998 if ($recs) {
1999 foreach ($recs as $rec) {
2000 //Get the full record from backup_ids
2001 $data = backup_getid($restore->backup_unique_code,'grade_outcomes_history',$rec->old_id);
2002 if ($data) {
2003 //Now get completed xmlized object
2004 $info = $data->info;
2005 //traverse_xmlize($info); //Debug
2006 //print_object ($GLOBALS['traverse_array']); //Debug
2007 //$GLOBALS['traverse_array']=""; //Debug
2009 $oldobj = backup_getid($restore->backup_unique_code,"grade_outcomes", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['OLDID']['0']['#']));
2010 if (empty($oldobj->new_id)) {
2011 // if the old object is not being restored, can't restoring its history
2012 $counter++;
2013 continue;
2015 $dbrec->oldid = $oldobj->new_id;
2016 $dbrec->action = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['ACTION']['0']['#']);
2017 $dbrec->source = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SOURCE']['0']['#']);
2018 $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2019 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2020 $dbrec->loggeduser = $oldobj->new_id;
2022 $dbrec->shortname = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SHORTNAME']['0']['#']);
2023 $dbrec->fullname= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['FULLNAME']['0']['#']);
2024 $oldobj = backup_getid($restore->backup_unique_code,"scale", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SCALEID']['0']['#']));
2025 $dbrec->scaleid = $oldobj->new_id;
2026 $dbrec->description = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['DESCRIPTION']['0']['#']);
2028 insert_record('grade_outcomes_history', $dbrec);
2029 unset($dbrec);
2032 //Increment counters
2033 $counter++;
2034 //Do some output
2035 if ($counter % 1 == 0) {
2036 if (!defined('RESTORE_SILENTLY')) {
2037 echo ".";
2038 if ($counter % 20 == 0) {
2039 echo "<br />";
2042 backup_flush(300);
2049 if (!defined('RESTORE_SILENTLY')) {
2050 //End ul
2051 echo '</ul>';
2053 return $status;
2056 //This function creates all the user, user_students, user_teachers
2057 //user_course_creators and user_admins from xml
2058 function restore_create_users($restore,$xml_file) {
2060 global $CFG, $db;
2062 $status = true;
2063 //Check it exists
2064 if (!file_exists($xml_file)) {
2065 $status = false;
2067 //Get info from xml
2068 if ($status) {
2069 //info will contain the old_id of every user
2070 //in backup_ids->info will be the real info (serialized)
2071 $info = restore_read_xml_users($restore,$xml_file);
2074 //Now, get evey user_id from $info and user data from $backup_ids
2075 //and create the necessary records (users, user_students, user_teachers
2076 //user_course_creators and user_admins
2077 if (!empty($info->users)) {
2078 // Grab mnethosts keyed by wwwroot, to map to id
2079 $mnethosts = get_records('mnet_host', '', '',
2080 'wwwroot', 'wwwroot, id');
2082 $languages = get_list_of_languages();
2084 foreach ($info->users as $userid) {
2085 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
2086 $user = $rec->info;
2088 //Now, recode some languages (Moodle 1.5)
2089 if ($user->lang == 'ma_nt') {
2090 $user->lang = 'mi_nt';
2094 //If language does not exist here - use site default
2095 if (!array_key_exists($user->lang, $languages)) {
2096 $user->lang = $CFG->lang;
2099 //Check if it's admin and coursecreator
2100 $is_admin = !empty($user->roles['admin']);
2101 $is_coursecreator = !empty($user->roles['coursecreator']);
2103 //Check if it's teacher and student
2104 $is_teacher = !empty($user->roles['teacher']);
2105 $is_student = !empty($user->roles['student']);
2107 //Check if it's needed
2108 $is_needed = !empty($user->roles['needed']);
2110 //Calculate if it is a course user
2111 //Has role teacher or student or needed
2112 $is_course_user = ($is_teacher or $is_student or $is_needed);
2114 //Calculate mnethostid
2115 if (empty($user->mnethosturl) || $user->mnethosturl===$CFG->wwwroot) {
2116 $user->mnethostid = $CFG->mnet_localhost_id;
2117 } else {
2118 // fast url-to-id lookups
2119 if (isset($mnethosts[$user->mnethosturl])) {
2120 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
2121 } else {
2122 // should not happen, as we check in restore_chech.php
2123 // but handle the error if it does
2124 error("This backup file contains external Moodle Network Hosts that are not configured locally.");
2127 unset($user->mnethosturl);
2129 //To store new ids created
2130 $newid=null;
2131 //check if it exists (by username) and get its id
2132 $user_exists = true;
2133 $user_data = get_record("user","username",addslashes($user->username),
2134 'mnethostid', $user->mnethostid);
2135 if (!$user_data) {
2136 $user_exists = false;
2137 } else {
2138 $newid = $user_data->id;
2140 //Flags to see if we have to create the user, roles and preferences
2141 $create_user = true;
2142 $create_roles = true;
2143 $create_preferences = true;
2145 //If we are restoring course users and it isn't a course user
2146 if ($restore->users == 1 and !$is_course_user) {
2147 //If only restoring course_users and user isn't a course_user, inform to $backup_ids
2148 $status = backup_putid($restore->backup_unique_code,"user",$userid,null,'notincourse');
2149 $create_user = false;
2150 $create_roles = false;
2151 $create_preferences = false;
2154 if ($user_exists and $create_user) {
2155 //If user exists mark its newid in backup_ids (the same than old)
2156 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,'exists');
2157 $create_user = false;
2160 //Here, if create_user, do it
2161 if ($create_user) {
2162 //Unset the id because it's going to be inserted with a new one
2163 unset ($user->id);
2164 //We addslashes to necessary fields
2165 $user->username = addslashes($user->username);
2166 $user->firstname = addslashes($user->firstname);
2167 $user->lastname = addslashes($user->lastname);
2168 $user->email = addslashes($user->email);
2169 $user->institution = addslashes($user->institution);
2170 $user->department = addslashes($user->department);
2171 $user->address = addslashes($user->address);
2172 $user->city = addslashes($user->city);
2173 $user->url = addslashes($user->url);
2174 $user->description = backup_todb($user->description);
2176 //We need to analyse the AUTH field to recode it:
2177 // - if the field isn't set, we are in a pre 1.4 backup and we'll
2178 // use manual
2180 if (empty($user->auth)) {
2181 if ($CFG->registerauth == 'email') {
2182 $user->auth = 'email';
2183 } else {
2184 $user->auth = 'manual';
2188 //We need to process the POLICYAGREED field to recalculate it:
2189 // - if the destination site is different (by wwwroot) reset it.
2190 // - if the destination site is the same (by wwwroot), leave it unmodified
2192 if ($restore->original_wwwroot != $CFG->wwwroot) {
2193 $user->policyagreed = 0;
2194 } else {
2195 //Nothing to do, we are in the same server
2198 //Check if the theme exists in destination server
2199 $themes = get_list_of_themes();
2200 if (!in_array($user->theme, $themes)) {
2201 $user->theme = '';
2204 //We are going to create the user
2205 //The structure is exactly as we need
2206 $newid = insert_record ("user",$user);
2207 //Put the new id
2208 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,"new");
2211 //Here, if create_roles, do it as necessary
2212 if ($create_roles) {
2213 //Get the newid and current info from backup_ids
2214 $data = backup_getid($restore->backup_unique_code,"user",$userid);
2215 $newid = $data->new_id;
2216 $currinfo = $data->info.",";
2218 //Now, depending of the role, create records in user_studentes and user_teacher
2219 //and/or mark it in backup_ids
2221 if ($is_admin) {
2222 //If the record (user_admins) doesn't exists
2223 //Only put status in backup_ids
2224 $currinfo = $currinfo."admin,";
2225 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2227 if ($is_coursecreator) {
2228 //If the record (user_coursecreators) doesn't exists
2229 //Only put status in backup_ids
2230 $currinfo = $currinfo."coursecreator,";
2231 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2233 if ($is_needed) {
2234 //Only put status in backup_ids
2235 $currinfo = $currinfo."needed,";
2236 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2238 if ($is_teacher) {
2239 //If the record (teacher) doesn't exists
2240 //Put status in backup_ids
2241 $currinfo = $currinfo."teacher,";
2242 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2243 //Set course and user
2244 $user->roles['teacher']->course = $restore->course_id;
2245 $user->roles['teacher']->userid = $newid;
2247 //Need to analyse the enrol field
2248 // - if it isn't set, set it to $CFG->enrol
2249 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2250 // - if we are in the same server (by wwwroot), maintain it unmodified.
2251 if (empty($user->roles['teacher']->enrol)) {
2252 $user->roles['teacher']->enrol = $CFG->enrol;
2253 } else if ($restore->original_wwwroot != $CFG->wwwroot) {
2254 $user->roles['teacher']->enrol = $CFG->enrol;
2255 } else {
2256 //Nothing to do. Leave it unmodified
2259 $rolesmapping = $restore->rolesmapping;
2260 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
2261 if ($user->roles['teacher']->editall) {
2262 role_assign($rolesmapping['defaultteacheredit'],
2263 $newid,
2265 $context->id,
2266 $user->roles['teacher']->timestart,
2267 $user->roles['teacher']->timeend,
2269 $user->roles['teacher']->enrol);
2271 // editting teacher
2272 } else {
2273 // non editting teacher
2274 role_assign($rolesmapping['defaultteacher'],
2275 $newid,
2277 $context->id,
2278 $user->roles['teacher']->timestart,
2279 $user->roles['teacher']->timeend,
2281 $user->roles['teacher']->enrol);
2284 if ($is_student) {
2286 //Put status in backup_ids
2287 $currinfo = $currinfo."student,";
2288 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2289 //Set course and user
2290 $user->roles['student']->course = $restore->course_id;
2291 $user->roles['student']->userid = $newid;
2293 //Need to analyse the enrol field
2294 // - if it isn't set, set it to $CFG->enrol
2295 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2296 // - if we are in the same server (by wwwroot), maintain it unmodified.
2297 if (empty($user->roles['student']->enrol)) {
2298 $user->roles['student']->enrol = $CFG->enrol;
2299 } else if ($restore->original_wwwroot != $CFG->wwwroot) {
2300 $user->roles['student']->enrol = $CFG->enrol;
2301 } else {
2302 //Nothing to do. Leave it unmodified
2304 $rolesmapping = $restore->rolesmapping;
2305 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
2307 role_assign($rolesmapping['defaultstudent'],
2308 $newid,
2310 $context->id,
2311 $user->roles['student']->timestart,
2312 $user->roles['student']->timeend,
2314 $user->roles['student']->enrol);
2317 if (!$is_course_user) {
2318 //If the record (user) doesn't exists
2319 if (!record_exists("user","id",$newid)) {
2320 //Put status in backup_ids
2321 $currinfo = $currinfo."user,";
2322 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2327 //Here, if create_preferences, do it as necessary
2328 if ($create_preferences) {
2329 //echo "Checking for preferences of user ".$user->username."<br />"; //Debug
2330 //Get user new id from backup_ids
2331 $data = backup_getid($restore->backup_unique_code,"user",$userid);
2332 $newid = $data->new_id;
2333 if (isset($user->user_preferences)) {
2334 //echo "Preferences exist in backup file<br />"; //Debug
2335 foreach($user->user_preferences as $user_preference) {
2336 //echo $user_preference->name." = ".$user_preference->value."<br />"; //Debug
2337 //We check if that user_preference exists in DB
2338 if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name)) {
2339 //echo "Creating it<br />"; //Debug
2340 //Prepare the record and insert it
2341 $user_preference->userid = $newid;
2342 $status = insert_record("user_preferences",$user_preference);
2350 return $status;
2353 //This function creates all the structures messages and contacts
2354 function restore_create_messages($restore,$xml_file) {
2356 global $CFG;
2358 $status = true;
2359 //Check it exists
2360 if (!file_exists($xml_file)) {
2361 $status = false;
2363 //Get info from xml
2364 if ($status) {
2365 //info will contain the id and name of every table
2366 //(message, message_read and message_contacts)
2367 //in backup_ids->info will be the real info (serialized)
2368 $info = restore_read_xml_messages($restore,$xml_file);
2370 //If we have info, then process messages & contacts
2371 if ($info > 0) {
2372 //Count how many we have
2373 $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message');
2374 $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_read');
2375 $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_contacts');
2376 if ($unreadcount || $readcount || $contactcount) {
2377 //Start ul
2378 if (!defined('RESTORE_SILENTLY')) {
2379 echo '<ul>';
2381 //Number of records to get in every chunk
2382 $recordset_size = 4;
2384 //Process unread
2385 if ($unreadcount) {
2386 if (!defined('RESTORE_SILENTLY')) {
2387 echo '<li>'.get_string('unreadmessages','message').'</li>';
2389 $counter = 0;
2390 while ($counter < $unreadcount) {
2391 //Fetch recordset_size records in each iteration
2392 $recs = get_records_select("backup_ids","table_name = 'message' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2393 if ($recs) {
2394 foreach ($recs as $rec) {
2395 //Get the full record from backup_ids
2396 $data = backup_getid($restore->backup_unique_code,"message",$rec->old_id);
2397 if ($data) {
2398 //Now get completed xmlized object
2399 $info = $data->info;
2400 //traverse_xmlize($info); //Debug
2401 //print_object ($GLOBALS['traverse_array']); //Debug
2402 //$GLOBALS['traverse_array']=""; //Debug
2403 //Now build the MESSAGE record structure
2404 $dbrec = new object();
2405 $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2406 $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2407 $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2408 $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2409 $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2410 $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2411 //We have to recode the useridfrom field
2412 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
2413 if ($user) {
2414 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2415 $dbrec->useridfrom = $user->new_id;
2417 //We have to recode the useridto field
2418 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
2419 if ($user) {
2420 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2421 $dbrec->useridto = $user->new_id;
2423 //Check if the record doesn't exist in DB!
2424 $exist = get_record('message','useridfrom',$dbrec->useridfrom,
2425 'useridto', $dbrec->useridto,
2426 'timecreated',$dbrec->timecreated);
2427 if (!$exist) {
2428 //Not exist. Insert
2429 $status = insert_record('message',$dbrec);
2430 } else {
2431 //Duplicate. Do nothing
2434 //Do some output
2435 $counter++;
2436 if ($counter % 10 == 0) {
2437 if (!defined('RESTORE_SILENTLY')) {
2438 echo ".";
2439 if ($counter % 200 == 0) {
2440 echo "<br />";
2443 backup_flush(300);
2450 //Process read
2451 if ($readcount) {
2452 if (!defined('RESTORE_SILENTLY')) {
2453 echo '<li>'.get_string('readmessages','message').'</li>';
2455 $counter = 0;
2456 while ($counter < $readcount) {
2457 //Fetch recordset_size records in each iteration
2458 $recs = get_records_select("backup_ids","table_name = 'message_read' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2459 if ($recs) {
2460 foreach ($recs as $rec) {
2461 //Get the full record from backup_ids
2462 $data = backup_getid($restore->backup_unique_code,"message_read",$rec->old_id);
2463 if ($data) {
2464 //Now get completed xmlized object
2465 $info = $data->info;
2466 //traverse_xmlize($info); //Debug
2467 //print_object ($GLOBALS['traverse_array']); //Debug
2468 //$GLOBALS['traverse_array']=""; //Debug
2469 //Now build the MESSAGE_READ record structure
2470 $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2471 $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2472 $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2473 $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2474 $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2475 $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2476 $dbrec->timeread = backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
2477 $dbrec->mailed = backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
2478 //We have to recode the useridfrom field
2479 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
2480 if ($user) {
2481 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2482 $dbrec->useridfrom = $user->new_id;
2484 //We have to recode the useridto field
2485 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
2486 if ($user) {
2487 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2488 $dbrec->useridto = $user->new_id;
2490 //Check if the record doesn't exist in DB!
2491 $exist = get_record('message_read','useridfrom',$dbrec->useridfrom,
2492 'useridto', $dbrec->useridto,
2493 'timecreated',$dbrec->timecreated);
2494 if (!$exist) {
2495 //Not exist. Insert
2496 $status = insert_record('message_read',$dbrec);
2497 } else {
2498 //Duplicate. Do nothing
2501 //Do some output
2502 $counter++;
2503 if ($counter % 10 == 0) {
2504 if (!defined('RESTORE_SILENTLY')) {
2505 echo ".";
2506 if ($counter % 200 == 0) {
2507 echo "<br />";
2510 backup_flush(300);
2517 //Process contacts
2518 if ($contactcount) {
2519 if (!defined('RESTORE_SILENTLY')) {
2520 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
2522 $counter = 0;
2523 while ($counter < $contactcount) {
2524 //Fetch recordset_size records in each iteration
2525 $recs = get_records_select("backup_ids","table_name = 'message_contacts' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
2526 if ($recs) {
2527 foreach ($recs as $rec) {
2528 //Get the full record from backup_ids
2529 $data = backup_getid($restore->backup_unique_code,"message_contacts",$rec->old_id);
2530 if ($data) {
2531 //Now get completed xmlized object
2532 $info = $data->info;
2533 //traverse_xmlize($info); //Debug
2534 //print_object ($GLOBALS['traverse_array']); //Debug
2535 //$GLOBALS['traverse_array']=""; //Debug
2536 //Now build the MESSAGE_CONTACTS record structure
2537 $dbrec->userid = backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
2538 $dbrec->contactid = backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
2539 $dbrec->blocked = backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
2540 //We have to recode the userid field
2541 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->userid);
2542 if ($user) {
2543 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
2544 $dbrec->userid = $user->new_id;
2546 //We have to recode the contactid field
2547 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->contactid);
2548 if ($user) {
2549 //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />"; //Debug
2550 $dbrec->contactid = $user->new_id;
2552 //Check if the record doesn't exist in DB!
2553 $exist = get_record('message_contacts','userid',$dbrec->userid,
2554 'contactid', $dbrec->contactid);
2555 if (!$exist) {
2556 //Not exist. Insert
2557 $status = insert_record('message_contacts',$dbrec);
2558 } else {
2559 //Duplicate. Do nothing
2562 //Do some output
2563 $counter++;
2564 if ($counter % 10 == 0) {
2565 if (!defined('RESTORE_SILENTLY')) {
2566 echo ".";
2567 if ($counter % 200 == 0) {
2568 echo "<br />";
2571 backup_flush(300);
2577 if (!defined('RESTORE_SILENTLY')) {
2578 //End ul
2579 echo '</ul>';
2585 return $status;
2588 //This function creates all the categories and questions
2589 //from xml
2590 function restore_create_questions($restore,$xml_file) {
2592 global $CFG, $db;
2594 $status = true;
2595 //Check it exists
2596 if (!file_exists($xml_file)) {
2597 $status = false;
2599 //Get info from xml
2600 if ($status) {
2601 //info will contain the old_id of every category
2602 //in backup_ids->info will be the real info (serialized)
2603 $info = restore_read_xml_questions($restore,$xml_file);
2605 //Now, if we have anything in info, we have to restore that
2606 //categories/questions
2607 if ($info) {
2608 if ($info !== true) {
2609 $status = $status && restore_question_categories($info, $restore);
2611 } else {
2612 $status = false;
2614 return $status;
2617 //This function creates all the scales
2618 function restore_create_scales($restore,$xml_file) {
2620 global $CFG, $db;
2622 $status = true;
2623 //Check it exists
2624 if (!file_exists($xml_file)) {
2625 $status = false;
2627 //Get info from xml
2628 if ($status) {
2629 //scales will contain the old_id of every scale
2630 //in backup_ids->info will be the real info (serialized)
2631 $scales = restore_read_xml_scales($restore,$xml_file);
2633 //Now, if we have anything in scales, we have to restore that
2634 //scales
2635 if ($scales) {
2636 //Get admin->id for later use
2637 $admin = get_admin();
2638 $adminid = $admin->id;
2639 if ($scales !== true) {
2640 //Iterate over each scale
2641 foreach ($scales as $scale) {
2642 //Get record from backup_ids
2643 $data = backup_getid($restore->backup_unique_code,"scale",$scale->id);
2644 //Init variables
2645 $create_scale = false;
2647 if ($data) {
2648 //Now get completed xmlized object
2649 $info = $data->info;
2650 //traverse_xmlize($info); //Debug
2651 //print_object ($GLOBALS['traverse_array']); //Debug
2652 //$GLOBALS['traverse_array']=""; //Debug
2654 //Now build the SCALE record structure
2655 $sca = new object();
2656 $sca->courseid = backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
2657 $sca->userid = backup_todb($info['SCALE']['#']['USERID']['0']['#']);
2658 $sca->name = backup_todb($info['SCALE']['#']['NAME']['0']['#']);
2659 $sca->scale = backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
2660 $sca->description = backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
2661 $sca->timemodified = backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);
2663 //Now search if that scale exists (by scale field) in course 0 (Standar scale)
2664 //or in restore->course_id course (Personal scale)
2665 if ($sca->courseid == 0) {
2666 $course_to_search = 0;
2667 } else {
2668 $course_to_search = $restore->course_id;
2671 // scale is not course unique, use get_record_sql to suppress warning
2673 $sca_db = get_record_sql("SELECT * FROM {$CFG->prefix}scale
2674 WHERE scale = '$sca->scale'
2675 AND courseid = $course_to_search", true);
2677 //If it doesn't exist, create
2678 if (!$sca_db) {
2679 $create_scale = true;
2681 //If we must create the scale
2682 if ($create_scale) {
2683 //Me must recode the courseid if it's <> 0 (common scale)
2684 if ($sca->courseid != 0) {
2685 $sca->courseid = $restore->course_id;
2687 //We must recode the userid
2688 $user = backup_getid($restore->backup_unique_code,"user",$sca->userid);
2689 if ($user) {
2690 $sca->userid = $user->new_id;
2691 } else {
2692 //Assign it to admin
2693 $sca->userid = $adminid;
2695 //The structure is equal to the db, so insert the scale
2696 $newid = insert_record ("scale",$sca);
2697 } else {
2698 //get current scale id
2699 $newid = $sca_db->id;
2701 if ($newid) {
2702 //We have the newid, update backup_ids
2703 backup_putid($restore->backup_unique_code,"scale",
2704 $scale->id, $newid);
2709 } else {
2710 $status = false;
2712 return $status;
2715 //This function creates all the groups
2716 function restore_create_groups($restore,$xml_file) {
2718 global $CFG;
2720 //Check it exists
2721 if (!file_exists($xml_file)) {
2722 return false;
2724 //Get info from xml
2725 if (!$groups = restore_read_xml_groups($restore,$xml_file)) {
2726 //groups will contain the old_id of every group
2727 //in backup_ids->info will be the real info (serialized)
2728 return false;
2730 } else if ($groups === true) {
2731 return true;
2734 $status = true;
2736 //Iterate over each group
2737 foreach ($groups as $group) {
2738 //Get record from backup_ids
2739 $data = backup_getid($restore->backup_unique_code,"groups",$group->id);
2741 if ($data) {
2742 //Now get completed xmlized object
2743 $info = $data->info;
2744 //traverse_xmlize($info); //Debug
2745 //print_object ($GLOBALS['traverse_array']); //Debug
2746 //$GLOBALS['traverse_array']=""; //Debug
2747 //Now build the GROUP record structure
2748 $gro = new Object();
2749 $gro->courseid = $restore->course_id;
2750 $gro->name = backup_todb($info['GROUP']['#']['NAME']['0']['#']);
2751 $gro->description = backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
2752 if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) {
2753 $gro->enrolmentkey = backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']);
2754 } else {
2755 $gro->enrolmentkey = backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
2757 $gro->picture = backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
2758 $gro->hidepicture = backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
2759 $gro->timecreated = backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
2760 $gro->timemodified = backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
2762 //Now search if that group exists (by name and description field) in
2763 //restore->course_id course
2764 //Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides.
2765 $description_clause = '';
2766 if (!empty($gro->description)) { /// Only for groups having a description
2767 $literal_description = "'" . $gro->description . "'";
2768 $description_clause = " AND " .
2769 sql_compare_text('description') . " = " .
2770 sql_compare_text($literal_description);
2772 if (!$gro_db = get_record_sql("SELECT *
2773 FROM {$CFG->prefix}groups
2774 WHERE courseid = $restore->course_id AND
2775 name = '{$gro->name}'" . $description_clause)) {
2776 //If it doesn't exist, create
2777 $newid = insert_record('groups', $gro);
2779 } else {
2780 //get current group id
2781 $newid = $gro_db->id;
2784 if ($newid) {
2785 //We have the newid, update backup_ids
2786 backup_putid($restore->backup_unique_code,"groups", $group->id, $newid);
2787 } else {
2789 $status = false;
2790 continue;
2793 //Now restore members in the groups_members, only if
2794 //users are included
2795 if ($restore->users != 2) {
2796 if (!restore_create_groups_members($newid,$info,$restore)) {
2797 $status = false;
2803 //Now, restore group_files
2804 if ($status) {
2805 $status = restore_group_files($restore);
2808 return $status;
2811 //This function restores the groups_members
2812 function restore_create_groups_members($group_id,$info,$restore) {
2814 if (! isset($info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'])) {
2815 //OK, some groups have no members.
2816 return true;
2818 //Get the members array
2819 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
2821 $status = true;
2823 //Iterate over members
2824 for($i = 0; $i < sizeof($members); $i++) {
2825 $mem_info = $members[$i];
2826 //traverse_xmlize($mem_info); //Debug
2827 //print_object ($GLOBALS['traverse_array']); //Debug
2828 //$GLOBALS['traverse_array']=""; //Debug
2830 //Now, build the GROUPS_MEMBERS record structure
2831 $group_member = new Object();
2832 $group_member->groupid = $group_id;
2833 $group_member->userid = backup_todb($mem_info['#']['USERID']['0']['#']);
2834 $group_member->timeadded = backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
2836 $newid = false;
2838 //We have to recode the userid field
2839 if (!$user = backup_getid($restore->backup_unique_code,"user",$group_member->userid)) {
2840 $status = false;
2841 continue;
2844 $group_member->userid = $user->new_id;
2846 //The structure is equal to the db, so insert the groups_members
2847 if (!insert_record ("groups_members", $group_member)) {
2848 $status = false;
2849 continue;
2852 //Do some output
2853 if (($i+1) % 50 == 0) {
2854 if (!defined('RESTORE_SILENTLY')) {
2855 echo ".";
2856 if (($i+1) % 1000 == 0) {
2857 echo "<br />";
2860 backup_flush(300);
2864 return $status;
2867 //This function creates all the groupings
2868 function restore_create_groupings($restore,$xml_file) {
2870 //Check it exists
2871 if (!file_exists($xml_file)) {
2872 return false;
2874 //Get info from xml
2875 if (!$groupings = restore_read_xml_groupings($restore,$xml_file)) {
2876 return false;
2878 } else if ($groupings === true) {
2879 return true;
2882 $status = true;
2884 //Iterate over each group
2885 foreach ($groupings as $grouping) {
2886 if ($data = backup_getid($restore->backup_unique_code,"groupings",$grouping->id)) {
2887 //Now get completed xmlized object
2888 $info = $data->info;
2889 //Now build the GROUPING record structure
2890 $gro = new Object();
2891 ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']);
2892 $gro->courseid = $restore->course_id;
2893 $gro->name = backup_todb($info['GROUPING']['#']['NAME']['0']['#']);
2894 $gro->description = backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']);
2895 $gro->configdata = backup_todb($info['GROUPING']['#']['CONFIGDATA']['0']['#']);
2896 $gro->timecreated = backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']);
2898 //Now search if that group exists (by name and description field) in
2899 if ($gro_db = get_record('groupings', 'courseid', $restore->course_id, 'name', $gro->name, 'description', $gro->description)) {
2900 //get current group id
2901 $newid = $gro_db->id;
2903 } else {
2904 //The structure is equal to the db, so insert the grouping
2905 if (!$newid = insert_record('groupings', $gro)) {
2906 $status = false;
2907 continue;
2911 //We have the newid, update backup_ids
2912 backup_putid($restore->backup_unique_code,"groupings",
2913 $grouping->id, $newid);
2918 // now fix the defaultgroupingid in course
2919 $course = get_record('course', 'id', $restore->course_id);
2920 if ($course->defaultgroupingid) {
2921 if ($grouping = backup_getid($restore->backup_unique_code,"groupings",$course->defaultgroupingid)) {
2922 set_field('course', 'defaultgroupingid', $grouping->new_id, 'id', $course->id);
2923 } else {
2924 set_field('course', 'defaultgroupingid', 0, 'id', $course->id);
2928 return $status;
2931 //This function creates all the groupingsgroups
2932 function restore_create_groupings_groups($restore,$xml_file) {
2934 //Check it exists
2935 if (!file_exists($xml_file)) {
2936 return false;
2938 //Get info from xml
2939 if (!$groupingsgroups = restore_read_xml_groupings_groups($restore,$xml_file)) {
2940 return false;
2942 } else if ($groupingsgroups === true) {
2943 return true;
2946 $status = true;
2948 //Iterate over each group
2949 foreach ($groupingsgroups as $groupinggroup) {
2950 if ($data = backup_getid($restore->backup_unique_code,"groupingsgroups",$groupinggroup->id)) {
2951 //Now get completed xmlized object
2952 $info = $data->info;
2953 //Now build the GROUPING record structure
2954 $gro_member = new Object();
2955 $gro_member->groupingid = backup_todb($info['GROUPINGGROUP']['#']['GROUPINGID']['0']['#']);
2956 $gro_member->groupid = backup_todb($info['GROUPINGGROUP']['#']['GROUPID']['0']['#']);
2957 $gro_member->timeadded = backup_todb($info['GROUPINGGROUP']['#']['TIMEADDED']['0']['#']);
2959 if (!$grouping = backup_getid($restore->backup_unique_code,"groupings",$gro_member->groupingid)) {
2960 $status = false;
2961 continue;
2964 if (!$group = backup_getid($restore->backup_unique_code,"groups",$gro_member->groupid)) {
2965 $status = false;
2966 continue;
2969 $gro_member->groupid = $group->new_id;
2970 $gro_member->groupingid = $grouping->new_id;
2971 if (!get_record('groupings_groups', 'groupid', $gro_member->groupid, 'groupingid', $gro_member->groupingid)) {
2972 if (!insert_record('groupings_groups', $gro_member)) {
2973 $status = false;
2979 return $status;
2982 //This function creates all the course events
2983 function restore_create_events($restore,$xml_file) {
2985 global $CFG, $db;
2987 $status = true;
2988 //Check it exists
2989 if (!file_exists($xml_file)) {
2990 $status = false;
2992 //Get info from xml
2993 if ($status) {
2994 //events will contain the old_id of every event
2995 //in backup_ids->info will be the real info (serialized)
2996 $events = restore_read_xml_events($restore,$xml_file);
2999 //Get admin->id for later use
3000 $admin = get_admin();
3001 $adminid = $admin->id;
3003 //Now, if we have anything in events, we have to restore that
3004 //events
3005 if ($events) {
3006 if ($events !== true) {
3007 //Iterate over each event
3008 foreach ($events as $event) {
3009 //Get record from backup_ids
3010 $data = backup_getid($restore->backup_unique_code,"event",$event->id);
3011 //Init variables
3012 $create_event = false;
3014 if ($data) {
3015 //Now get completed xmlized object
3016 $info = $data->info;
3017 //traverse_xmlize($info); //Debug
3018 //print_object ($GLOBALS['traverse_array']); //Debug
3019 //$GLOBALS['traverse_array']=""; //Debug
3021 //if necessary, write to restorelog and adjust date/time fields
3022 if ($restore->course_startdateoffset) {
3023 restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
3026 //Now build the EVENT record structure
3027 $eve->name = backup_todb($info['EVENT']['#']['NAME']['0']['#']);
3028 $eve->description = backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
3029 $eve->format = backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
3030 $eve->courseid = $restore->course_id;
3031 $eve->groupid = backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
3032 $eve->userid = backup_todb($info['EVENT']['#']['USERID']['0']['#']);
3033 $eve->repeatid = backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
3034 $eve->modulename = "";
3035 if (!empty($info['EVENT']['#']['MODULENAME'])) {
3036 $eve->modulename = backup_todb($info['EVENT']['#']['MODULENAME']['0']['#']);
3038 $eve->instance = 0;
3039 $eve->eventtype = backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
3040 $eve->timestart = backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
3041 $eve->timeduration = backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
3042 $eve->visible = backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
3043 $eve->timemodified = backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
3045 //Now search if that event exists (by name, description, timestart fields) in
3046 //restore->course_id course
3047 $eve_db = get_record_select("event",
3048 "courseid={$eve->courseid} AND name='{$eve->name}' AND description='{$eve->description}' AND timestart=$eve->timestart");
3049 //If it doesn't exist, create
3050 if (!$eve_db) {
3051 $create_event = true;
3053 //If we must create the event
3054 if ($create_event) {
3056 //We must recode the userid
3057 $user = backup_getid($restore->backup_unique_code,"user",$eve->userid);
3058 if ($user) {
3059 $eve->userid = $user->new_id;
3060 } else {
3061 //Assign it to admin
3062 $eve->userid = $adminid;
3065 //We must recode the repeatid if the event has it
3066 if (!empty($eve->repeatid)) {
3067 $repeat_rec = backup_getid($restore->backup_unique_code,"event_repeatid",$eve->repeatid);
3068 if ($repeat_rec) { //Exists, so use it...
3069 $eve->repeatid = $repeat_rec->new_id;
3070 } else { //Doesn't exists, calculate the next and save it
3071 $oldrepeatid = $eve->repeatid;
3072 $max_rec = get_record_sql('SELECT 1, MAX(repeatid) AS repeatid FROM '.$CFG->prefix.'event');
3073 $eve->repeatid = empty($max_rec) ? 1 : $max_rec->repeatid + 1;
3074 backup_putid($restore->backup_unique_code,"event_repeatid", $oldrepeatid, $eve->repeatid);
3078 //We have to recode the groupid field
3079 $group = backup_getid($restore->backup_unique_code,"groups",$eve->groupid);
3080 if ($group) {
3081 $eve->groupid = $group->new_id;
3082 } else {
3083 //Assign it to group 0
3084 $eve->groupid = 0;
3087 //The structure is equal to the db, so insert the event
3088 $newid = insert_record ("event",$eve);
3089 } else {
3090 //get current event id
3091 $newid = $eve_db->id;
3093 if ($newid) {
3094 //We have the newid, update backup_ids
3095 backup_putid($restore->backup_unique_code,"event",
3096 $event->id, $newid);
3101 } else {
3102 $status = false;
3104 return $status;
3107 //This function decode things to make restore multi-site fully functional
3108 //It does this conversions:
3109 // - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
3110 // |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
3112 //Note: Inter-activities linking is being implemented as a final
3113 //step in the restore execution, because we need to have it
3114 //finished to know all the oldid, newid equivaleces
3115 function restore_decode_absolute_links($content) {
3117 global $CFG,$restore;
3119 // MDL-10770
3120 // This function was replacing null with empty string
3121 // Nullity check is added in backup_todb(), this function will no longer not be called from backup_todb() if content is null
3122 // I noticed some parts of the restore code is calling this directly instead of calling backup_todb(), so just in case
3123 // 3rd party mod etc are doing the same
3124 if ($content === NULL) {
3125 return NULL;
3128 //Now decode wwwroot and file.php calls
3129 $search = array ("$@FILEPHP@$");
3131 //Check for the status of the slasharguments config variable
3132 $slash = $CFG->slasharguments;
3134 //Build the replace string as needed
3135 if ($slash == 1) {
3136 $replace = array ($CFG->wwwroot."/file.php/".$restore->course_id);
3137 } else {
3138 $replace = array ($CFG->wwwroot."/file.php?file=/".$restore->course_id);
3141 $result = str_replace($search,$replace,$content);
3143 if ($result != $content && debugging()) { //Debug
3144 if (!defined('RESTORE_SILENTLY')) {
3145 echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />'; //Debug
3147 } //Debug
3149 return $result;
3152 //This function restores the userfiles from the temp (user_files) directory to the
3153 //dataroot/users directory
3154 function restore_user_files($restore) {
3156 global $CFG;
3158 $status = true;
3160 $counter = 0;
3162 //First, we check to "users" exists and create is as necessary
3163 //in CFG->dataroot
3164 $dest_dir = $CFG->dataroot."/users";
3165 $status = check_dir_exists($dest_dir,true);
3167 //Now, we iterate over "user_files" records to check if that user dir must be
3168 //copied (and renamed) to the "users" dir.
3169 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/user_files";
3170 //Check if directory exists
3171 if (is_dir($rootdir)) {
3172 $list = list_directories ($rootdir);
3173 if ($list) {
3174 //Iterate
3175 $counter = 0;
3176 foreach ($list as $dir) {
3177 //Look for dir like username in backup_ids
3178 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
3179 "table_name","user",
3180 "old_id",$dir);
3181 //If thar user exists in backup_ids
3182 if ($data) {
3183 //Only it user has been created now
3184 //or if it existed previously, but he hasn't image (see bug 1123)
3185 if ((strpos($data->info,"new") !== false) or
3186 (!check_dir_exists($dest_dir."/".$data->new_id,false))) {
3187 //Copy the old_dir to its new location (and name) !!
3188 //Only if destination doesn't exists
3189 if (!file_exists($dest_dir."/".$data->new_id)) {
3190 $status = backup_copy_file($rootdir."/".$dir,
3191 $dest_dir."/".$data->new_id,true);
3192 $counter ++;
3194 //Do some output
3195 if ($counter % 2 == 0) {
3196 if (!defined('RESTORE_SILENTLY')) {
3197 echo ".";
3198 if ($counter % 40 == 0) {
3199 echo "<br />";
3202 backup_flush(300);
3209 //If status is ok and whe have dirs created, returns counter to inform
3210 if ($status and $counter) {
3211 return $counter;
3212 } else {
3213 return $status;
3217 //This function restores the groupfiles from the temp (group_files) directory to the
3218 //dataroot/groups directory
3219 function restore_group_files($restore) {
3221 global $CFG;
3223 $status = true;
3225 $counter = 0;
3227 //First, we check to "groups" exists and create is as necessary
3228 //in CFG->dataroot
3229 $dest_dir = $CFG->dataroot.'/groups';
3230 $status = check_dir_exists($dest_dir,true);
3232 //Now, we iterate over "group_files" records to check if that user dir must be
3233 //copied (and renamed) to the "groups" dir.
3234 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/group_files";
3235 //Check if directory exists
3236 if (is_dir($rootdir)) {
3237 $list = list_directories ($rootdir);
3238 if ($list) {
3239 //Iterate
3240 $counter = 0;
3241 foreach ($list as $dir) {
3242 //Look for dir like groupid in backup_ids
3243 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
3244 "table_name","groups",
3245 "old_id",$dir);
3246 //If that group exists in backup_ids
3247 if ($data) {
3248 if (!file_exists($dest_dir."/".$data->new_id)) {
3249 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id,true);
3250 $counter ++;
3252 //Do some output
3253 if ($counter % 2 == 0) {
3254 if (!defined('RESTORE_SILENTLY')) {
3255 echo ".";
3256 if ($counter % 40 == 0) {
3257 echo "<br />";
3260 backup_flush(300);
3266 //If status is ok and whe have dirs created, returns counter to inform
3267 if ($status and $counter) {
3268 return $counter;
3269 } else {
3270 return $status;
3274 //This function restores the course files from the temp (course_files) directory to the
3275 //dataroot/course_id directory
3276 function restore_course_files($restore) {
3278 global $CFG;
3280 $status = true;
3282 $counter = 0;
3284 //First, we check to "course_id" exists and create is as necessary
3285 //in CFG->dataroot
3286 $dest_dir = $CFG->dataroot."/".$restore->course_id;
3287 $status = check_dir_exists($dest_dir,true);
3289 //Now, we iterate over "course_files" records to check if that file/dir must be
3290 //copied to the "dest_dir" dir.
3291 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/course_files";
3292 //Check if directory exists
3293 if (is_dir($rootdir)) {
3294 $list = list_directories_and_files ($rootdir);
3295 if ($list) {
3296 //Iterate
3297 $counter = 0;
3298 foreach ($list as $dir) {
3299 //Copy the dir to its new location
3300 //Only if destination file/dir doesn exists
3301 if (!file_exists($dest_dir."/".$dir)) {
3302 $status = backup_copy_file($rootdir."/".$dir,
3303 $dest_dir."/".$dir,true);
3304 $counter ++;
3306 //Do some output
3307 if ($counter % 2 == 0) {
3308 if (!defined('RESTORE_SILENTLY')) {
3309 echo ".";
3310 if ($counter % 40 == 0) {
3311 echo "<br />";
3314 backup_flush(300);
3319 //If status is ok and whe have dirs created, returns counter to inform
3320 if ($status and $counter) {
3321 return $counter;
3322 } else {
3323 return $status;
3327 //This function restores the site files from the temp (site_files) directory to the
3328 //dataroot/SITEID directory
3329 function restore_site_files($restore) {
3331 global $CFG;
3333 $status = true;
3335 $counter = 0;
3337 //First, we check to "course_id" exists and create is as necessary
3338 //in CFG->dataroot
3339 $dest_dir = $CFG->dataroot."/".SITEID;
3340 $status = check_dir_exists($dest_dir,true);
3342 //Now, we iterate over "site_files" files to check if that file/dir must be
3343 //copied to the "dest_dir" dir.
3344 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/site_files";
3345 //Check if directory exists
3346 if (is_dir($rootdir)) {
3347 $list = list_directories_and_files ($rootdir);
3348 if ($list) {
3349 //Iterate
3350 $counter = 0;
3351 foreach ($list as $dir) {
3352 //Copy the dir to its new location
3353 //Only if destination file/dir doesn exists
3354 if (!file_exists($dest_dir."/".$dir)) {
3355 $status = backup_copy_file($rootdir."/".$dir,
3356 $dest_dir."/".$dir,true);
3357 $counter ++;
3359 //Do some output
3360 if ($counter % 2 == 0) {
3361 if (!defined('RESTORE_SILENTLY')) {
3362 echo ".";
3363 if ($counter % 40 == 0) {
3364 echo "<br />";
3367 backup_flush(300);
3372 //If status is ok and whe have dirs created, returns counter to inform
3373 if ($status and $counter) {
3374 return $counter;
3375 } else {
3376 return $status;
3381 //This function creates all the structures for every module in backup file
3382 //Depending what has been selected.
3383 function restore_create_modules($restore,$xml_file) {
3385 global $CFG;
3386 $status = true;
3387 //Check it exists
3388 if (!file_exists($xml_file)) {
3389 $status = false;
3391 //Get info from xml
3392 if ($status) {
3393 //info will contain the id and modtype of every module
3394 //in backup_ids->info will be the real info (serialized)
3395 $info = restore_read_xml_modules($restore,$xml_file);
3397 //Now, if we have anything in info, we have to restore that mods
3398 //from backup_ids (calling every mod restore function)
3399 if ($info) {
3400 if ($info !== true) {
3401 if (!defined('RESTORE_SILENTLY')) {
3402 echo '<ul>';
3404 //Iterate over each module
3405 foreach ($info as $mod) {
3406 if (empty($restore->mods[$mod->modtype]->granular) // We don't care about per instance, i.e. restore all instances.
3407 || (array_key_exists($mod->id,$restore->mods[$mod->modtype]->instances)
3408 && !empty($restore->mods[$mod->modtype]->instances[$mod->id]->restore))) {
3409 $modrestore = $mod->modtype."_restore_mods";
3410 if (function_exists($modrestore)) { //Debug
3411 // we want to restore all mods even when one fails
3412 // incorrect code here ignored any errors during module restore in 1.6-1.8
3413 $status = $status && $modrestore($mod,$restore);
3414 } else {
3415 //Something was wrong. Function should exist.
3416 $status = false;
3420 if (!defined('RESTORE_SILENTLY')) {
3421 echo '</ul>';
3424 } else {
3425 $status = false;
3427 return $status;
3430 //This function creates all the structures for every log in backup file
3431 //Depending what has been selected.
3432 function restore_create_logs($restore,$xml_file) {
3434 global $CFG,$db;
3436 //Number of records to get in every chunk
3437 $recordset_size = 4;
3438 //Counter, points to current record
3439 $counter = 0;
3440 //To count all the recods to restore
3441 $count_logs = 0;
3443 $status = true;
3444 //Check it exists
3445 if (!file_exists($xml_file)) {
3446 $status = false;
3448 //Get info from xml
3449 if ($status) {
3450 //count_logs will contain the number of logs entries to process
3451 //in backup_ids->info will be the real info (serialized)
3452 $count_logs = restore_read_xml_logs($restore,$xml_file);
3455 //Now, if we have records in count_logs, we have to restore that logs
3456 //from backup_ids. This piece of code makes calls to:
3457 // - restore_log_course() if it's a course log
3458 // - restore_log_user() if it's a user log
3459 // - restore_log_module() if it's a module log.
3460 //And all is segmented in chunks to allow large recordsets to be restored !!
3461 if ($count_logs > 0) {
3462 while ($counter < $count_logs) {
3463 //Get a chunk of records
3464 //Take old_id twice to avoid adodb limitation
3465 $logs = get_records_select("backup_ids","table_name = 'log' AND backup_code = '$restore->backup_unique_code'","old_id","old_id",$counter,$recordset_size);
3466 //We have logs
3467 if ($logs) {
3468 //Iterate
3469 foreach ($logs as $log) {
3470 //Get the full record from backup_ids
3471 $data = backup_getid($restore->backup_unique_code,"log",$log->old_id);
3472 if ($data) {
3473 //Now get completed xmlized object
3474 $info = $data->info;
3475 //traverse_xmlize($info); //Debug
3476 //print_object ($GLOBALS['traverse_array']); //Debug
3477 //$GLOBALS['traverse_array']=""; //Debug
3478 //Now build the LOG record structure
3479 $dblog = new object();
3480 $dblog->time = backup_todb($info['LOG']['#']['TIME']['0']['#']);
3481 $dblog->userid = backup_todb($info['LOG']['#']['USERID']['0']['#']);
3482 $dblog->ip = backup_todb($info['LOG']['#']['IP']['0']['#']);
3483 $dblog->course = $restore->course_id;
3484 $dblog->module = backup_todb($info['LOG']['#']['MODULE']['0']['#']);
3485 $dblog->cmid = backup_todb($info['LOG']['#']['CMID']['0']['#']);
3486 $dblog->action = backup_todb($info['LOG']['#']['ACTION']['0']['#']);
3487 $dblog->url = backup_todb($info['LOG']['#']['URL']['0']['#']);
3488 $dblog->info = backup_todb($info['LOG']['#']['INFO']['0']['#']);
3489 //We have to recode the userid field
3490 $user = backup_getid($restore->backup_unique_code,"user",$dblog->userid);
3491 if ($user) {
3492 //echo "User ".$dblog->userid." to user ".$user->new_id."<br />"; //Debug
3493 $dblog->userid = $user->new_id;
3495 //We have to recode the cmid field (if module isn't "course" or "user")
3496 if ($dblog->module != "course" and $dblog->module != "user") {
3497 $cm = backup_getid($restore->backup_unique_code,"course_modules",$dblog->cmid);
3498 if ($cm) {
3499 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
3500 $dblog->cmid = $cm->new_id;
3501 } else {
3502 $dblog->cmid = 0;
3505 //print_object ($dblog); //Debug
3506 //Now, we redirect to the needed function to make all the work
3507 if ($dblog->module == "course") {
3508 //It's a course log,
3509 $stat = restore_log_course($restore,$dblog);
3510 } elseif ($dblog->module == "user") {
3511 //It's a user log,
3512 $stat = restore_log_user($restore,$dblog);
3513 } else {
3514 //It's a module log,
3515 $stat = restore_log_module($restore,$dblog);
3519 //Do some output
3520 $counter++;
3521 if ($counter % 10 == 0) {
3522 if (!defined('RESTORE_SILENTLY')) {
3523 echo ".";
3524 if ($counter % 200 == 0) {
3525 echo "<br />";
3528 backup_flush(300);
3531 } else {
3532 //We never should arrive here
3533 $counter = $count_logs;
3534 $status = false;
3539 return $status;
3542 //This function inserts a course log record, calculating the URL field as necessary
3543 function restore_log_course($restore,$log) {
3545 $status = true;
3546 $toinsert = false;
3548 //echo "<hr />Before transformations<br />"; //Debug
3549 //print_object($log); //Debug
3550 //Depending of the action, we recode different things
3551 switch ($log->action) {
3552 case "view":
3553 $log->url = "view.php?id=".$log->course;
3554 $log->info = $log->course;
3555 $toinsert = true;
3556 break;
3557 case "guest":
3558 $log->url = "view.php?id=".$log->course;
3559 $toinsert = true;
3560 break;
3561 case "user report":
3562 //recode the info field (it's the user id)
3563 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3564 if ($user) {
3565 $log->info = $user->new_id;
3566 //Now, extract the mode from the url field
3567 $mode = substr(strrchr($log->url,"="),1);
3568 $log->url = "user.php?id=".$log->course."&user=".$log->info."&mode=".$mode;
3569 $toinsert = true;
3571 break;
3572 case "add mod":
3573 //Extract the course_module from the url field
3574 $cmid = substr(strrchr($log->url,"="),1);
3575 //recode the course_module to see it it has been restored
3576 $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
3577 if ($cm) {
3578 $cmid = $cm->new_id;
3579 //Extract the module name and the module id from the info field
3580 $modname = strtok($log->info," ");
3581 $modid = strtok(" ");
3582 //recode the module id to see if it has been restored
3583 $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
3584 if ($mod) {
3585 $modid = $mod->new_id;
3586 //Now I have everything so reconstruct url and info
3587 $log->info = $modname." ".$modid;
3588 $log->url = "../mod/".$modname."/view.php?id=".$cmid;
3589 $toinsert = true;
3592 break;
3593 case "update mod":
3594 //Extract the course_module from the url field
3595 $cmid = substr(strrchr($log->url,"="),1);
3596 //recode the course_module to see it it has been restored
3597 $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
3598 if ($cm) {
3599 $cmid = $cm->new_id;
3600 //Extract the module name and the module id from the info field
3601 $modname = strtok($log->info," ");
3602 $modid = strtok(" ");
3603 //recode the module id to see if it has been restored
3604 $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
3605 if ($mod) {
3606 $modid = $mod->new_id;
3607 //Now I have everything so reconstruct url and info
3608 $log->info = $modname." ".$modid;
3609 $log->url = "../mod/".$modname."/view.php?id=".$cmid;
3610 $toinsert = true;
3613 break;
3614 case "delete mod":
3615 $log->url = "view.php?id=".$log->course;
3616 $toinsert = true;
3617 break;
3618 case "update":
3619 $log->url = "edit.php?id=".$log->course;
3620 $log->info = "";
3621 $toinsert = true;
3622 break;
3623 case "unenrol":
3624 //recode the info field (it's the user id)
3625 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3626 if ($user) {
3627 $log->info = $user->new_id;
3628 $log->url = "view.php?id=".$log->course;
3629 $toinsert = true;
3631 break;
3632 case "enrol":
3633 //recode the info field (it's the user id)
3634 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3635 if ($user) {
3636 $log->info = $user->new_id;
3637 $log->url = "view.php?id=".$log->course;
3638 $toinsert = true;
3640 break;
3641 case "editsection":
3642 //Extract the course_section from the url field
3643 $secid = substr(strrchr($log->url,"="),1);
3644 //recode the course_section to see if it has been restored
3645 $sec = backup_getid($restore->backup_unique_code,"course_sections",$secid);
3646 if ($sec) {
3647 $secid = $sec->new_id;
3648 //Now I have everything so reconstruct url and info
3649 $log->url = "editsection.php?id=".$secid;
3650 $toinsert = true;
3652 break;
3653 case "new":
3654 $log->url = "view.php?id=".$log->course;
3655 $log->info = "";
3656 $toinsert = true;
3657 break;
3658 case "recent":
3659 $log->url = "recent.php?id=".$log->course;
3660 $log->info = "";
3661 $toinsert = true;
3662 break;
3663 case "report log":
3664 $log->url = "report/log/index.php?id=".$log->course;
3665 $log->info = $log->course;
3666 $toinsert = true;
3667 break;
3668 case "report live":
3669 $log->url = "report/log/live.php?id=".$log->course;
3670 $log->info = $log->course;
3671 $toinsert = true;
3672 break;
3673 case "report outline":
3674 $log->url = "report/outline/index.php?id=".$log->course;
3675 $log->info = $log->course;
3676 $toinsert = true;
3677 break;
3678 case "report participation":
3679 $log->url = "report/participation/index.php?id=".$log->course;
3680 $log->info = $log->course;
3681 $toinsert = true;
3682 break;
3683 case "report stats":
3684 $log->url = "report/stats/index.php?id=".$log->course;
3685 $log->info = $log->course;
3686 $toinsert = true;
3687 break;
3688 default:
3689 echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug
3690 break;
3693 //echo "After transformations<br />"; //Debug
3694 //print_object($log); //Debug
3696 //Now if $toinsert is set, insert the record
3697 if ($toinsert) {
3698 //echo "Inserting record<br />"; //Debug
3699 $status = insert_record("log",$log);
3701 return $status;
3704 //This function inserts a user log record, calculating the URL field as necessary
3705 function restore_log_user($restore,$log) {
3707 $status = true;
3708 $toinsert = false;
3710 //echo "<hr />Before transformations<br />"; //Debug
3711 //print_object($log); //Debug
3712 //Depending of the action, we recode different things
3713 switch ($log->action) {
3714 case "view":
3715 //recode the info field (it's the user id)
3716 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3717 if ($user) {
3718 $log->info = $user->new_id;
3719 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3720 $toinsert = true;
3722 break;
3723 case "change password":
3724 //recode the info field (it's the user id)
3725 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3726 if ($user) {
3727 $log->info = $user->new_id;
3728 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3729 $toinsert = true;
3731 break;
3732 case "login":
3733 //recode the info field (it's the user id)
3734 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3735 if ($user) {
3736 $log->info = $user->new_id;
3737 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3738 $toinsert = true;
3740 break;
3741 case "logout":
3742 //recode the info field (it's the user id)
3743 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3744 if ($user) {
3745 $log->info = $user->new_id;
3746 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3747 $toinsert = true;
3749 break;
3750 case "view all":
3751 $log->url = "view.php?id=".$log->course;
3752 $log->info = "";
3753 $toinsert = true;
3754 case "update":
3755 //We split the url by ampersand char
3756 $first_part = strtok($log->url,"&");
3757 //Get data after the = char. It's the user being updated
3758 $userid = substr(strrchr($first_part,"="),1);
3759 //Recode the user
3760 $user = backup_getid($restore->backup_unique_code,"user",$userid);
3761 if ($user) {
3762 $log->info = "";
3763 $log->url = "view.php?id=".$user->new_id."&course=".$log->course;
3764 $toinsert = true;
3766 break;
3767 default:
3768 echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug
3769 break;
3772 //echo "After transformations<br />"; //Debug
3773 //print_object($log); //Debug
3775 //Now if $toinsert is set, insert the record
3776 if ($toinsert) {
3777 //echo "Inserting record<br />"; //Debug
3778 $status = insert_record("log",$log);
3780 return $status;
3783 //This function inserts a module log record, calculating the URL field as necessary
3784 function restore_log_module($restore,$log) {
3786 $status = true;
3787 $toinsert = false;
3789 //echo "<hr />Before transformations<br />"; //Debug
3790 //print_object($log); //Debug
3792 //Now we see if the required function in the module exists
3793 $function = $log->module."_restore_logs";
3794 if (function_exists($function)) {
3795 //Call the function
3796 $log = $function($restore,$log);
3797 //If everything is ok, mark the insert flag
3798 if ($log) {
3799 $toinsert = true;
3803 //echo "After transformations<br />"; //Debug
3804 //print_object($log); //Debug
3806 //Now if $toinsert is set, insert the record
3807 if ($toinsert) {
3808 //echo "Inserting record<br />"; //Debug
3809 $status = insert_record("log",$log);
3811 return $status;
3814 //This function adjusts the instance field into course_modules. It's executed after
3815 //modules restore. There, we KNOW the new instance id !!
3816 function restore_check_instances($restore) {
3818 global $CFG;
3820 $status = true;
3822 //We are going to iterate over each course_module saved in backup_ids
3823 $course_modules = get_records_sql("SELECT old_id,new_id
3824 FROM {$CFG->prefix}backup_ids
3825 WHERE backup_code = '$restore->backup_unique_code' AND
3826 table_name = 'course_modules'");
3827 if ($course_modules) {
3828 foreach($course_modules as $cm) {
3829 //Get full record, using backup_getids
3830 $cm_module = backup_getid($restore->backup_unique_code,"course_modules",$cm->old_id);
3831 //Now we are going to the REAL course_modules to get its type (field module)
3832 $module = get_record("course_modules","id",$cm_module->new_id);
3833 if ($module) {
3834 //We know the module type id. Get the name from modules
3835 $type = get_record("modules","id",$module->module);
3836 if ($type) {
3837 //We know the type name and the old_id. Get its new_id
3838 //from backup_ids. It's the instance !!!
3839 $instance = backup_getid($restore->backup_unique_code,$type->name,$cm_module->info);
3840 if ($instance) {
3841 //We have the new instance, so update the record in course_modules
3842 $module->instance = $instance->new_id;
3843 //print_object ($module); //Debug
3844 $status = update_record("course_modules",$module);
3845 } else {
3846 $status = false;
3848 } else {
3849 $status = false;
3851 } else {
3852 $status = false;
3858 return $status;
3861 //=====================================================================================
3862 //== ==
3863 //== XML Functions (SAX) ==
3864 //== ==
3865 //=====================================================================================
3867 //This is the class used to do all the xml parse
3868 class MoodleParser {
3870 var $level = 0; //Level we are
3871 var $counter = 0; //Counter
3872 var $tree = array(); //Array of levels we are
3873 var $content = ""; //Content under current level
3874 var $todo = ""; //What we hav to do when parsing
3875 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
3876 var $temp = ""; //Temp storage.
3877 var $preferences = ""; //Preferences about what to load !!
3878 var $finished = false; //Flag to say xml_parse to stop
3880 //This function is used to get the current contents property value
3881 //They are trimed (and converted from utf8 if needed)
3882 function getContents() {
3883 return trim($this->content);
3886 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3887 function startElementInfo($parser, $tagName, $attrs) {
3888 //Refresh properties
3889 $this->level++;
3890 $this->tree[$this->level] = $tagName;
3892 //Output something to avoid browser timeouts...
3893 backup_flush();
3895 //Check if we are into INFO zone
3896 //if ($this->tree[2] == "INFO") //Debug
3897 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3900 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3901 function startElementRoles($parser, $tagName, $attrs) {
3902 //Refresh properties
3903 $this->level++;
3904 $this->tree[$this->level] = $tagName;
3906 //Output something to avoid browser timeouts...
3907 backup_flush();
3909 //Check if we are into INFO zone
3910 //if ($this->tree[2] == "INFO") //Debug
3911 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3915 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
3916 function startElementCourseHeader($parser, $tagName, $attrs) {
3917 //Refresh properties
3918 $this->level++;
3919 $this->tree[$this->level] = $tagName;
3921 //Output something to avoid browser timeouts...
3922 backup_flush();
3924 //Check if we are into COURSE_HEADER zone
3925 //if ($this->tree[3] == "HEADER") //Debug
3926 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3929 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
3930 function startElementBlocks($parser, $tagName, $attrs) {
3931 //Refresh properties
3932 $this->level++;
3933 $this->tree[$this->level] = $tagName;
3935 //Output something to avoid browser timeouts...
3936 backup_flush();
3938 //Check if we are into BLOCKS zone
3939 //if ($this->tree[3] == "BLOCKS") //Debug
3940 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3943 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
3944 function startElementSections($parser, $tagName, $attrs) {
3945 //Refresh properties
3946 $this->level++;
3947 $this->tree[$this->level] = $tagName;
3949 //Output something to avoid browser timeouts...
3950 backup_flush();
3952 //Check if we are into SECTIONS zone
3953 //if ($this->tree[3] == "SECTIONS") //Debug
3954 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3957 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
3958 function startElementFormatData($parser, $tagName, $attrs) {
3959 //Refresh properties
3960 $this->level++;
3961 $this->tree[$this->level] = $tagName;
3963 //Output something to avoid browser timeouts...
3964 backup_flush();
3966 //Accumulate all the data inside this tag
3967 if (isset($this->tree[3]) && $this->tree[3] == "FORMATDATA") {
3968 if (!isset($this->temp)) {
3969 $this->temp = '';
3971 $this->temp .= "<".$tagName.">";
3974 //Check if we are into FORMATDATA zone
3975 //if ($this->tree[3] == "FORMATDATA") //Debug
3976 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3979 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
3980 function startElementMetacourse($parser, $tagName, $attrs) {
3982 //Refresh properties
3983 $this->level++;
3984 $this->tree[$this->level] = $tagName;
3986 //Output something to avoid browser timeouts...
3987 backup_flush();
3989 //Check if we are into METACOURSE zone
3990 //if ($this->tree[3] == "METACOURSE") //Debug
3991 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3994 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
3995 function startElementGradebook($parser, $tagName, $attrs) {
3997 //Refresh properties
3998 $this->level++;
3999 $this->tree[$this->level] = $tagName;
4001 //Output something to avoid browser timeouts...
4002 backup_flush();
4004 //Check if we are into GRADEBOOK zone
4005 //if ($this->tree[3] == "GRADEBOOK") //Debug
4006 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4008 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4009 if (isset($this->tree[5]) and isset($this->tree[3])) {
4010 if (($this->tree[5] == "GRADE_ITEM" || $this->tree[5] == "GRADE_CATEGORY" || $this->tree[5] == "GRADE_OUTCOME" || $this->tree[5] == "GRADE_OUTCOMES_COURSE" || $this->tree[5] == "GRADE_CATEGORIES_HISTORY" || $this->tree[5] == "GRADE_GRADES_HISTORY" || $this->tree[5] == "GRADE_TEXT_HISTORY" || $this->tree[5] == "GRADE_ITEM_HISTORY" || $this->tree[5] == "GRADE_OUTCOME_HISTORY") && ($this->tree[3] == "GRADEBOOK")) {
4012 if (!isset($this->temp)) {
4013 $this->temp = "";
4015 $this->temp .= "<".$tagName.">";
4021 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
4022 function startElementUsers($parser, $tagName, $attrs) {
4023 //Refresh properties
4024 $this->level++;
4025 $this->tree[$this->level] = $tagName;
4027 //Check if we are into USERS zone
4028 //if ($this->tree[3] == "USERS") //Debug
4029 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4032 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
4033 function startElementMessages($parser, $tagName, $attrs) {
4034 //Refresh properties
4035 $this->level++;
4036 $this->tree[$this->level] = $tagName;
4038 //Output something to avoid browser timeouts...
4039 backup_flush();
4041 //Check if we are into MESSAGES zone
4042 //if ($this->tree[3] == "MESSAGES") //Debug
4043 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4045 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
4046 if (isset($this->tree[4]) and isset($this->tree[3])) {
4047 if (($this->tree[4] == "MESSAGE" || $this->tree[5] == "CONTACT" ) and ($this->tree[3] == "MESSAGES")) {
4048 if (!isset($this->temp)) {
4049 $this->temp = "";
4051 $this->temp .= "<".$tagName.">";
4055 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4056 function startElementQuestions($parser, $tagName, $attrs) {
4057 //Refresh properties
4058 $this->level++;
4059 $this->tree[$this->level] = $tagName;
4061 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
4062 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
4063 //} //Debug
4065 //Output something to avoid browser timeouts...
4066 backup_flush();
4068 //Check if we are into QUESTION_CATEGORIES zone
4069 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
4070 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4072 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
4073 if (isset($this->tree[4]) and isset($this->tree[3])) {
4074 if (($this->tree[4] == "QUESTION_CATEGORY") and ($this->tree[3] == "QUESTION_CATEGORIES")) {
4075 if (!isset($this->temp)) {
4076 $this->temp = "";
4078 $this->temp .= "<".$tagName.">";
4083 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
4084 function startElementScales($parser, $tagName, $attrs) {
4085 //Refresh properties
4086 $this->level++;
4087 $this->tree[$this->level] = $tagName;
4089 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
4090 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
4091 //} //Debug
4093 //Output something to avoid browser timeouts...
4094 backup_flush();
4096 //Check if we are into SCALES zone
4097 //if ($this->tree[3] == "SCALES") //Debug
4098 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4100 //If we are under a SCALE tag under a SCALES zone, accumule it
4101 if (isset($this->tree[4]) and isset($this->tree[3])) {
4102 if (($this->tree[4] == "SCALE") and ($this->tree[3] == "SCALES")) {
4103 if (!isset($this->temp)) {
4104 $this->temp = "";
4106 $this->temp .= "<".$tagName.">";
4111 function startElementGroups($parser, $tagName, $attrs) {
4112 //Refresh properties
4113 $this->level++;
4114 $this->tree[$this->level] = $tagName;
4116 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
4117 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
4118 //} //Debug
4120 //Output something to avoid browser timeouts...
4121 backup_flush();
4123 //Check if we are into GROUPS zone
4124 //if ($this->tree[3] == "GROUPS") //Debug
4125 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4127 //If we are under a GROUP tag under a GROUPS zone, accumule it
4128 if (isset($this->tree[4]) and isset($this->tree[3])) {
4129 if (($this->tree[4] == "GROUP") and ($this->tree[3] == "GROUPS")) {
4130 if (!isset($this->temp)) {
4131 $this->temp = "";
4133 $this->temp .= "<".$tagName.">";
4138 function startElementGroupings($parser, $tagName, $attrs) {
4139 //Refresh properties
4140 $this->level++;
4141 $this->tree[$this->level] = $tagName;
4143 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
4144 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
4145 //} //Debug
4147 //Output something to avoid browser timeouts...
4148 backup_flush();
4150 //Check if we are into GROUPINGS zone
4151 //if ($this->tree[3] == "GROUPINGS") //Debug
4152 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4154 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
4155 if (isset($this->tree[4]) and isset($this->tree[3])) {
4156 if (($this->tree[4] == "GROUPING") and ($this->tree[3] == "GROUPINGS")) {
4157 if (!isset($this->temp)) {
4158 $this->temp = "";
4160 $this->temp .= "<".$tagName.">";
4165 function startElementGroupingsGroups($parser, $tagName, $attrs) {
4166 //Refresh properties
4167 $this->level++;
4168 $this->tree[$this->level] = $tagName;
4170 //if ($tagName == "GROUPINGGROUP" && $this->tree[3] == "GROUPINGSGROUPS") { //Debug
4171 // echo "<P>GROUPINGSGROUP: ".strftime ("%X",time()),"-"; //Debug
4172 //} //Debug
4174 //Output something to avoid browser timeouts...
4175 backup_flush();
4177 //Check if we are into GROUPINGSGROUPS zone
4178 //if ($this->tree[3] == "GROUPINGSGROUPS") //Debug
4179 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4181 //If we are under a GROUPINGGROUP tag under a GROUPINGSGROUPS zone, accumule it
4182 if (isset($this->tree[4]) and isset($this->tree[3])) {
4183 if (($this->tree[4] == "GROUPINGGROUP") and ($this->tree[3] == "GROUPINGSGROUPS")) {
4184 if (!isset($this->temp)) {
4185 $this->temp = "";
4187 $this->temp .= "<".$tagName.">";
4192 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
4193 function startElementEvents($parser, $tagName, $attrs) {
4194 //Refresh properties
4195 $this->level++;
4196 $this->tree[$this->level] = $tagName;
4198 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
4199 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
4200 //} //Debug
4202 //Output something to avoid browser timeouts...
4203 backup_flush();
4205 //Check if we are into EVENTS zone
4206 //if ($this->tree[3] == "EVENTS") //Debug
4207 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4209 //If we are under a EVENT tag under a EVENTS zone, accumule it
4210 if (isset($this->tree[4]) and isset($this->tree[3])) {
4211 if (($this->tree[4] == "EVENT") and ($this->tree[3] == "EVENTS")) {
4212 if (!isset($this->temp)) {
4213 $this->temp = "";
4215 $this->temp .= "<".$tagName.">";
4220 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
4221 function startElementModules($parser, $tagName, $attrs) {
4222 //Refresh properties
4223 $this->level++;
4224 $this->tree[$this->level] = $tagName;
4226 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
4227 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
4228 //} //Debug
4230 //Output something to avoid browser timeouts...
4231 backup_flush();
4233 //Check if we are into MODULES zone
4234 //if ($this->tree[3] == "MODULES") //Debug
4235 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4237 //If we are under a MOD tag under a MODULES zone, accumule it
4238 if (isset($this->tree[4]) and isset($this->tree[3])) {
4239 if (($this->tree[4] == "MOD") and ($this->tree[3] == "MODULES")) {
4240 if (!isset($this->temp)) {
4241 $this->temp = "";
4243 $this->temp .= "<".$tagName.">";
4248 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
4249 function startElementLogs($parser, $tagName, $attrs) {
4250 //Refresh properties
4251 $this->level++;
4252 $this->tree[$this->level] = $tagName;
4254 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
4255 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
4256 //} //Debug
4258 //Output something to avoid browser timeouts...
4259 backup_flush();
4261 //Check if we are into LOGS zone
4262 //if ($this->tree[3] == "LOGS") //Debug
4263 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4265 //If we are under a LOG tag under a LOGS zone, accumule it
4266 if (isset($this->tree[4]) and isset($this->tree[3])) {
4267 if (($this->tree[4] == "LOG") and ($this->tree[3] == "LOGS")) {
4268 if (!isset($this->temp)) {
4269 $this->temp = "";
4271 $this->temp .= "<".$tagName.">";
4276 //This is the startTag default handler we use when todo is undefined
4277 function startElement($parser, $tagName, $attrs) {
4278 $this->level++;
4279 $this->tree[$this->level] = $tagName;
4281 //Output something to avoid browser timeouts...
4282 backup_flush();
4284 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4287 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
4288 function endElementInfo($parser, $tagName) {
4289 //Check if we are into INFO zone
4290 if ($this->tree[2] == "INFO") {
4291 //if (trim($this->content)) //Debug
4292 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4293 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4294 //Dependig of different combinations, do different things
4295 if ($this->level == 3) {
4296 switch ($tagName) {
4297 case "NAME":
4298 $this->info->backup_name = $this->getContents();
4299 break;
4300 case "MOODLE_VERSION":
4301 $this->info->backup_moodle_version = $this->getContents();
4302 break;
4303 case "MOODLE_RELEASE":
4304 $this->info->backup_moodle_release = $this->getContents();
4305 break;
4306 case "BACKUP_VERSION":
4307 $this->info->backup_backup_version = $this->getContents();
4308 break;
4309 case "BACKUP_RELEASE":
4310 $this->info->backup_backup_release = $this->getContents();
4311 break;
4312 case "DATE":
4313 $this->info->backup_date = $this->getContents();
4314 break;
4315 case "ORIGINAL_WWWROOT":
4316 $this->info->original_wwwroot = $this->getContents();
4317 break;
4318 case "MNET_EXTERNALUSERS":
4319 $this->info->mnet_externalusers = $this->getContents();
4320 break;
4323 if ($this->tree[3] == "DETAILS") {
4324 if ($this->level == 4) {
4325 switch ($tagName) {
4326 case "METACOURSE":
4327 $this->info->backup_metacourse = $this->getContents();
4328 break;
4329 case "USERS":
4330 $this->info->backup_users = $this->getContents();
4331 break;
4332 case "LOGS":
4333 $this->info->backup_logs = $this->getContents();
4334 break;
4335 case "USERFILES":
4336 $this->info->backup_user_files = $this->getContents();
4337 break;
4338 case "COURSEFILES":
4339 $this->info->backup_course_files = $this->getContents();
4340 break;
4341 case "SITEFILES":
4342 $this->info->backup_site_files = $this->getContents();
4343 break;
4344 case "MESSAGES":
4345 $this->info->backup_messages = $this->getContents();
4346 break;
4347 case 'BLOCKFORMAT':
4348 $this->info->backup_block_format = $this->getContents();
4349 break;
4352 if ($this->level == 5) {
4353 switch ($tagName) {
4354 case "NAME":
4355 $this->info->tempName = $this->getContents();
4356 break;
4357 case "INCLUDED":
4358 $this->info->mods[$this->info->tempName]->backup = $this->getContents();
4359 break;
4360 case "USERINFO":
4361 $this->info->mods[$this->info->tempName]->userinfo = $this->getContents();
4362 break;
4365 if ($this->level == 7) {
4366 switch ($tagName) {
4367 case "ID":
4368 $this->info->tempId = $this->getContents();
4369 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->id = $this->info->tempId;
4370 break;
4371 case "NAME":
4372 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->name = $this->getContents();
4373 break;
4374 case "INCLUDED":
4375 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->backup = $this->getContents();
4376 break;
4377 case "USERINFO":
4378 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->userinfo = $this->getContents();
4379 break;
4385 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
4386 //Speed up a lot (avoid parse all)
4387 if ($tagName == "INFO") {
4388 $this->finished = true;
4391 //Clear things
4392 $this->tree[$this->level] = "";
4393 $this->level--;
4394 $this->content = "";
4398 function endElementRoles($parser, $tagName) {
4399 //Check if we are into INFO zone
4400 if ($this->tree[2] == "ROLES") {
4402 if ($this->tree[3] == "ROLE") {
4403 if ($this->level == 4) {
4404 switch ($tagName) {
4405 case "NAME":
4406 $this->info->tempname = $this->getContents();
4408 break;
4409 case "SHORTNAME":
4410 $this->info->tempshortname = $this->getContents();
4411 break;
4412 case "ID": // this is the old id
4413 $this->info->tempid = $this->getContents();
4414 break;
4417 if ($this->level == 6) {
4418 switch ($tagName) {
4419 case "NAME":
4420 $this->info->roles[$this->info->tempid]->name = $this->info->tempname;
4421 $this->info->roles[$this->info->tempid]->shortname = $this->info->tempshortname;
4423 $this->info->tempcapname = $this->getContents();
4424 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->name = $this->getContents();
4425 break;
4426 case "PERMISSION":
4427 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->permission = $this->getContents();
4428 break;
4429 case "TIMEMODIFIED":
4430 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->timemodified = $this->getContents();
4431 break;
4432 case "MODIFIERID":
4433 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->modifierid = $this->getContents();
4434 break;
4440 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
4441 //Speed up a lot (avoid parse all)
4442 if ($tagName == "ROLES") {
4443 $this->finished = true;
4446 //Clear things
4447 $this->tree[$this->level] = "";
4448 $this->level--;
4449 $this->content = "";
4453 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
4454 function endElementCourseHeader($parser, $tagName) {
4455 //Check if we are into COURSE_HEADER zone
4456 if ($this->tree[3] == "HEADER") {
4457 //if (trim($this->content)) //Debug
4458 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4459 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4460 //Dependig of different combinations, do different things
4461 if ($this->level == 4) {
4462 switch ($tagName) {
4463 case "ID":
4464 $this->info->course_id = $this->getContents();
4465 break;
4466 case "PASSWORD":
4467 $this->info->course_password = $this->getContents();
4468 break;
4469 case "FULLNAME":
4470 $this->info->course_fullname = $this->getContents();
4471 break;
4472 case "SHORTNAME":
4473 $this->info->course_shortname = $this->getContents();
4474 break;
4475 case "IDNUMBER":
4476 $this->info->course_idnumber = $this->getContents();
4477 break;
4478 case "SUMMARY":
4479 $this->info->course_summary = $this->getContents();
4480 break;
4481 case "FORMAT":
4482 $this->info->course_format = $this->getContents();
4483 break;
4484 case "SHOWGRADES":
4485 $this->info->course_showgrades = $this->getContents();
4486 break;
4487 case "BLOCKINFO":
4488 $this->info->blockinfo = $this->getContents();
4489 break;
4490 case "NEWSITEMS":
4491 $this->info->course_newsitems = $this->getContents();
4492 break;
4493 case "TEACHER":
4494 $this->info->course_teacher = $this->getContents();
4495 break;
4496 case "TEACHERS":
4497 $this->info->course_teachers = $this->getContents();
4498 break;
4499 case "STUDENT":
4500 $this->info->course_student = $this->getContents();
4501 break;
4502 case "STUDENTS":
4503 $this->info->course_students = $this->getContents();
4504 break;
4505 case "GUEST":
4506 $this->info->course_guest = $this->getContents();
4507 break;
4508 case "STARTDATE":
4509 $this->info->course_startdate = $this->getContents();
4510 break;
4511 case "NUMSECTIONS":
4512 $this->info->course_numsections = $this->getContents();
4513 break;
4514 //case "SHOWRECENT": INFO: This is out in 1.3
4515 // $this->info->course_showrecent = $this->getContents();
4516 // break;
4517 case "MAXBYTES":
4518 $this->info->course_maxbytes = $this->getContents();
4519 break;
4520 case "SHOWREPORTS":
4521 $this->info->course_showreports = $this->getContents();
4522 break;
4523 case "GROUPMODE":
4524 $this->info->course_groupmode = $this->getContents();
4525 break;
4526 case "GROUPMODEFORCE":
4527 $this->info->course_groupmodeforce = $this->getContents();
4528 break;
4529 case "DEFAULTGROUPINGID":
4530 $this->info->course_defaultgroupingid = $this->getContents();
4531 break;
4532 case "LANG":
4533 $this->info->course_lang = $this->getContents();
4534 break;
4535 case "THEME":
4536 $this->info->course_theme = $this->getContents();
4537 break;
4538 case "COST":
4539 $this->info->course_cost = $this->getContents();
4540 break;
4541 case "CURRENCY":
4542 $this->info->course_currency = $this->getContents();
4543 break;
4544 case "MARKER":
4545 $this->info->course_marker = $this->getContents();
4546 break;
4547 case "VISIBLE":
4548 $this->info->course_visible = $this->getContents();
4549 break;
4550 case "HIDDENSECTIONS":
4551 $this->info->course_hiddensections = $this->getContents();
4552 break;
4553 case "TIMECREATED":
4554 $this->info->course_timecreated = $this->getContents();
4555 break;
4556 case "TIMEMODIFIED":
4557 $this->info->course_timemodified = $this->getContents();
4558 break;
4559 case "METACOURSE":
4560 $this->info->course_metacourse = $this->getContents();
4561 break;
4562 case "EXPIRENOTIFY":
4563 $this->info->course_expirynotify = $this->getContents();
4564 break;
4565 case "NOTIFYSTUDENTS":
4566 $this->info->course_notifystudents = $this->getContents();
4567 break;
4568 case "EXPIRYTHRESHOLD":
4569 $this->info->course_expirythreshold = $this->getContents();
4570 break;
4571 case "ENROLLABLE":
4572 $this->info->course_enrollable = $this->getContents();
4573 break;
4574 case "ENROLSTARTDATE":
4575 $this->info->course_enrolstartdate = $this->getContents();
4576 break;
4577 case "ENROLENDDATE":
4578 $this->info->course_enrolenddate = $this->getContents();
4579 break;
4580 case "ENROLPERIOD":
4581 $this->info->course_enrolperiod = $this->getContents();
4582 break;
4585 if ($this->tree[4] == "CATEGORY") {
4586 if ($this->level == 5) {
4587 switch ($tagName) {
4588 case "ID":
4589 $this->info->category->id = $this->getContents();
4590 break;
4591 case "NAME":
4592 $this->info->category->name = $this->getContents();
4593 break;
4598 if ($this->tree[4] == "ROLES_ASSIGNMENTS") {
4599 if ($this->level == 6) {
4600 switch ($tagName) {
4601 case "NAME":
4602 $this->info->tempname = $this->getContents();
4603 break;
4604 case "SHORTNAME":
4605 $this->info->tempshortname = $this->getContents();
4606 break;
4607 case "ID":
4608 $this->info->tempid = $this->getContents();
4609 break;
4613 if ($this->level == 8) {
4614 switch ($tagName) {
4615 case "USERID":
4616 $this->info->roleassignments[$this->info->tempid]->name = $this->info->tempname;
4617 $this->info->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
4618 $this->info->tempuser = $this->getContents();
4619 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
4620 break;
4621 case "HIDDEN":
4622 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
4623 break;
4624 case "TIMESTART":
4625 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
4626 break;
4627 case "TIMEEND":
4628 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
4629 break;
4630 case "TIMEMODIFIED":
4631 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
4632 break;
4633 case "MODIFIERID":
4634 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
4635 break;
4636 case "ENROL":
4637 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
4638 break;
4639 case "SORTORDER":
4640 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
4641 break;
4645 } /// ends role_assignments
4647 if ($this->tree[4] == "ROLES_OVERRIDES") {
4648 if ($this->level == 6) {
4649 switch ($tagName) {
4650 case "NAME":
4651 $this->info->tempname = $this->getContents();
4652 break;
4653 case "SHORTNAME":
4654 $this->info->tempshortname = $this->getContents();
4655 break;
4656 case "ID":
4657 $this->info->tempid = $this->getContents();
4658 break;
4662 if ($this->level == 8) {
4663 switch ($tagName) {
4664 case "NAME":
4665 $this->info->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
4666 $this->info->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
4667 $this->info->tempname = $this->getContents(); // change to name of capability
4668 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
4669 break;
4670 case "PERMISSION":
4671 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
4672 break;
4673 case "TIMEMODIFIED":
4674 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
4675 break;
4676 case "MODIFIERID":
4677 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
4678 break;
4681 } /// ends role_overrides
4684 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
4685 //Speed up a lot (avoid parse all)
4686 if ($tagName == "HEADER") {
4687 $this->finished = true;
4690 //Clear things
4691 $this->tree[$this->level] = "";
4692 $this->level--;
4693 $this->content = "";
4697 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
4698 function endElementBlocks($parser, $tagName) {
4699 //Check if we are into BLOCKS zone
4700 if ($this->tree[3] == 'BLOCKS') {
4701 //if (trim($this->content)) //Debug
4702 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4703 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4704 //Dependig of different combinations, do different things
4705 if ($this->level == 4) {
4706 switch ($tagName) {
4707 case 'BLOCK':
4708 //We've finalized a block, get it
4709 $this->info->instances[] = $this->info->tempinstance;
4710 unset($this->info->tempinstance);
4711 break;
4712 default:
4713 die($tagName);
4716 if ($this->level == 5) {
4717 switch ($tagName) {
4718 case 'ID':
4719 $this->info->tempinstance->id = $this->getContents();
4720 case 'NAME':
4721 $this->info->tempinstance->name = $this->getContents();
4722 break;
4723 case 'PAGEID':
4724 $this->info->tempinstance->pageid = $this->getContents();
4725 break;
4726 case 'PAGETYPE':
4727 $this->info->tempinstance->pagetype = $this->getContents();
4728 break;
4729 case 'POSITION':
4730 $this->info->tempinstance->position = $this->getContents();
4731 break;
4732 case 'WEIGHT':
4733 $this->info->tempinstance->weight = $this->getContents();
4734 break;
4735 case 'VISIBLE':
4736 $this->info->tempinstance->visible = $this->getContents();
4737 break;
4738 case 'CONFIGDATA':
4739 $this->info->tempinstance->configdata = $this->getContents();
4740 break;
4741 default:
4742 break;
4746 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
4747 if ($this->level == 7) {
4748 switch ($tagName) {
4749 case "NAME":
4750 $this->info->tempname = $this->getContents();
4751 break;
4752 case "SHORTNAME":
4753 $this->info->tempshortname = $this->getContents();
4754 break;
4755 case "ID":
4756 $this->info->tempid = $this->getContents(); // temp roleid
4757 break;
4761 if ($this->level == 9) {
4763 switch ($tagName) {
4764 case "USERID":
4765 $this->info->tempinstance->roleassignments[$this->info->tempid]->name = $this->info->tempname;
4767 $this->info->tempinstance->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
4769 $this->info->tempuser = $this->getContents();
4771 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
4772 break;
4773 case "HIDDEN":
4774 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
4775 break;
4776 case "TIMESTART":
4777 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
4778 break;
4779 case "TIMEEND":
4780 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
4781 break;
4782 case "TIMEMODIFIED":
4783 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
4784 break;
4785 case "MODIFIERID":
4786 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
4787 break;
4788 case "ENROL":
4789 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
4790 break;
4791 case "SORTORDER":
4792 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
4793 break;
4797 } /// ends role_assignments
4799 if ($this->tree[5] == "ROLES_OVERRIDES") {
4800 if ($this->level == 7) {
4801 switch ($tagName) {
4802 case "NAME":
4803 $this->info->tempname = $this->getContents();
4804 break;
4805 case "SHORTNAME":
4806 $this->info->tempshortname = $this->getContents();
4807 break;
4808 case "ID":
4809 $this->info->tempid = $this->getContents(); // temp roleid
4810 break;
4814 if ($this->level == 9) {
4815 switch ($tagName) {
4816 case "NAME":
4818 $this->info->tempinstance->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
4819 $this->info->tempinstance->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
4820 $this->info->tempname = $this->getContents(); // change to name of capability
4821 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
4822 break;
4823 case "PERMISSION":
4824 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
4825 break;
4826 case "TIMEMODIFIED":
4827 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
4828 break;
4829 case "MODIFIERID":
4830 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
4831 break;
4834 } /// ends role_overrides
4837 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
4838 //Speed up a lot (avoid parse all)
4839 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
4840 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
4841 if ($this->tree[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
4842 $this->finished = true;
4845 //Clear things
4846 $this->tree[$this->level] = '';
4847 $this->level--;
4848 $this->content = "";
4851 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
4852 function endElementSections($parser, $tagName) {
4853 //Check if we are into SECTIONS zone
4854 if ($this->tree[3] == "SECTIONS") {
4855 //if (trim($this->content)) //Debug
4856 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4857 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4858 //Dependig of different combinations, do different things
4859 if ($this->level == 4) {
4860 switch ($tagName) {
4861 case "SECTION":
4862 //We've finalized a section, get it
4863 $this->info->sections[$this->info->tempsection->id] = $this->info->tempsection;
4864 unset($this->info->tempsection);
4867 if ($this->level == 5) {
4868 switch ($tagName) {
4869 case "ID":
4870 $this->info->tempsection->id = $this->getContents();
4871 break;
4872 case "NUMBER":
4873 $this->info->tempsection->number = $this->getContents();
4874 break;
4875 case "SUMMARY":
4876 $this->info->tempsection->summary = $this->getContents();
4877 break;
4878 case "VISIBLE":
4879 $this->info->tempsection->visible = $this->getContents();
4880 break;
4883 if ($this->level == 6) {
4884 switch ($tagName) {
4885 case "MOD":
4886 if (!isset($this->info->tempmod->groupmode)) {
4887 $this->info->tempmod->groupmode = 0;
4889 if (!isset($this->info->tempmod->groupingid)) {
4890 $this->info->tempmod->groupingid = 0;
4892 if (!isset($this->info->tempmod->groupmembersonly)) {
4893 $this->info->tempmod->groupmembersonly = 0;
4896 //We've finalized a mod, get it
4897 $this->info->tempsection->mods[$this->info->tempmod->id]->type =
4898 $this->info->tempmod->type;
4899 $this->info->tempsection->mods[$this->info->tempmod->id]->instance =
4900 $this->info->tempmod->instance;
4901 $this->info->tempsection->mods[$this->info->tempmod->id]->added =
4902 $this->info->tempmod->added;
4903 $this->info->tempsection->mods[$this->info->tempmod->id]->score =
4904 $this->info->tempmod->score;
4905 $this->info->tempsection->mods[$this->info->tempmod->id]->indent =
4906 $this->info->tempmod->indent;
4907 $this->info->tempsection->mods[$this->info->tempmod->id]->visible =
4908 $this->info->tempmod->visible;
4909 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmode =
4910 $this->info->tempmod->groupmode;
4911 $this->info->tempsection->mods[$this->info->tempmod->id]->groupingid =
4912 $this->info->tempmod->groupingid;
4913 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmembersonly =
4914 $this->info->tempmod->groupmembersonly;
4916 unset($this->info->tempmod);
4919 if ($this->level == 7) {
4920 switch ($tagName) {
4921 case "ID":
4922 $this->info->tempmod->id = $this->getContents();
4923 break;
4924 case "TYPE":
4925 $this->info->tempmod->type = $this->getContents();
4926 break;
4927 case "INSTANCE":
4928 $this->info->tempmod->instance = $this->getContents();
4929 break;
4930 case "ADDED":
4931 $this->info->tempmod->added = $this->getContents();
4932 break;
4933 case "SCORE":
4934 $this->info->tempmod->score = $this->getContents();
4935 break;
4936 case "INDENT":
4937 $this->info->tempmod->indent = $this->getContents();
4938 break;
4939 case "VISIBLE":
4940 $this->info->tempmod->visible = $this->getContents();
4941 break;
4942 case "GROUPMODE":
4943 $this->info->tempmod->groupmode = $this->getContents();
4944 break;
4945 case "GROUPINGID":
4946 $this->info->tempmod->groupingid = $this->getContents();
4947 break;
4948 case "GROUPMEMBERSONLY":
4949 $this->info->tempmod->groupmembersonly = $this->getContents();
4950 break;
4951 default:
4952 break;
4956 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_ASSIGNMENTS") {
4958 if ($this->level == 9) {
4959 switch ($tagName) {
4960 case "NAME":
4961 $this->info->tempname = $this->getContents();
4962 break;
4963 case "SHORTNAME":
4964 $this->info->tempshortname = $this->getContents();
4965 break;
4966 case "ID":
4967 $this->info->tempid = $this->getContents(); // temp roleid
4968 break;
4972 if ($this->level == 11) {
4973 switch ($tagName) {
4974 case "USERID":
4975 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->name = $this->info->tempname;
4977 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
4979 $this->info->tempuser = $this->getContents();
4981 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
4982 break;
4983 case "HIDDEN":
4984 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
4985 break;
4986 case "TIMESTART":
4987 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
4988 break;
4989 case "TIMEEND":
4990 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
4991 break;
4992 case "TIMEMODIFIED":
4993 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
4994 break;
4995 case "MODIFIERID":
4996 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
4997 break;
4998 case "ENROL":
4999 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5000 break;
5001 case "SORTORDER":
5002 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5003 break;
5007 } /// ends role_assignments
5009 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_OVERRIDES") {
5010 if ($this->level == 9) {
5011 switch ($tagName) {
5012 case "NAME":
5013 $this->info->tempname = $this->getContents();
5014 break;
5015 case "SHORTNAME":
5016 $this->info->tempshortname = $this->getContents();
5017 break;
5018 case "ID":
5019 $this->info->tempid = $this->getContents(); // temp roleid
5020 break;
5024 if ($this->level == 11) {
5025 switch ($tagName) {
5026 case "NAME":
5028 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5029 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5030 $this->info->tempname = $this->getContents(); // change to name of capability
5031 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5032 break;
5033 case "PERMISSION":
5034 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5035 break;
5036 case "TIMEMODIFIED":
5037 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5038 break;
5039 case "MODIFIERID":
5040 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5041 break;
5044 } /// ends role_overrides
5048 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
5049 //Speed up a lot (avoid parse all)
5050 if ($tagName == "SECTIONS") {
5051 $this->finished = true;
5054 //Clear things
5055 $this->tree[$this->level] = "";
5056 $this->level--;
5057 $this->content = "";
5061 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
5062 function endElementFormatData($parser, $tagName) {
5063 //Check if we are into FORMATDATA zone
5064 if ($this->tree[3] == 'FORMATDATA') {
5065 if (!isset($this->temp)) {
5066 $this->temp = '';
5068 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5071 if($tagName=='FORMATDATA') {
5072 //Did we have any data? If not don't bother
5073 if($this->temp!='<FORMATDATA></FORMATDATA>') {
5074 //Prepend XML standard header to info gathered
5075 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5076 $this->temp='';
5078 //Call to xmlize for this portion of xml data (the FORMATDATA block)
5079 $this->info->format_data = xmlize($xml_data,0);
5081 //Stop parsing at end of FORMATDATA
5082 $this->finished=true;
5085 //Clear things
5086 $this->tree[$this->level] = "";
5087 $this->level--;
5088 $this->content = "";
5091 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
5092 function endElementMetacourse($parser, $tagName) {
5093 //Check if we are into METACOURSE zone
5094 if ($this->tree[3] == 'METACOURSE') {
5095 //if (trim($this->content)) //Debug
5096 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5097 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5098 //Dependig of different combinations, do different things
5099 if ($this->level == 5) {
5100 switch ($tagName) {
5101 case 'CHILD':
5102 //We've finalized a child, get it
5103 $this->info->childs[] = $this->info->tempmeta;
5104 unset($this->info->tempmeta);
5105 break;
5106 case 'PARENT':
5107 //We've finalized a parent, get it
5108 $this->info->parents[] = $this->info->tempmeta;
5109 unset($this->info->tempmeta);
5110 break;
5111 default:
5112 die($tagName);
5115 if ($this->level == 6) {
5116 switch ($tagName) {
5117 case 'ID':
5118 $this->info->tempmeta->id = $this->getContents();
5119 break;
5120 case 'IDNUMBER':
5121 $this->info->tempmeta->idnumber = $this->getContents();
5122 break;
5123 case 'SHORTNAME':
5124 $this->info->tempmeta->shortname = $this->getContents();
5125 break;
5130 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
5131 //Speed up a lot (avoid parse all)
5132 if ($this->tree[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
5133 $this->finished = true;
5136 //Clear things
5137 $this->tree[$this->level] = '';
5138 $this->level--;
5139 $this->content = "";
5142 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5143 function endElementGradebook($parser, $tagName) {
5144 //Check if we are into GRADEBOOK zone
5145 if ($this->tree[3] == "GRADEBOOK") {
5146 //if (trim($this->content)) //Debug
5147 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5148 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
5149 //Acumulate data to info (content + close tag)
5150 //Reconvert: strip htmlchars again and trim to generate xml data
5151 if (!isset($this->temp)) {
5152 $this->temp = "";
5154 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5155 // We have finished outcome, grade_category or grade_item, reset accumulated
5156 // data because they are close tags
5157 if ($this->level == 4) {
5158 $this->temp = "";
5160 //If we've finished a grade item, xmlize it an save to db
5161 if (($this->level == 5) and ($tagName == "GRADE_ITEM")) {
5162 //Prepend XML standard header to info gathered
5163 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5164 //Call to xmlize for this portion of xml data (one PREFERENCE)
5165 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5166 $data = xmlize($xml_data,0);
5167 //echo strftime ("%X",time())."<p>"; //Debug
5168 //traverse_xmlize($data); //Debug
5169 //print_object ($GLOBALS['traverse_array']); //Debug
5170 //$GLOBALS['traverse_array']=""; //Debug
5171 //Now, save data to db. We'll use it later
5172 //Get id and status from data
5173 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
5174 $this->counter++;
5175 //Save to db
5177 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items', $item_id,
5178 null,$data);
5179 //Create returning info
5180 $this->info = $this->counter;
5181 //Reset temp
5183 unset($this->temp);
5186 //If we've finished a grade_category, xmlize it an save to db
5187 if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
5188 //Prepend XML standard header to info gathered
5189 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5190 //Call to xmlize for this portion of xml data (one CATECORY)
5191 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5192 $data = xmlize($xml_data,0);
5193 //echo strftime ("%X",time())."<p>"; //Debug
5194 //traverse_xmlize($data); //Debug
5195 //print_object ($GLOBALS['traverse_array']); //Debug
5196 //$GLOBALS['traverse_array']=""; //Debug
5197 //Now, save data to db. We'll use it later
5198 //Get id and status from data
5199 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5200 $this->counter++;
5201 //Save to db
5202 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories' ,$category_id,
5203 null,$data);
5204 //Create returning info
5205 $this->info = $this->counter;
5206 //Reset temp
5207 unset($this->temp);
5210 //If we've finished a grade_outcome, xmlize it an save to db
5211 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME")) {
5212 //Prepend XML standard header to info gathered
5213 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5214 //Call to xmlize for this portion of xml data (one CATECORY)
5215 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5216 $data = xmlize($xml_data,0);
5217 //echo strftime ("%X",time())."<p>"; //Debug
5218 //traverse_xmlize($data); //Debug
5219 //print_object ($GLOBALS['traverse_array']); //Debug
5220 //$GLOBALS['traverse_array']=""; //Debug
5221 //Now, save data to db. We'll use it later
5222 //Get id and status from data
5223 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
5224 $this->counter++;
5225 //Save to db
5226 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes' ,$outcome_id,
5227 null,$data);
5228 //Create returning info
5229 $this->info = $this->counter;
5230 //Reset temp
5231 unset($this->temp);
5234 //If we've finished a grade_outcomes_course, xmlize it an save to db
5235 if (($this->level == 5) and ($tagName == "GRADE_OUTCOMES_COURSE")) {
5236 //Prepend XML standard header to info gathered
5237 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5238 //Call to xmlize for this portion of xml data (one CATECORY)
5239 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5240 $data = xmlize($xml_data,0);
5241 //echo strftime ("%X",time())."<p>"; //Debug
5242 //traverse_xmlize($data); //Debug
5243 //print_object ($GLOBALS['traverse_array']); //Debug
5244 //$GLOBALS['traverse_array']=""; //Debug
5245 //Now, save data to db. We'll use it later
5246 //Get id and status from data
5247 $outcomes_course_id = $data["GRADE_OUTCOMES_COURSE"]["#"]["ID"]["0"]["#"];
5248 $this->counter++;
5249 //Save to db
5250 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_courses' ,$outcomes_course_id,
5251 null,$data);
5252 //Create returning info
5253 $this->info = $this->counter;
5254 //Reset temp
5255 unset($this->temp);
5258 if (($this->level == 5) and ($tagName == "GRADE_CATEGORIES_HISTORY")) {
5259 //Prepend XML standard header to info gathered
5260 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5261 //Call to xmlize for this portion of xml data (one PREFERENCE)
5262 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5263 $data = xmlize($xml_data,0);
5264 //echo strftime ("%X",time())."<p>"; //Debug
5265 //traverse_xmlize($data); //Debug
5266 //print_object ($GLOBALS['traverse_array']); //Debug
5267 //$GLOBALS['traverse_array']=""; //Debug
5268 //Now, save data to db. We'll use it later
5269 //Get id and status from data
5270 $id = $data["GRADE_CATEGORIES_HISTORY"]["#"]["ID"]["0"]["#"];
5271 $this->counter++;
5272 //Save to db
5274 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories_history', $id,
5275 null,$data);
5276 //Create returning info
5277 $this->info = $this->counter;
5278 //Reset temp
5280 unset($this->temp);
5283 if (($this->level == 5) and ($tagName == "GRADE_GRADES_HISTORY")) {
5284 //Prepend XML standard header to info gathered
5285 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5286 //Call to xmlize for this portion of xml data (one PREFERENCE)
5287 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5288 $data = xmlize($xml_data,0);
5289 //echo strftime ("%X",time())."<p>"; //Debug
5290 //traverse_xmlize($data); //Debug
5291 //print_object ($GLOBALS['traverse_array']); //Debug
5292 //$GLOBALS['traverse_array']=""; //Debug
5293 //Now, save data to db. We'll use it later
5294 //Get id and status from data
5295 $id = $data["GRADE_GRADES_HISTORY"]["#"]["ID"]["0"]["#"];
5296 $this->counter++;
5297 //Save to db
5299 $status = backup_putid($this->preferences->backup_unique_code, 'grade_grades_history', $id,
5300 null,$data);
5301 //Create returning info
5302 $this->info = $this->counter;
5303 //Reset temp
5305 unset($this->temp);
5308 if (($this->level == 5) and ($tagName == "GRADE_ITEM_HISTORY")) {
5309 //Prepend XML standard header to info gathered
5310 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5311 //Call to xmlize for this portion of xml data (one PREFERENCE)
5312 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5313 $data = xmlize($xml_data,0);
5314 //echo strftime ("%X",time())."<p>"; //Debug
5315 //traverse_xmlize($data); //Debug
5316 //print_object ($GLOBALS['traverse_array']); //Debug
5317 //$GLOBALS['traverse_array']=""; //Debug
5318 //Now, save data to db. We'll use it later
5319 //Get id and status from data
5320 $id = $data["GRADE_ITEM_HISTORY"]["#"]["ID"]["0"]["#"];
5321 $this->counter++;
5322 //Save to db
5324 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items_history', $id,
5325 null,$data);
5326 //Create returning info
5327 $this->info = $this->counter;
5328 //Reset temp
5330 unset($this->temp);
5333 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME_HISTORY")) {
5334 //Prepend XML standard header to info gathered
5335 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5336 //Call to xmlize for this portion of xml data (one PREFERENCE)
5337 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5338 $data = xmlize($xml_data,0);
5339 //echo strftime ("%X",time())."<p>"; //Debug
5340 //traverse_xmlize($data); //Debug
5341 //print_object ($GLOBALS['traverse_array']); //Debug
5342 //$GLOBALS['traverse_array']=""; //Debug
5343 //Now, save data to db. We'll use it later
5344 //Get id and status from data
5345 $id = $data["GRADE_OUTCOME_HISTORY"]["#"]["ID"]["0"]["#"];
5346 $this->counter++;
5347 //Save to db
5349 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_history', $id,
5350 null,$data);
5351 //Create returning info
5352 $this->info = $this->counter;
5353 //Reset temp
5355 unset($this->temp);
5359 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
5360 //Speed up a lot (avoid parse all)
5361 if ($tagName == "GRADEBOOK" and $this->level == 3) {
5362 $this->finished = true;
5363 $this->counter = 0;
5366 //Clear things
5367 $this->tree[$this->level] = "";
5368 $this->level--;
5369 $this->content = "";
5373 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
5374 function endElementUsers($parser, $tagName) {
5375 global $CFG;
5376 //Check if we are into USERS zone
5377 if ($this->tree[3] == "USERS") {
5378 //if (trim($this->content)) //Debug
5379 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5380 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5381 //Dependig of different combinations, do different things
5382 if ($this->level == 4) {
5383 switch ($tagName) {
5384 case "USER":
5385 //Increment counter
5386 $this->counter++;
5387 //Save to db, only save if record not already exist
5388 // if there already is an new_id for this entry, just use that new_id?
5389 $newuser = backup_getid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id);
5390 if (isset($newuser->new_id)) {
5391 $newid = $newuser->new_id;
5392 } else {
5393 $newid = null;
5396 backup_putid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id,
5397 $newid,$this->info->tempuser);
5399 //Do some output
5400 if ($this->counter % 10 == 0) {
5401 if (!defined('RESTORE_SILENTLY')) {
5402 echo ".";
5403 if ($this->counter % 200 == 0) {
5404 echo "<br />";
5407 backup_flush(300);
5410 //Delete temp obejct
5411 unset($this->info->tempuser);
5412 break;
5415 if ($this->level == 5) {
5416 switch ($tagName) {
5417 case "ID":
5418 $this->info->users[$this->getContents()] = $this->getContents();
5419 $this->info->tempuser->id = $this->getContents();
5420 break;
5421 case "AUTH":
5422 $this->info->tempuser->auth = $this->getContents();
5423 break;
5424 case "CONFIRMED":
5425 $this->info->tempuser->confirmed = $this->getContents();
5426 break;
5427 case "POLICYAGREED":
5428 $this->info->tempuser->policyagreed = $this->getContents();
5429 break;
5430 case "DELETED":
5431 $this->info->tempuser->deleted = $this->getContents();
5432 break;
5433 case "USERNAME":
5434 $this->info->tempuser->username = $this->getContents();
5435 break;
5436 case "PASSWORD":
5437 $this->info->tempuser->password = $this->getContents();
5438 break;
5439 case "IDNUMBER":
5440 $this->info->tempuser->idnumber = $this->getContents();
5441 break;
5442 case "FIRSTNAME":
5443 $this->info->tempuser->firstname = $this->getContents();
5444 break;
5445 case "LASTNAME":
5446 $this->info->tempuser->lastname = $this->getContents();
5447 break;
5448 case "EMAIL":
5449 $this->info->tempuser->email = $this->getContents();
5450 break;
5451 case "EMAILSTOP":
5452 $this->info->tempuser->emailstop = $this->getContents();
5453 break;
5454 case "ICQ":
5455 $this->info->tempuser->icq = $this->getContents();
5456 break;
5457 case "SKYPE":
5458 $this->info->tempuser->skype = $this->getContents();
5459 break;
5460 case "AIM":
5461 $this->info->tempuser->aim = $this->getContents();
5462 break;
5463 case "YAHOO":
5464 $this->info->tempuser->yahoo = $this->getContents();
5465 break;
5466 case "MSN":
5467 $this->info->tempuser->msn = $this->getContents();
5468 break;
5469 case "PHONE1":
5470 $this->info->tempuser->phone1 = $this->getContents();
5471 break;
5472 case "PHONE2":
5473 $this->info->tempuser->phone2 = $this->getContents();
5474 break;
5475 case "INSTITUTION":
5476 $this->info->tempuser->institution = $this->getContents();
5477 break;
5478 case "DEPARTMENT":
5479 $this->info->tempuser->department = $this->getContents();
5480 break;
5481 case "ADDRESS":
5482 $this->info->tempuser->address = $this->getContents();
5483 break;
5484 case "CITY":
5485 $this->info->tempuser->city = $this->getContents();
5486 break;
5487 case "COUNTRY":
5488 $this->info->tempuser->country = $this->getContents();
5489 break;
5490 case "LANG":
5491 $this->info->tempuser->lang = $this->getContents();
5492 break;
5493 case "THEME":
5494 $this->info->tempuser->theme = $this->getContents();
5495 break;
5496 case "TIMEZONE":
5497 $this->info->tempuser->timezone = $this->getContents();
5498 break;
5499 case "FIRSTACCESS":
5500 $this->info->tempuser->firstaccess = $this->getContents();
5501 break;
5502 case "LASTACCESS":
5503 $this->info->tempuser->lastaccess = $this->getContents();
5504 break;
5505 case "LASTLOGIN":
5506 $this->info->tempuser->lastlogin = $this->getContents();
5507 break;
5508 case "CURRENTLOGIN":
5509 $this->info->tempuser->currentlogin = $this->getContents();
5510 break;
5511 case "LASTIP":
5512 $this->info->tempuser->lastip = $this->getContents();
5513 break;
5514 case "SECRET":
5515 $this->info->tempuser->secret = $this->getContents();
5516 break;
5517 case "PICTURE":
5518 $this->info->tempuser->picture = $this->getContents();
5519 break;
5520 case "URL":
5521 $this->info->tempuser->url = $this->getContents();
5522 break;
5523 case "DESCRIPTION":
5524 $this->info->tempuser->description = $this->getContents();
5525 break;
5526 case "MAILFORMAT":
5527 $this->info->tempuser->mailformat = $this->getContents();
5528 break;
5529 case "MAILDIGEST":
5530 $this->info->tempuser->maildigest = $this->getContents();
5531 break;
5532 case "MAILDISPLAY":
5533 $this->info->tempuser->maildisplay = $this->getContents();
5534 break;
5535 case "HTMLEDITOR":
5536 $this->info->tempuser->htmleditor = $this->getContents();
5537 break;
5538 case "AJAX":
5539 $this->info->tempuser->ajax = $this->getContents();
5540 break;
5541 case "AUTOSUBSCRIBE":
5542 $this->info->tempuser->autosubscribe = $this->getContents();
5543 break;
5544 case "TRACKFORUMS":
5545 $this->info->tempuser->trackforums = $this->getContents();
5546 break;
5547 case "MNETHOSTURL":
5548 $this->info->tempuser->mnethosturl = $this->getContents();
5549 break;
5550 case "TIMEMODIFIED":
5551 $this->info->tempuser->timemodified = $this->getContents();
5552 break;
5553 default:
5554 break;
5557 if ($this->level == 6 && $this->tree[5]!="ROLES_ASSIGNMENTS" && $this->tree[5]!="ROLES_OVERRIDES") {
5558 switch ($tagName) {
5559 case "ROLE":
5560 //We've finalized a role, get it
5561 $this->info->tempuser->roles[$this->info->temprole->type] = $this->info->temprole;
5562 unset($this->info->temprole);
5563 break;
5564 case "USER_PREFERENCE":
5565 //We've finalized a user_preference, get it
5566 $this->info->tempuser->user_preferences[$this->info->tempuserpreference->name] = $this->info->tempuserpreference;
5567 unset($this->info->tempuserpreference);
5568 break;
5572 if ($this->level == 7) {
5573 switch ($tagName) {
5574 case "TYPE":
5575 $this->info->temprole->type = $this->getContents();
5576 break;
5577 case "AUTHORITY":
5578 $this->info->temprole->authority = $this->getContents();
5579 break;
5580 case "TEA_ROLE":
5581 $this->info->temprole->tea_role = $this->getContents();
5582 break;
5583 case "EDITALL":
5584 $this->info->temprole->editall = $this->getContents();
5585 break;
5586 case "TIMESTART":
5587 $this->info->temprole->timestart = $this->getContents();
5588 break;
5589 case "TIMEEND":
5590 $this->info->temprole->timeend = $this->getContents();
5591 break;
5592 case "TIMEMODIFIED":
5593 $this->info->temprole->timemodified = $this->getContents();
5594 break;
5595 case "TIMESTART":
5596 $this->info->temprole->timestart = $this->getContents();
5597 break;
5598 case "TIMEEND":
5599 $this->info->temprole->timeend = $this->getContents();
5600 break;
5601 case "TIME":
5602 $this->info->temprole->time = $this->getContents();
5603 break;
5604 case "TIMEACCESS":
5605 $this->info->temprole->timeaccess = $this->getContents();
5606 break;
5607 case "ENROL":
5608 $this->info->temprole->enrol = $this->getContents();
5609 break;
5610 case "NAME":
5611 $this->info->tempuserpreference->name = $this->getContents();
5612 break;
5613 case "VALUE":
5614 $this->info->tempuserpreference->value = $this->getContents();
5615 break;
5616 default:
5617 break;
5622 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
5624 if ($this->level == 7) {
5625 switch ($tagName) {
5626 case "NAME":
5627 $this->info->tempname = $this->getContents();
5628 break;
5629 case "SHORTNAME":
5630 $this->info->tempshortname = $this->getContents();
5631 break;
5632 case "ID":
5633 $this->info->tempid = $this->getContents(); // temp roleid
5634 break;
5638 if ($this->level == 9) {
5640 switch ($tagName) {
5641 case "USERID":
5642 $this->info->tempuser->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5644 $this->info->tempuser->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5646 $this->info->tempuserid = $this->getContents();
5648 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->userid = $this->getContents();
5649 break;
5650 case "HIDDEN":
5651 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->hidden = $this->getContents();
5652 break;
5653 case "TIMESTART":
5654 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timestart = $this->getContents();
5655 break;
5656 case "TIMEEND":
5657 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timeend = $this->getContents();
5658 break;
5659 case "TIMEMODIFIED":
5660 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timemodified = $this->getContents();
5661 break;
5662 case "MODIFIERID":
5663 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->modifierid = $this->getContents();
5664 break;
5665 case "ENROL":
5666 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->enrol = $this->getContents();
5667 break;
5668 case "SORTORDER":
5669 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->sortorder = $this->getContents();
5670 break;
5674 } /// ends role_assignments
5676 if ($this->tree[5] == "ROLES_OVERRIDES") {
5677 if ($this->level == 7) {
5678 switch ($tagName) {
5679 case "NAME":
5680 $this->info->tempname = $this->getContents();
5681 break;
5682 case "SHORTNAME":
5683 $this->info->tempshortname = $this->getContents();
5684 break;
5685 case "ID":
5686 $this->info->tempid = $this->getContents(); // temp roleid
5687 break;
5691 if ($this->level == 9) {
5692 switch ($tagName) {
5693 case "NAME":
5695 $this->info->tempuser->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5696 $this->info->tempuser->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5697 $this->info->tempname = $this->getContents(); // change to name of capability
5698 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5699 break;
5700 case "PERMISSION":
5701 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5702 break;
5703 case "TIMEMODIFIED":
5704 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5705 break;
5706 case "MODIFIERID":
5707 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5708 break;
5711 } /// ends role_overrides
5713 } // closes if this->tree[3]=="users"
5715 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
5716 //Speed up a lot (avoid parse all)
5717 if ($tagName == "USERS" and $this->level == 3) {
5718 $this->finished = true;
5719 $this->counter = 0;
5722 //Clear things
5723 $this->tree[$this->level] = "";
5724 $this->level--;
5725 $this->content = "";
5729 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
5730 function endElementMessages($parser, $tagName) {
5731 //Check if we are into MESSAGES zone
5732 if ($this->tree[3] == "MESSAGES") {
5733 //if (trim($this->content)) //Debug
5734 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5735 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
5736 //Acumulate data to info (content + close tag)
5737 //Reconvert: strip htmlchars again and trim to generate xml data
5738 if (!isset($this->temp)) {
5739 $this->temp = "";
5741 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5742 //If we've finished a message, xmlize it an save to db
5743 if (($this->level == 4) and ($tagName == "MESSAGE")) {
5744 //Prepend XML standard header to info gathered
5745 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5746 //Call to xmlize for this portion of xml data (one MESSAGE)
5747 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5748 $data = xmlize($xml_data,0);
5749 //echo strftime ("%X",time())."<p>"; //Debug
5750 //traverse_xmlize($data); //Debug
5751 //print_object ($GLOBALS['traverse_array']); //Debug
5752 //$GLOBALS['traverse_array']=""; //Debug
5753 //Now, save data to db. We'll use it later
5754 //Get id and status from data
5755 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
5756 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
5757 if ($message_status == "READ") {
5758 $table = "message_read";
5759 } else {
5760 $table = "message";
5762 $this->counter++;
5763 //Save to db
5764 $status = backup_putid($this->preferences->backup_unique_code, $table,$message_id,
5765 null,$data);
5766 //Create returning info
5767 $this->info = $this->counter;
5768 //Reset temp
5769 unset($this->temp);
5771 //If we've finished a contact, xmlize it an save to db
5772 if (($this->level == 5) and ($tagName == "CONTACT")) {
5773 //Prepend XML standard header to info gathered
5774 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5775 //Call to xmlize for this portion of xml data (one MESSAGE)
5776 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5777 $data = xmlize($xml_data,0);
5778 //echo strftime ("%X",time())."<p>"; //Debug
5779 //traverse_xmlize($data); //Debug
5780 //print_object ($GLOBALS['traverse_array']); //Debug
5781 //$GLOBALS['traverse_array']=""; //Debug
5782 //Now, save data to db. We'll use it later
5783 //Get id and status from data
5784 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
5785 $this->counter++;
5786 //Save to db
5787 $status = backup_putid($this->preferences->backup_unique_code, 'message_contacts' ,$contact_id,
5788 null,$data);
5789 //Create returning info
5790 $this->info = $this->counter;
5791 //Reset temp
5792 unset($this->temp);
5796 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
5797 //Speed up a lot (avoid parse all)
5798 if ($tagName == "MESSAGES" and $this->level == 3) {
5799 $this->finished = true;
5800 $this->counter = 0;
5803 //Clear things
5804 $this->tree[$this->level] = "";
5805 $this->level--;
5806 $this->content = "";
5810 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
5811 function endElementQuestions($parser, $tagName) {
5812 //Check if we are into QUESTION_CATEGORIES zone
5813 if ($this->tree[3] == "QUESTION_CATEGORIES") {
5814 //if (trim($this->content)) //Debug
5815 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5816 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5817 //Acumulate data to info (content + close tag)
5818 //Reconvert: strip htmlchars again and trim to generate xml data
5819 if (!isset($this->temp)) {
5820 $this->temp = "";
5822 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5823 //If we've finished a mod, xmlize it an save to db
5824 if (($this->level == 4) and ($tagName == "QUESTION_CATEGORY")) {
5825 //Prepend XML standard header to info gathered
5826 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5827 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
5828 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5829 $data = xmlize($xml_data,0);
5830 //echo strftime ("%X",time())."<p>"; //Debug
5831 //traverse_xmlize($data); //Debug
5832 //print_object ($GLOBALS['traverse_array']); //Debug
5833 //$GLOBALS['traverse_array']=""; //Debug
5834 //Now, save data to db. We'll use it later
5835 //Get id from data
5836 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
5837 //Save to db
5838 $status = backup_putid($this->preferences->backup_unique_code,"question_categories",$category_id,
5839 null,$data);
5840 //Create returning info
5841 $ret_info = new object();
5842 $ret_info->id = $category_id;
5843 $this->info[] = $ret_info;
5844 //Reset temp
5845 unset($this->temp);
5849 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
5850 //Speed up a lot (avoid parse all)
5851 if ($tagName == "QUESTION_CATEGORIES" and $this->level == 3) {
5852 $this->finished = true;
5855 //Clear things
5856 $this->tree[$this->level] = "";
5857 $this->level--;
5858 $this->content = "";
5862 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
5863 function endElementScales($parser, $tagName) {
5864 //Check if we are into SCALES zone
5865 if ($this->tree[3] == "SCALES") {
5866 //if (trim($this->content)) //Debug
5867 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5868 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5869 //Acumulate data to info (content + close tag)
5870 //Reconvert: strip htmlchars again and trim to generate xml data
5871 if (!isset($this->temp)) {
5872 $this->temp = "";
5874 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5875 //If we've finished a scale, xmlize it an save to db
5876 if (($this->level == 4) and ($tagName == "SCALE")) {
5877 //Prepend XML standard header to info gathered
5878 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5879 //Call to xmlize for this portion of xml data (one SCALE)
5880 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5881 $data = xmlize($xml_data,0);
5882 //echo strftime ("%X",time())."<p>"; //Debug
5883 //traverse_xmlize($data); //Debug
5884 //print_object ($GLOBALS['traverse_array']); //Debug
5885 //$GLOBALS['traverse_array']=""; //Debug
5886 //Now, save data to db. We'll use it later
5887 //Get id and from data
5888 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
5889 //Save to db
5890 $status = backup_putid($this->preferences->backup_unique_code,"scale",$scale_id,
5891 null,$data);
5892 //Create returning info
5893 $ret_info = new object();
5894 $ret_info->id = $scale_id;
5895 $this->info[] = $ret_info;
5896 //Reset temp
5897 unset($this->temp);
5901 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
5902 //Speed up a lot (avoid parse all)
5903 if ($tagName == "SCALES" and $this->level == 3) {
5904 $this->finished = true;
5907 //Clear things
5908 $this->tree[$this->level] = "";
5909 $this->level--;
5910 $this->content = "";
5914 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
5915 function endElementGroups($parser, $tagName) {
5916 //Check if we are into GROUPS zone
5917 if ($this->tree[3] == "GROUPS") {
5918 //if (trim($this->content)) //Debug
5919 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5920 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5921 //Acumulate data to info (content + close tag)
5922 //Reconvert: strip htmlchars again and trim to generate xml data
5923 if (!isset($this->temp)) {
5924 $this->temp = "";
5926 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5927 //If we've finished a group, xmlize it an save to db
5928 if (($this->level == 4) and ($tagName == "GROUP")) {
5929 //Prepend XML standard header to info gathered
5930 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5931 //Call to xmlize for this portion of xml data (one GROUP)
5932 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5933 $data = xmlize($xml_data,0);
5934 //echo strftime ("%X",time())."<p>"; //Debug
5935 //traverse_xmlize($data); //Debug
5936 //print_object ($GLOBALS['traverse_array']); //Debug
5937 //$GLOBALS['traverse_array']=""; //Debug
5938 //Now, save data to db. We'll use it later
5939 //Get id and from data
5940 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
5941 //Save to db
5942 $status = backup_putid($this->preferences->backup_unique_code,"groups",$group_id,
5943 null,$data);
5944 //Create returning info
5945 $ret_info = new Object();
5946 $ret_info->id = $group_id;
5947 $this->info[] = $ret_info;
5948 //Reset temp
5949 unset($this->temp);
5953 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
5954 //Speed up a lot (avoid parse all)
5955 if ($tagName == "GROUPS" and $this->level == 3) {
5956 $this->finished = true;
5959 //Clear things
5960 $this->tree[$this->level] = "";
5961 $this->level--;
5962 $this->content = "";
5966 //This is the endTag handler we use where we are reading the groupings zone (todo="GROUPINGS")
5967 function endElementGroupings($parser, $tagName) {
5968 //Check if we are into GROUPINGS zone
5969 if ($this->tree[3] == "GROUPINGS") {
5970 //Acumulate data to info (content + close tag)
5971 //Reconvert: strip htmlchars again and trim to generate xml data
5972 if (!isset($this->temp)) {
5973 $this->temp = "";
5975 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5976 //If we've finished a group, xmlize it an save to db
5977 if (($this->level == 4) and ($tagName == "GROUPING")) {
5978 //Prepend XML standard header to info gathered
5979 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5980 //Call to xmlize for this portion of xml data (one GROUPING)
5981 $data = xmlize($xml_data,0);
5982 //Now, save data to db. We'll use it later
5983 //Get id and from data
5984 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
5985 //Save to db
5986 $status = backup_putid($this->preferences->backup_unique_code,"groupings",$grouping_id,
5987 null,$data);
5988 //Create returning info
5989 $ret_info = new Object();
5990 $ret_info->id = $grouping_id;
5991 $this->info[] = $ret_info;
5992 //Reset temp
5993 unset($this->temp);
5997 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
5998 //Speed up a lot (avoid parse all)
5999 if ($tagName == "GROUPINGS" and $this->level == 3) {
6000 $this->finished = true;
6003 //Clear things
6004 $this->tree[$this->level] = "";
6005 $this->level--;
6006 $this->content = "";
6010 //This is the endTag handler we use where we are reading the groupingsgroups zone (todo="GROUPINGGROUPS")
6011 function endElementGroupingsGroups($parser, $tagName) {
6012 //Check if we are into GROUPINGSGROUPS zone
6013 if ($this->tree[3] == "GROUPINGSGROUPS") {
6014 //Acumulate data to info (content + close tag)
6015 //Reconvert: strip htmlchars again and trim to generate xml data
6016 if (!isset($this->temp)) {
6017 $this->temp = "";
6019 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6020 //If we've finished a group, xmlize it an save to db
6021 if (($this->level == 4) and ($tagName == "GROUPINGGROUP")) {
6022 //Prepend XML standard header to info gathered
6023 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6024 //Call to xmlize for this portion of xml data (one GROUPING)
6025 $data = xmlize($xml_data,0);
6026 //Now, save data to db. We'll use it later
6027 //Get id and from data
6028 $groupinggroup_id = $data["GROUPINGGROUP"]["#"]["ID"]["0"]["#"];
6029 //Save to db
6030 $status = backup_putid($this->preferences->backup_unique_code,"groupingsgroups",$groupinggroup_id,
6031 null,$data);
6032 //Create returning info
6033 $ret_info = new Object();
6034 $ret_info->id = $groupinggroup_id;
6035 $this->info[] = $ret_info;
6036 //Reset temp
6037 unset($this->temp);
6041 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6042 //Speed up a lot (avoid parse all)
6043 if ($tagName == "GROUPINGSGROUPS" and $this->level == 3) {
6044 $this->finished = true;
6047 //Clear things
6048 $this->tree[$this->level] = "";
6049 $this->level--;
6050 $this->content = "";
6054 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
6055 function endElementEvents($parser, $tagName) {
6056 //Check if we are into EVENTS zone
6057 if ($this->tree[3] == "EVENTS") {
6058 //if (trim($this->content)) //Debug
6059 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6060 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6061 //Acumulate data to info (content + close tag)
6062 //Reconvert: strip htmlchars again and trim to generate xml data
6063 if (!isset($this->temp)) {
6064 $this->temp = "";
6066 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6067 //If we've finished a event, xmlize it an save to db
6068 if (($this->level == 4) and ($tagName == "EVENT")) {
6069 //Prepend XML standard header to info gathered
6070 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6071 //Call to xmlize for this portion of xml data (one EVENT)
6072 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6073 $data = xmlize($xml_data,0);
6074 //echo strftime ("%X",time())."<p>"; //Debug
6075 //traverse_xmlize($data); //Debug
6076 //print_object ($GLOBALS['traverse_array']); //Debug
6077 //$GLOBALS['traverse_array']=""; //Debug
6078 //Now, save data to db. We'll use it later
6079 //Get id and from data
6080 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
6081 //Save to db
6082 $status = backup_putid($this->preferences->backup_unique_code,"event",$event_id,
6083 null,$data);
6084 //Create returning info
6085 $ret_info = new object();
6086 $ret_info->id = $event_id;
6087 $this->info[] = $ret_info;
6088 //Reset temp
6089 unset($this->temp);
6093 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
6094 //Speed up a lot (avoid parse all)
6095 if ($tagName == "EVENTS" and $this->level == 3) {
6096 $this->finished = true;
6099 //Clear things
6100 $this->tree[$this->level] = "";
6101 $this->level--;
6102 $this->content = "";
6106 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
6107 function endElementModules($parser, $tagName) {
6108 //Check if we are into MODULES zone
6109 if ($this->tree[3] == "MODULES") {
6110 //if (trim($this->content)) //Debug
6111 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6112 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6113 //Acumulate data to info (content + close tag)
6114 //Reconvert: strip htmlchars again and trim to generate xml data
6115 if (!isset($this->temp)) {
6116 $this->temp = "";
6118 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6119 //If we've finished a mod, xmlize it an save to db
6120 if (($this->level == 4) and ($tagName == "MOD")) {
6121 //Prepend XML standard header to info gathered
6122 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6123 //Call to xmlize for this portion of xml data (one MOD)
6124 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6125 $data = xmlize($xml_data,0);
6126 //echo strftime ("%X",time())."<p>"; //Debug
6127 //traverse_xmlize($data); //Debug
6128 //print_object ($GLOBALS['traverse_array']); //Debug
6129 //$GLOBALS['traverse_array']=""; //Debug
6130 //Now, save data to db. We'll use it later
6131 //Get id and modtype from data
6132 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
6133 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
6134 //Only if we've selected to restore it
6135 if (!empty($this->preferences->mods[$mod_type]->restore)) {
6136 //Save to db
6137 $status = backup_putid($this->preferences->backup_unique_code,$mod_type,$mod_id,
6138 null,$data);
6139 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6140 //Create returning info
6141 $ret_info = new object();
6142 $ret_info->id = $mod_id;
6143 $ret_info->modtype = $mod_type;
6144 $this->info[] = $ret_info;
6146 //Reset temp
6147 unset($this->temp);
6153 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
6154 //Speed up a lot (avoid parse all)
6155 if ($tagName == "MODULES" and $this->level == 3) {
6156 $this->finished = true;
6159 //Clear things
6160 $this->tree[$this->level] = "";
6161 $this->level--;
6162 $this->content = "";
6166 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
6167 function endElementLogs($parser, $tagName) {
6168 //Check if we are into LOGS zone
6169 if ($this->tree[3] == "LOGS") {
6170 //if (trim($this->content)) //Debug
6171 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6172 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6173 //Acumulate data to info (content + close tag)
6174 //Reconvert: strip htmlchars again and trim to generate xml data
6175 if (!isset($this->temp)) {
6176 $this->temp = "";
6178 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6179 //If we've finished a log, xmlize it an save to db
6180 if (($this->level == 4) and ($tagName == "LOG")) {
6181 //Prepend XML standard header to info gathered
6182 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6183 //Call to xmlize for this portion of xml data (one LOG)
6184 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6185 $data = xmlize($xml_data,0);
6186 //echo strftime ("%X",time())."<p>"; //Debug
6187 //traverse_xmlize($data); //Debug
6188 //print_object ($GLOBALS['traverse_array']); //Debug
6189 //$GLOBALS['traverse_array']=""; //Debug
6190 //Now, save data to db. We'll use it later
6191 //Get id and modtype from data
6192 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
6193 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
6194 //We only save log entries from backup file if they are:
6195 // - Course logs
6196 // - User logs
6197 // - Module logs about one restored module
6198 if ($log_module == "course" or
6199 $log_module == "user" or
6200 $this->preferences->mods[$log_module]->restore) {
6201 //Increment counter
6202 $this->counter++;
6203 //Save to db
6204 $status = backup_putid($this->preferences->backup_unique_code,"log",$log_id,
6205 null,$data);
6206 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6207 //Create returning info
6208 $this->info = $this->counter;
6210 //Reset temp
6211 unset($this->temp);
6215 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
6216 //Speed up a lot (avoid parse all)
6217 if ($tagName == "LOGS" and $this->level == 3) {
6218 $this->finished = true;
6219 $this->counter = 0;
6222 //Clear things
6223 $this->tree[$this->level] = "";
6224 $this->level--;
6225 $this->content = "";
6229 //This is the endTag default handler we use when todo is undefined
6230 function endElement($parser, $tagName) {
6231 if (trim($this->content)) //Debug
6232 echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6233 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6235 //Clear things
6236 $this->tree[$this->level] = "";
6237 $this->level--;
6238 $this->content = "";
6241 //This is the handler to read data contents (simple accumule it)
6242 function characterData($parser, $data) {
6243 $this->content .= $data;
6247 //This function executes the MoodleParser
6248 function restore_read_xml ($xml_file,$todo,$preferences) {
6250 $status = true;
6252 $xml_parser = xml_parser_create('UTF-8');
6253 $moodle_parser = new MoodleParser();
6254 $moodle_parser->todo = $todo;
6255 $moodle_parser->preferences = $preferences;
6256 xml_set_object($xml_parser,$moodle_parser);
6257 //Depending of the todo we use some element_handler or another
6258 if ($todo == "INFO") {
6259 //Define handlers to that zone
6260 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
6261 } else if ($todo == "ROLES") {
6262 // Define handlers to that zone
6263 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
6264 } else if ($todo == "COURSE_HEADER") {
6265 //Define handlers to that zone
6266 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
6267 } else if ($todo == 'BLOCKS') {
6268 //Define handlers to that zone
6269 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
6270 } else if ($todo == "SECTIONS") {
6271 //Define handlers to that zone
6272 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
6273 } else if ($todo == 'FORMATDATA') {
6274 //Define handlers to that zone
6275 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
6276 } else if ($todo == "METACOURSE") {
6277 //Define handlers to that zone
6278 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
6279 } else if ($todo == "GRADEBOOK") {
6280 //Define handlers to that zone
6281 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
6282 } else if ($todo == "USERS") {
6283 //Define handlers to that zone
6284 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
6285 } else if ($todo == "MESSAGES") {
6286 //Define handlers to that zone
6287 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
6288 } else if ($todo == "QUESTIONS") {
6289 //Define handlers to that zone
6290 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
6291 } else if ($todo == "SCALES") {
6292 //Define handlers to that zone
6293 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
6294 } else if ($todo == "GROUPS") {
6295 //Define handlers to that zone
6296 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
6297 } else if ($todo == "GROUPINGS") {
6298 //Define handlers to that zone
6299 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
6300 } else if ($todo == "GROUPINGSGROUPS") {
6301 //Define handlers to that zone
6302 xml_set_element_handler($xml_parser, "startElementGroupingsGroups", "endElementGroupingsGroups");
6303 } else if ($todo == "EVENTS") {
6304 //Define handlers to that zone
6305 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
6306 } else if ($todo == "MODULES") {
6307 //Define handlers to that zone
6308 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
6309 } else if ($todo == "LOGS") {
6310 //Define handlers to that zone
6311 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
6312 } else {
6313 //Define default handlers (must no be invoked when everything become finished)
6314 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
6316 xml_set_character_data_handler($xml_parser, "characterData");
6317 $fp = fopen($xml_file,"r")
6318 or $status = false;
6319 if ($status) {
6320 while ($data = fread($fp, 4096) and !$moodle_parser->finished)
6321 xml_parse($xml_parser, $data, feof($fp))
6322 or die(sprintf("XML error: %s at line %d",
6323 xml_error_string(xml_get_error_code($xml_parser)),
6324 xml_get_current_line_number($xml_parser)));
6325 fclose($fp);
6327 //Get info from parser
6328 $info = $moodle_parser->info;
6330 //Clear parser mem
6331 xml_parser_free($xml_parser);
6333 if ($status && !empty($info)) {
6334 return $info;
6335 } else {
6336 return $status;
6341 * @param string $errorstr passed by reference, if silent is true,
6342 * errorstr will be populated and this function will return false rather than calling error() or notify()
6343 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
6344 * redirect to the next step in the restore process, instead will return $backup_unique_code
6346 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
6348 global $CFG, $SESSION;
6350 //Prepend dataroot to variable to have the absolute path
6351 $file = $CFG->dataroot."/".$file;
6353 if (!defined('RESTORE_SILENTLY')) {
6354 //Start the main table
6355 echo "<table cellpadding=\"5\">";
6356 echo "<tr><td>";
6358 //Start the mail ul
6359 echo "<ul>";
6362 //Check the file exists
6363 if (!is_file($file)) {
6364 if (!defined('RESTORE_SILENTLY')) {
6365 error ("File not exists ($file)");
6366 } else {
6367 $errorstr = "File not exists ($file)";
6368 return false;
6372 //Check the file name ends with .zip
6373 if (!substr($file,-4) == ".zip") {
6374 if (!defined('RESTORE_SILENTLY')) {
6375 error ("File has an incorrect extension");
6376 } else {
6377 $errorstr = 'File has an incorrect extension';
6378 return false;
6382 //Now calculate the unique_code for this restore
6383 $backup_unique_code = time();
6385 //Now check and create the backup dir (if it doesn't exist)
6386 if (!defined('RESTORE_SILENTLY')) {
6387 echo "<li>".get_string("creatingtemporarystructures").'</li>';
6389 $status = check_and_create_backup_dir($backup_unique_code);
6390 //Empty dir
6391 if ($status) {
6392 $status = clear_backup_dir($backup_unique_code);
6395 //Now delete old data and directories under dataroot/temp/backup
6396 if ($status) {
6397 if (!defined('RESTORE_SILENTLY')) {
6398 echo "<li>".get_string("deletingolddata").'</li>';
6400 $status = backup_delete_old_data();
6403 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
6404 if ($status) {
6405 if (!defined('RESTORE_SILENTLY')) {
6406 echo "<li>".get_string("copyingzipfile").'</li>';
6408 if (! $status = backup_copy_file($file,$CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
6409 if (!defined('RESTORE_SILENTLY')) {
6410 notify("Error copying backup file. Invalid name or bad perms.");
6411 } else {
6412 $errorstr = "Error copying backup file. Invalid name or bad perms";
6413 return false;
6418 //Now unzip the file
6419 if ($status) {
6420 if (!defined('RESTORE_SILENTLY')) {
6421 echo "<li>".get_string("unzippingbackup").'</li>';
6423 if (! $status = restore_unzip ($CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
6424 if (!defined('RESTORE_SILENTLY')) {
6425 notify("Error unzipping backup file. Invalid zip file.");
6426 } else {
6427 $errorstr = "Error unzipping backup file. Invalid zip file.";
6428 return false;
6433 //Check for Blackboard backups and convert
6434 if ($status){
6435 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
6436 if (!defined('RESTORE_SILENTLY')) {
6437 echo "<li>".get_string("checkingforbbexport").'</li>';
6439 $status = blackboard_convert($CFG->dataroot."/temp/backup/".$backup_unique_code);
6442 //Now check for the moodle.xml file
6443 if ($status) {
6444 $xml_file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
6445 if (!defined('RESTORE_SILENTLY')) {
6446 echo "<li>".get_string("checkingbackup").'</li>';
6448 if (! $status = restore_check_moodle_file ($xml_file)) {
6449 if (!is_file($xml_file)) {
6450 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
6451 } else {
6452 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
6454 if (!defined('RESTORE_SILENTLY')) {
6455 notify($errorstr);
6456 } else {
6457 return false;
6462 $info = "";
6463 $course_header = "";
6465 //Now read the info tag (all)
6466 if ($status) {
6467 if (!defined('RESTORE_SILENTLY')) {
6468 echo "<li>".get_string("readinginfofrombackup").'</li>';
6470 //Reading info from file
6471 $info = restore_read_xml_info ($xml_file);
6472 //Reading course_header from file
6473 $course_header = restore_read_xml_course_header ($xml_file);
6476 if (!defined('RESTORE_SILENTLY')) {
6477 //End the main ul
6478 echo "</ul>\n";
6480 //End the main table
6481 echo "</td></tr>";
6482 echo "</table>";
6485 //We compare Moodle's versions
6486 if ($CFG->version < $info->backup_moodle_version && $status) {
6487 $message = new message();
6488 $message->serverversion = $CFG->version;
6489 $message->serverrelease = $CFG->release;
6490 $message->backupversion = $info->backup_moodle_version;
6491 $message->backuprelease = $info->backup_moodle_release;
6492 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
6496 //Now we print in other table, the backup and the course it contains info
6497 if ($info and $course_header and $status) {
6498 //First, the course info
6499 if (!defined('RESTORE_SILENTLY')) {
6500 $status = restore_print_course_header($course_header);
6502 //Now, the backup info
6503 if ($status) {
6504 if (!defined('RESTORE_SILENTLY')) {
6505 $status = restore_print_info($info);
6510 //Save course header and info into php session
6511 if ($status) {
6512 $SESSION->info = $info;
6513 $SESSION->course_header = $course_header;
6516 //Finally, a little form to continue
6517 //with some hidden fields
6518 if ($status) {
6519 if (!defined('RESTORE_SILENTLY')) {
6520 echo "<br /><div style='text-align:center'>";
6521 $hidden["backup_unique_code"] = $backup_unique_code;
6522 $hidden["launch"] = "form";
6523 $hidden["file"] = $file;
6524 $hidden["id"] = $id;
6525 print_single_button("restore.php", $hidden, get_string("continue"),"post");
6526 echo "</div>";
6528 else {
6529 if (empty($noredirect)) {
6530 redirect($CFG->wwwroot.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
6531 } else {
6532 return $backup_unique_code;
6537 if (!$status) {
6538 if (!defined('RESTORE_SILENTLY')) {
6539 error ("An error has ocurred");
6540 } else {
6541 $errorstr = "An error has occured"; // helpful! :P
6542 return false;
6545 return true;
6548 function restore_setup_for_check(&$restore,$backup_unique_code) {
6549 global $SESSION;
6550 $restore->backup_unique_code=$backup_unique_code;
6551 $restore->users = 2; // yuk
6552 $restore->course_files = $SESSION->restore->restore_course_files;
6553 $restore->site_files = $SESSION->restore->restore_site_files;
6554 if ($allmods = get_records("modules")) {
6555 foreach ($allmods as $mod) {
6556 $modname = $mod->name;
6557 $var = "restore_".$modname;
6558 //Now check that we have that module info in the backup file
6559 if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
6560 $restore->$var = 1;
6564 return true;
6567 function backup_to_restore_array($backup,$k=0) {
6568 if (is_array($backup) ) {
6569 foreach ($backup as $key => $value) {
6570 $newkey = str_replace('backup','restore',$key);
6571 $restore[$newkey] = backup_to_restore_array($value,$key);
6574 else if (is_object($backup)) {
6575 $tmp = get_object_vars($backup);
6576 foreach ($tmp as $key => $value) {
6577 $newkey = str_replace('backup','restore',$key);
6578 $restore->$newkey = backup_to_restore_array($value,$key);
6581 else {
6582 $newkey = str_replace('backup','restore',$k);
6583 $restore = $backup;
6585 return $restore;
6589 * compatibility function
6590 * checks for per-instance backups AND
6591 * older per-module backups
6592 * and returns whether userdata has been selected.
6594 function restore_userdata_selected($restore,$modname,$modid) {
6595 // check first for per instance array
6596 if (!empty($restore->mods[$modname]->granular)) { // supports per instance
6597 return array_key_exists($modid,$restore->mods[$modname]->instances)
6598 && !empty($restore->mods[$modname]->instances[$modid]->userinfo);
6601 //print_object($restore->mods[$modname]);
6602 return !empty($restore->mods[$modname]->userinfo);
6605 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
6607 global $CFG, $USER;
6608 $status = true;
6610 //Checks for the required files/functions to restore every module
6611 //and include them
6612 if ($allmods = get_records("modules") ) {
6613 foreach ($allmods as $mod) {
6614 $modname = $mod->name;
6615 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
6616 //If file exists and we have selected to restore that type of module
6617 if ((file_exists($modfile)) and !empty($restore->mods[$modname]) and ($restore->mods[$modname]->restore)) {
6618 include_once($modfile);
6623 if (!defined('RESTORE_SILENTLY')) {
6624 //Start the main table
6625 echo "<table cellpadding=\"5\">";
6626 echo "<tr><td>";
6628 //Start the main ul
6629 echo "<ul>";
6632 //Localtion of the xml file
6633 $xml_file = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/moodle.xml";
6635 //If we've selected to restore into new course
6636 //create it (course)
6637 //Saving conversion id variables into backup_tables
6638 if ($restore->restoreto == 2) {
6639 if (!defined('RESTORE_SILENTLY')) {
6640 echo '<li>'.get_string('creatingnewcourse') . '</li>';
6642 $oldidnumber = $course_header->course_idnumber;
6643 if (!$status = restore_create_new_course($restore,$course_header)) {
6644 if (!defined('RESTORE_SILENTLY')) {
6645 notify("Error while creating the new empty course.");
6646 } else {
6647 $errorstr = "Error while creating the new empty course.";
6648 return false;
6652 //Print course fullname and shortname and category
6653 if ($status) {
6654 if (!defined('RESTORE_SILENTLY')) {
6655 echo "<ul>";
6656 echo "<li>".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
6657 echo "<li>".get_string("category").": ".$course_header->category->name.'</li>';
6658 if (!empty($oldidnumber)) {
6659 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
6661 echo "</ul>";
6662 //Put the destination course_id
6664 $restore->course_id = $course_header->course_id;
6667 if ($status = restore_open_html($restore,$course_header)){
6668 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
6671 } else {
6672 $course = get_record("course","id",$restore->course_id);
6673 if ($course) {
6674 if (!defined('RESTORE_SILENTLY')) {
6675 echo "<li>".get_string("usingexistingcourse");
6676 echo "<ul>";
6677 echo "<li>".get_string("from").": ".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
6678 echo "<li>".get_string("to").": ". format_string($course->fullname) ." (".format_string($course->shortname).")".'</li>';
6679 if (($restore->deleting)) {
6680 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
6681 } else {
6682 echo "<li>".get_string("addingdatatoexisting").'</li>';
6684 echo "</ul></li>";
6686 //If we have selected to restore deleting, we do it now.
6687 if ($restore->deleting) {
6688 if (!defined('RESTORE_SILENTLY')) {
6689 echo "<li>".get_string("deletingolddata").'</li>';
6691 $status = remove_course_contents($restore->course_id,false) and
6692 delete_dir_contents($CFG->dataroot."/".$restore->course_id,"backupdata");
6693 if ($status) {
6694 //Now , this situation is equivalent to the "restore to new course" one (we
6695 //have a course record and nothing more), so define it as "to new course"
6696 $restore->restoreto = 2;
6697 } else {
6698 if (!defined('RESTORE_SILENTLY')) {
6699 notify("An error occurred while deleting some of the course contents.");
6700 } else {
6701 $errrostr = "An error occurred while deleting some of the course contents.";
6702 return false;
6706 } else {
6707 if (!defined('RESTORE_SILENTLY')) {
6708 notify("Error opening existing course.");
6709 $status = false;
6710 } else {
6711 $errorstr = "Error opening existing course.";
6712 return false;
6717 //Now create users as needed
6718 if ($status and ($restore->users == 0 or $restore->users == 1)) {
6719 if (!defined('RESTORE_SILENTLY')) {
6720 echo "<li>".get_string("creatingusers")."<br />";
6722 if (!$status = restore_create_users($restore,$xml_file)) {
6723 if (!defined('RESTORE_SILENTLY')) {
6724 notify("Could not restore users.");
6725 } else {
6726 $errorstr = "Could not restore users.";
6727 return false;
6731 //Now print info about the work done
6732 if ($status) {
6733 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
6734 where backup_code = '$restore->backup_unique_code' and
6735 table_name = 'user'");
6736 //We've records
6737 if ($recs) {
6738 $new_count = 0;
6739 $exists_count = 0;
6740 $student_count = 0;
6741 $teacher_count = 0;
6742 $counter = 0;
6743 //Iterate, filling counters
6744 foreach ($recs as $rec) {
6745 //Get full record, using backup_getids
6746 $record = backup_getid($restore->backup_unique_code,"user",$rec->old_id);
6747 if (strpos($record->info,"new") !== false) {
6748 $new_count++;
6750 if (strpos($record->info,"exists") !== false) {
6751 $exists_count++;
6753 if (strpos($record->info,"student") !== false) {
6754 $student_count++;
6755 } else if (strpos($record->info,"teacher") !== false) {
6756 $teacher_count++;
6758 //Do some output
6759 $counter++;
6760 if ($counter % 10 == 0) {
6761 if (!defined('RESTORE_SILENTLY')) {
6762 echo ".";
6763 if ($counter % 200 == 0) {
6764 echo "<br />";
6767 backup_flush(300);
6770 if (!defined('RESTORE_SILENTLY')) {
6771 //Now print information gathered
6772 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
6773 echo "<ul>";
6774 echo "<li>".get_string("students").": ".$student_count.'</li>';
6775 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
6776 echo "</ul>";
6778 } else {
6779 if (!defined('RESTORE_SILENTLY')) {
6780 notify("No users were found!");
6781 } // no need to return false here, it's recoverable.
6785 if (!defined('RESTORE_SILENTLY')) {
6786 echo "</li>";
6791 //Now create groups as needed
6792 if ($status) {
6793 if (!defined('RESTORE_SILENTLY')) {
6794 echo "<li>".get_string("creatinggroups");
6796 if (!$status = restore_create_groups($restore,$xml_file)) {
6797 if (!defined('RESTORE_SILENTLY')) {
6798 notify("Could not restore groups!");
6799 } else {
6800 $errorstr = "Could not restore groups!";
6801 return false;
6804 if (!defined('RESTORE_SILENTLY')) {
6805 echo '</li>';
6809 //Now create groupings as needed
6810 if ($status) {
6811 if (!defined('RESTORE_SILENTLY')) {
6812 echo "<li>".get_string("creatinggroupings");
6814 if (!$status = restore_create_groupings($restore,$xml_file)) {
6815 if (!defined('RESTORE_SILENTLY')) {
6816 notify("Could not restore groupings!");
6817 } else {
6818 $errorstr = "Could not restore groupings!";
6819 return false;
6822 if (!defined('RESTORE_SILENTLY')) {
6823 echo '</li>';
6827 //Now create groupingsgroups as needed
6828 if ($status) {
6829 if (!defined('RESTORE_SILENTLY')) {
6830 echo "<li>".get_string("creatinggroupingsgroups");
6832 if (!$status = restore_create_groupings_groups($restore,$xml_file)) {
6833 if (!defined('RESTORE_SILENTLY')) {
6834 notify("Could not restore groups in groupings!");
6835 } else {
6836 $errorstr = "Could not restore groups in groupings!";
6837 return false;
6840 if (!defined('RESTORE_SILENTLY')) {
6841 echo '</li>';
6846 //Now create the course_sections and their associated course_modules
6847 //we have to do this after groups and groupings are restored, because we need the new groupings id
6848 if ($status) {
6849 //Into new course
6850 if ($restore->restoreto == 2) {
6851 if (!defined('RESTORE_SILENTLY')) {
6852 echo "<li>".get_string("creatingsections");
6854 if (!$status = restore_create_sections($restore,$xml_file)) {
6855 if (!defined('RESTORE_SILENTLY')) {
6856 notify("Error creating sections in the existing course.");
6857 } else {
6858 $errorstr = "Error creating sections in the existing course.";
6859 return false;
6862 if (!defined('RESTORE_SILENTLY')) {
6863 echo '</li>';
6865 //Into existing course
6866 } else if ($restore->restoreto == 0 or $restore->restoreto == 1) {
6867 if (!defined('RESTORE_SILENTLY')) {
6868 echo "<li>".get_string("checkingsections");
6870 if (!$status = restore_create_sections($restore,$xml_file)) {
6871 if (!defined('RESTORE_SILENTLY')) {
6872 notify("Error creating sections in the existing course.");
6873 } else {
6874 $errorstr = "Error creating sections in the existing course.";
6875 return false;
6878 if (!defined('RESTORE_SILENTLY')) {
6879 echo '</li>';
6881 //Error
6882 } else {
6883 if (!defined('RESTORE_SILENTLY')) {
6884 notify("Neither a new course or an existing one was specified.");
6885 $status = false;
6886 } else {
6887 $errorstr = "Neither a new course or an existing one was specified.";
6888 return false;
6893 //Now create metacourse info
6894 if ($status and $restore->metacourse) {
6895 //Only to new courses!
6896 if ($restore->restoreto == 2) {
6897 if (!defined('RESTORE_SILENTLY')) {
6898 echo "<li>".get_string("creatingmetacoursedata");
6900 if (!$status = restore_create_metacourse($restore,$xml_file)) {
6901 if (!defined('RESTORE_SILENTLY')) {
6902 notify("Error creating metacourse in the course.");
6903 } else {
6904 $errorstr = "Error creating metacourse in the course.";
6905 return false;
6908 if (!defined('RESTORE_SILENTLY')) {
6909 echo '</li>';
6915 //Now create categories and questions as needed
6916 if ($status) {
6917 include_once("$CFG->dirroot/question/restorelib.php");
6918 if (!defined('RESTORE_SILENTLY')) {
6919 echo "<li>".get_string("creatingcategoriesandquestions");
6920 echo "<ul>";
6922 if (!$status = restore_create_questions($restore,$xml_file)) {
6923 if (!defined('RESTORE_SILENTLY')) {
6924 notify("Could not restore categories and questions!");
6925 } else {
6926 $errorstr = "Could not restore categories and questions!";
6927 return false;
6930 if (!defined('RESTORE_SILENTLY')) {
6931 echo "</ul></li>";
6935 //Now create user_files as needed
6936 if ($status and ($restore->user_files)) {
6937 if (!defined('RESTORE_SILENTLY')) {
6938 echo "<li>".get_string("copyinguserfiles");
6940 if (!$status = restore_user_files($restore)) {
6941 if (!defined('RESTORE_SILENTLY')) {
6942 notify("Could not restore user files!");
6943 } else {
6944 $errorstr = "Could not restore user files!";
6945 return false;
6948 //If all is ok (and we have a counter)
6949 if ($status and ($status !== true)) {
6950 //Inform about user dirs created from backup
6951 if (!defined('RESTORE_SILENTLY')) {
6952 echo "<ul>";
6953 echo "<li>".get_string("userzones").": ".$status;
6954 echo "</li></ul>";
6957 if (!defined('RESTORE_SILENTLY')) {
6958 echo '</li>';
6962 //Now create course files as needed
6963 if ($status and ($restore->course_files)) {
6964 if (!defined('RESTORE_SILENTLY')) {
6965 echo "<li>".get_string("copyingcoursefiles");
6967 if (!$status = restore_course_files($restore)) {
6968 if (empty($status)) {
6969 notify("Could not restore course files!");
6970 } else {
6971 $errorstr = "Could not restore course files!";
6972 return false;
6975 //If all is ok (and we have a counter)
6976 if ($status and ($status !== true)) {
6977 //Inform about user dirs created from backup
6978 if (!defined('RESTORE_SILENTLY')) {
6979 echo "<ul>";
6980 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
6981 echo "</ul>";
6984 if (!defined('RESTORE_SILENTLY')) {
6985 echo "</li>";
6990 //Now create site files as needed
6991 if ($status and ($restore->site_files)) {
6992 if (!defined('RESTORE_SILENTLY')) {
6993 echo "<li>".get_string('copyingsitefiles');
6995 if (!$status = restore_site_files($restore)) {
6996 if (empty($status)) {
6997 notify("Could not restore site files!");
6998 } else {
6999 $errorstr = "Could not restore site files!";
7000 return false;
7003 //If all is ok (and we have a counter)
7004 if ($status and ($status !== true)) {
7005 //Inform about user dirs created from backup
7006 if (!defined('RESTORE_SILENTLY')) {
7007 echo "<ul>";
7008 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7009 echo "</ul>";
7012 if (!defined('RESTORE_SILENTLY')) {
7013 echo "</li>";
7017 //Now create messages as needed
7018 if ($status and ($restore->messages)) {
7019 if (!defined('RESTORE_SILENTLY')) {
7020 echo "<li>".get_string("creatingmessagesinfo");
7022 if (!$status = restore_create_messages($restore,$xml_file)) {
7023 if (!defined('RESTORE_SILENTLY')) {
7024 notify("Could not restore messages!");
7025 } else {
7026 $errorstr = "Could not restore messages!";
7027 return false;
7030 if (!defined('RESTORE_SILENTLY')) {
7031 echo "</li>";
7035 //Now create scales as needed
7036 if ($status) {
7037 if (!defined('RESTORE_SILENTLY')) {
7038 echo "<li>".get_string("creatingscales");
7040 if (!$status = restore_create_scales($restore,$xml_file)) {
7041 if (!defined('RESTORE_SILENTLY')) {
7042 notify("Could not restore custom scales!");
7043 } else {
7044 $errorstr = "Could not restore custom scales!";
7045 return false;
7048 if (!defined('RESTORE_SILENTLY')) {
7049 echo '</li>';
7053 //Now create events as needed
7054 if ($status) {
7055 if (!defined('RESTORE_SILENTLY')) {
7056 echo "<li>".get_string("creatingevents");
7058 if (!$status = restore_create_events($restore,$xml_file)) {
7059 if (!defined('RESTORE_SILENTLY')) {
7060 notify("Could not restore course events!");
7061 } else {
7062 $errorstr = "Could not restore course events!";
7063 return false;
7066 if (!defined('RESTORE_SILENTLY')) {
7067 echo '</li>';
7071 //Now create course modules as needed
7072 if ($status) {
7073 if (!defined('RESTORE_SILENTLY')) {
7074 echo "<li>".get_string("creatingcoursemodules");
7076 if (!$status = restore_create_modules($restore,$xml_file)) {
7077 if (!defined('RESTORE_SILENTLY')) {
7078 notify("Could not restore modules!");
7079 } else {
7080 $errorstr = "Could not restore modules!";
7081 return false;
7084 if (!defined('RESTORE_SILENTLY')) {
7085 echo '</li>';
7089 //Now create gradebook as needed -- AFTER modules!!!
7090 if ($status) {
7091 if (!defined('RESTORE_SILENTLY')) {
7092 echo "<li>".get_string("creatinggradebook");
7094 if (!$status = restore_create_gradebook($restore,$xml_file)) {
7095 if (!defined('RESTORE_SILENTLY')) {
7096 notify("Could not restore gradebook!");
7097 } else {
7098 $errorstr = "Could not restore gradebook!";
7099 return false;
7102 if (!defined('RESTORE_SILENTLY')) {
7103 echo '</li>';
7107 //Bring back the course blocks -- do it AFTER the modules!!!
7108 if($status) {
7109 //If we are deleting and bringing into a course or making a new course, same situation
7110 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7111 if (!defined('RESTORE_SILENTLY')) {
7112 echo '<li>'.get_string('creatingblocks');
7114 $course_header->blockinfo = !empty($course_header->blockinfo) ? $course_header->blockinfo : NULL;
7115 if (!$status = restore_create_blocks($restore, $info->backup_block_format, $course_header->blockinfo, $xml_file)) {
7116 if (!defined('RESTORE_SILENTLY')) {
7117 notify('Error while creating the course blocks');
7118 } else {
7119 $errorstr = "Error while creating the course blocks";
7120 return false;
7123 if (!defined('RESTORE_SILENTLY')) {
7124 echo '</li>';
7129 if($status) {
7130 //If we are deleting and bringing into a course or making a new course, same situation
7131 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7132 if (!defined('RESTORE_SILENTLY')) {
7133 echo '<li>'.get_string('courseformatdata');
7135 if (!$status = restore_set_format_data($restore, $xml_file)) {
7136 $error = "Error while setting the course format data";
7137 if (!defined('RESTORE_SILENTLY')) {
7138 notify($error);
7139 } else {
7140 $errorstr=$error;
7141 return false;
7144 if (!defined('RESTORE_SILENTLY')) {
7145 echo '</li>';
7150 //Now create log entries as needed
7151 if ($status and ($restore->logs)) {
7152 if (!defined('RESTORE_SILENTLY')) {
7153 echo "<li>".get_string("creatinglogentries");
7155 if (!$status = restore_create_logs($restore,$xml_file)) {
7156 if (!defined('RESTORE_SILENTLY')) {
7157 notify("Could not restore logs!");
7158 } else {
7159 $errorstr = "Could not restore logs!";
7160 return false;
7163 if (!defined('RESTORE_SILENTLY')) {
7164 echo '</li>';
7168 //Now, if all is OK, adjust the instance field in course_modules !!
7169 if ($status) {
7170 if (!defined('RESTORE_SILENTLY')) {
7171 echo "<li>".get_string("checkinginstances");
7173 if (!$status = restore_check_instances($restore)) {
7174 if (!defined('RESTORE_SILENTLY')) {
7175 notify("Could not adjust instances in course_modules!");
7176 } else {
7177 $errorstr = "Could not adjust instances in course_modules!";
7178 return false;
7181 if (!defined('RESTORE_SILENTLY')) {
7182 echo '</li>';
7186 //Now, if all is OK, adjust activity events
7187 if ($status) {
7188 if (!defined('RESTORE_SILENTLY')) {
7189 echo "<li>".get_string("refreshingevents");
7191 if (!$status = restore_refresh_events($restore)) {
7192 if (!defined('RESTORE_SILENTLY')) {
7193 notify("Could not refresh events for activities!");
7194 } else {
7195 $errorstr = "Could not refresh events for activities!";
7196 return false;
7199 if (!defined('RESTORE_SILENTLY')) {
7200 echo '</li>';
7204 //Now, if all is OK, adjust inter-activity links
7205 if ($status) {
7206 if (!defined('RESTORE_SILENTLY')) {
7207 echo "<li>".get_string("decodinginternallinks");
7209 if (!$status = restore_decode_content_links($restore)) {
7210 if (!defined('RESTORE_SILENTLY')) {
7211 notify("Could not decode content links!");
7212 } else {
7213 $errorstr = "Could not decode content links!";
7214 return false;
7217 if (!defined('RESTORE_SILENTLY')) {
7218 echo '</li>';
7222 //Now, with backup files prior to version 2005041100,
7223 //convert all the wiki texts in the course to markdown
7224 if ($status && $restore->backup_version < 2005041100) {
7225 if (!defined('RESTORE_SILENTLY')) {
7226 echo "<li>".get_string("convertingwikitomarkdown");
7228 if (!$status = restore_convert_wiki2markdown($restore)) {
7229 if (!defined('RESTORE_SILENTLY')) {
7230 notify("Could not convert wiki texts to markdown!");
7231 } else {
7232 $errorstr = "Could not convert wiki texts to markdown!";
7233 return false;
7236 if (!defined('RESTORE_SILENTLY')) {
7237 echo '</li>';
7241 // for moodle versions before 1.9, those grades need to be converted to use the new gradebook
7242 // this code needs to execute *after* the course_modules are sorted out
7243 if ($status && $restore->backup_version < 2007090500) {
7244 if (!defined('RESTORE_SILENTLY')) {
7245 echo "<li>".get_string("migratinggrades");
7248 // we need need to worry about mods that are restored
7249 // the others in the course are not relevent
7250 if (!empty($restore->mods)) {
7251 require_once($CFG->dirroot.'/lib/gradelib.php');
7252 foreach ($restore->mods as $mod=>$modtype) {
7253 if (!empty($modtype->instances)) {
7254 foreach ($modtype->instances as $modinstance) {
7255 $sql = "SELECT a.*, cm.idnumber as cmidnumber, m.name as modname
7256 FROM {$CFG->prefix}$mod a,
7257 {$CFG->prefix}course_modules cm,
7258 {$CFG->prefix}modules m
7259 WHERE m.name='$mod'
7260 AND m.id=cm.module
7261 AND cm.instance=a.id
7262 AND cm.id= {$modinstance->restored_as_course_module}";
7264 if ($module = get_record_sql($sql)) {
7265 grade_update_mod_grades($module);
7272 if (!defined('RESTORE_SILENTLY')) {
7273 echo '</li>';
7277 /*******************************************************************************
7278 ************* Restore of Roles and Capabilities happens here ******************
7279 *******************************************************************************/
7280 // try to restore roles even when restore is going to fail - teachers might have
7281 // at least some role assigned - this is not correct though
7282 $status = restore_create_roles($restore, $xml_file) && $status;
7283 $status = restore_roles_settings($restore, $xml_file) && $status;
7285 //Now if all is OK, update:
7286 // - course modinfo field
7287 // - categories table
7288 // - add user as teacher
7289 if ($status) {
7290 if (!defined('RESTORE_SILENTLY')) {
7291 echo "<li>".get_string("checkingcourse");
7293 //modinfo field
7294 rebuild_course_cache($restore->course_id);
7295 //categories table
7296 $course = get_record("course","id",$restore->course_id);
7297 fix_course_sortorder();
7298 // Check if the user has course update capability in the newly restored course
7299 // there is no need to load his capabilities again, because restore_roles_settings
7300 // would have loaded it anyway, if there is any assignments.
7301 // fix for MDL-6831
7302 $newcontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
7303 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
7304 // fix for MDL-9065, use the new config setting if exists
7305 if ($CFG->creatornewroleid) {
7306 role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id);
7307 } else {
7308 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM, SITEID))) {
7309 if ($legacyteacher = array_shift($legacyteachers)) {
7310 role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id);
7312 } else {
7313 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
7317 if (!defined('RESTORE_SILENTLY')) {
7318 echo '</li>';
7322 //Cleanup temps (files and db)
7323 if ($status) {
7324 if (!defined('RESTORE_SILENTLY')) {
7325 echo "<li>".get_string("cleaningtempdata");
7327 if (!$status = clean_temp_data ($restore)) {
7328 if (!defined('RESTORE_SILENTLY')) {
7329 notify("Could not clean up temporary data from files and database");
7330 } else {
7331 $errorstr = "Could not clean up temporary data from files and database";
7332 return false;
7335 if (!defined('RESTORE_SILENTLY')) {
7336 echo '</li>';
7340 // this is not a critical check - the result can be ignored
7341 if (restore_close_html($restore)){
7342 if (!defined('RESTORE_SILENTLY')) {
7343 echo '<li>Closing the Restorelog.html file.</li>';
7346 else {
7347 if (!defined('RESTORE_SILENTLY')) {
7348 notify("Could not close the restorelog.html file");
7352 if (!defined('RESTORE_SILENTLY')) {
7353 //End the main ul
7354 echo "</ul>";
7356 //End the main table
7357 echo "</td></tr>";
7358 echo "</table>";
7361 return $status;
7363 //Create, open and write header of the html log file
7364 function restore_open_html($restore,$course_header) {
7366 global $CFG;
7368 $status = true;
7370 //Open file for writing
7371 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
7372 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
7373 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
7375 $status = check_dir_exists($dest_dir,true);
7376 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
7377 //Add the stylesheet
7378 $stylesheetshtml = '';
7379 foreach ($CFG->stylesheets as $stylesheet) {
7380 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
7382 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
7383 $languagehtml = get_html_lang($dir=true);
7385 //Write the header in the new logging file
7386 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
7387 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
7388 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
7389 fwrite ($restorelog_file,"<head>");
7390 fwrite ($restorelog_file,$stylesheetshtml);
7391 fwrite ($restorelog_file,"<title>".$course_header->course_shortname." Restored </title>");
7392 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
7393 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname." The FullName is now - ".$course_header->course_fullname."<br/><br/>");
7394 $startdate = addslashes($course_header->course_startdate);
7395 $date = usergetdate($startdate);
7396 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
7397 $startdate += $restore->course_startdateoffset;
7398 $date = usergetdate($startdate);
7399 fwrite ($restorelog_file,"&nbsp;&nbsp;&nbsp;This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
7401 if ($status) {
7402 return $restorelog_file;
7403 } else {
7404 return false;
7407 //Create & close footer of the html log file
7408 function restore_close_html($restore) {
7410 global $CFG;
7412 $status = true;
7414 //Open file for writing
7415 //First, check that course_id/backupdata folder exists in CFG->dataroot
7416 $dest_dir = $CFG->dataroot."/".$restore->course_id."/backupdata";
7417 $status = check_dir_exists($dest_dir, true, true);
7418 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
7419 //Write the footer to close the logging file
7420 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
7421 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
7423 if ($status) {
7424 return $restorelog_file;
7425 } else {
7426 return false;
7430 /********************** Roles and Capabilities Related Functions *******************************/
7432 /* Yu: Note recovering of role assignments/overrides need to take place after
7433 users have been recovered, i.e. after we get their new_id, and after all
7434 roles have been recreated or mapped. Contexts can be created on the fly.
7435 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
7436 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
7437 once roles and users have been restored.
7441 * This function restores all the needed roles for this course
7442 * i.e. roles with an assignment in any of the mods or blocks,
7443 * roles assigned on any user (e.g. parent role) and roles
7444 * assigned at course levle
7445 * This function should check for duplicate roles first
7446 * It isn't now, just overwriting
7448 function restore_create_roles($restore, $xmlfile) {
7449 if (!defined('RESTORE_SILENTLY')) {
7450 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
7452 $info = restore_read_xml_roles($xmlfile);
7454 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
7456 // the following code creates new roles
7457 // but we could use more intelligent detection, and role mapping
7458 // get role mapping info from $restore
7459 $rolemappings = array();
7461 if (!empty($restore->rolesmapping)) {
7462 $rolemappings = $restore->rolesmapping;
7464 // $info->roles will be empty for backups pre 1.7
7465 if (isset($info->roles) && $info->roles) {
7467 foreach ($info->roles as $oldroleid=>$roledata) {
7468 if (empty($restore->rolesmapping)) {
7469 // if this is empty altogether, we came from import or there's no roles used in course at all
7470 // in this case, write the same oldid as this is the same site
7471 // no need to do mapping
7472 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
7473 $oldroleid); // adding a new id
7474 continue; // do not create additonal roles;
7476 // first we check if the roles are in the mappings
7477 // if so, we just do a mapping i.e. update oldids table
7478 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
7479 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
7480 $rolemappings[$oldroleid]); // adding a new id
7482 } else {
7484 // code to make new role name/short name if same role name or shortname exists
7485 $fullname = $roledata->name;
7486 $shortname = $roledata->shortname;
7487 $currentfullname = "";
7488 $currentshortname = "";
7489 $counter = 0;
7491 do {
7492 if ($counter) {
7493 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
7494 $suffixshort = "_".$counter;
7495 } else {
7496 $suffixfull = "";
7497 $suffixshort = "";
7499 $currentfullname = $fullname.$suffixfull;
7500 // Limit the size of shortname - database column accepts <= 15 chars
7501 $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
7502 $coursefull = get_record("role","name",addslashes($currentfullname));
7503 $courseshort = get_record("role","shortname",addslashes($currentshortname));
7504 $counter++;
7505 } while ($coursefull || $courseshort);
7507 $roledata->name = $currentfullname;
7508 $roledata->shortname= $currentshortname;
7510 // done finding a unique name
7512 $newroleid = create_role(addslashes($roledata->name),addslashes($roledata->shortname),'');
7513 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
7514 $newroleid); // adding a new id
7515 foreach ($roledata->capabilities as $capability) {
7517 $roleinfo = new object();
7518 $roleinfo = (object)$capability;
7519 $roleinfo->contextid = $sitecontext->id;
7520 $roleinfo->capability = $capability->name;
7521 $roleinfo->roleid = $newroleid;
7523 insert_record('role_capabilities', $roleinfo);
7528 return true;
7532 * this function restores role assignments and role overrides
7533 * in course/user/block/mod level, it passed through
7534 * the xml file again
7536 function restore_roles_settings($restore, $xmlfile) {
7537 // data pulls from course, mod, user, and blocks
7539 /*******************************************************
7540 * Restoring from course level assignments *
7541 *******************************************************/
7542 if (!defined('RESTORE_SILENTLY')) {
7543 echo "<li>".get_string("creatingcourseroles").'</li>';
7545 $course = restore_read_xml_course_header($xmlfile);
7547 if (!isset($restore->rolesmapping)) {
7548 $isimport = true; // course import from another course, or course with no role assignments
7549 } else {
7550 $isimport = false; // course restore with role assignments
7553 if (!empty($course->roleassignments) && !$isimport) {
7554 $courseassignments = $course->roleassignments;
7556 foreach ($courseassignments as $oldroleid => $courseassignment) {
7557 restore_write_roleassignments($restore, $courseassignment->assignments, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
7560 /*****************************************************
7561 * Restoring from course level overrides *
7562 *****************************************************/
7564 if (!empty($course->roleoverrides) && !$isimport) {
7565 $courseoverrides = $course->roleoverrides;
7566 foreach ($courseoverrides as $oldroleid => $courseoverride) {
7567 // if not importing into exiting course, or creating new role, we are ok
7568 // local course overrides to be respected (i.e. restored course overrides ignored)
7569 if ($restore->restoreto != 1 || empty($restore->rolesmapping[$oldroleid])) {
7570 restore_write_roleoverrides($restore, $courseoverride->overrides, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
7575 /*******************************************************
7576 * Restoring role assignments/overrdies *
7577 * from module level assignments *
7578 *******************************************************/
7580 if (!defined('RESTORE_SILENTLY')) {
7581 echo "<li>".get_string("creatingmodroles").'</li>';
7583 $sections = restore_read_xml_sections($xmlfile);
7584 $secs = $sections->sections;
7586 foreach ($secs as $section) {
7587 if (isset($section->mods)) {
7588 foreach ($section->mods as $modid=>$mod) {
7589 if (isset($mod->roleassignments) && !$isimport) {
7590 foreach ($mod->roleassignments as $oldroleid=>$modassignment) {
7591 restore_write_roleassignments($restore, $modassignment->assignments, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
7594 // role overrides always applies, in import or backup/restore
7595 if (isset($mod->roleoverrides)) {
7596 foreach ($mod->roleoverrides as $oldroleid=>$modoverride) {
7597 restore_write_roleoverrides($restore, $modoverride->overrides, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
7604 /*************************************************
7605 * Restoring assignments from blocks level *
7606 * role assignments/overrides *
7607 *************************************************/
7609 if ($restore->restoreto != 1) { // skip altogether if restoring to exisitng course by adding
7610 if (!defined('RESTORE_SILENTLY')) {
7611 echo "<li>".get_string("creatingblocksroles").'</li>';
7613 $blocks = restore_read_xml_blocks($xmlfile);
7614 if (isset($blocks->instances)) {
7615 foreach ($blocks->instances as $instance) {
7616 if (isset($instance->roleassignments) && !$isimport) {
7617 foreach ($instance->roleassignments as $oldroleid=>$blockassignment) {
7618 restore_write_roleassignments($restore, $blockassignment->assignments, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
7622 // likewise block overrides should always be restored like mods
7623 if (isset($instance->roleoverrides)) {
7624 foreach ($instance->roleoverrides as $oldroleid=>$blockoverride) {
7625 restore_write_roleoverrides($restore, $blockoverride->overrides, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
7631 /************************************************
7632 * Restoring assignments from userid level *
7633 * role assignments/overrides *
7634 ************************************************/
7635 if (!defined('RESTORE_SILENTLY')) {
7636 echo "<li>".get_string("creatinguserroles").'</li>';
7638 $info = restore_read_xml_users($restore, $xmlfile);
7639 if (!empty($info->users) && !$isimport) { // no need to restore user assignments for imports (same course)
7640 //For each user, take its info from backup_ids
7641 foreach ($info->users as $userid) {
7642 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
7643 if (isset($rec->info->roleassignments)) {
7644 foreach ($rec->info->roleassignments as $oldroleid=>$userassignment) {
7645 restore_write_roleassignments($restore, $userassignment->assignments, "user", CONTEXT_USER, $userid, $oldroleid);
7648 if (isset($rec->info->roleoverrides)) {
7649 foreach ($rec->info->roleoverrides as $oldroleid=>$useroverride) {
7650 restore_write_roleoverrides($restore, $useroverride->overrides, "user", CONTEXT_USER, $userid, $oldroleid);
7656 return true;
7659 // auxillary function to write role assignments read from xml to db
7660 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
7662 $role = backup_getid($restore->backup_unique_code, "role", $oldroleid);
7664 foreach ($assignments as $assignment) {
7666 $olduser = backup_getid($restore->backup_unique_code,"user",$assignment->userid);
7667 //Oh dear, $olduser... can be an object, $obj->string or bool!
7668 if (!$olduser || (is_string($olduser->info) && $olduser->info == "notincourse")) { // it's possible that user is not in the course
7669 continue;
7671 $assignment->userid = $olduser->new_id; // new userid here
7672 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$assignment->modifierid);
7673 $assignment->modifierid = !empty($oldmodifier->new_id) ? $oldmodifier->new_id : 0; // new modifier id here
7674 $assignment->roleid = $role->new_id; // restored new role id
7676 // hack to make the correct contextid for course level imports
7677 if ($contextlevel == CONTEXT_COURSE) {
7678 $oldinstance->new_id = $restore->course_id;
7679 } else {
7680 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
7683 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
7684 $assignment->contextid = $newcontext->id; // new context id
7685 // might already have same assignment
7686 role_assign($assignment->roleid, $assignment->userid, 0, $assignment->contextid, $assignment->timestart, $assignment->timeend, $assignment->hidden, $assignment->enrol, $assignment->timemodified);
7691 // auxillary function to write role assignments read from xml to db
7692 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
7694 // it is possible to have an override not relevant to this course context.
7695 // should be ignored(?)
7696 if (!$role = backup_getid($restore->backup_unique_code, "role", $oldroleid)) {
7697 return null;
7700 foreach ($overrides as $override) {
7701 $override->capability = $override->name;
7702 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$override->modifierid);
7703 $override->modifierid = $oldmodifier->new_id?$oldmodifier->new_id:0; // new modifier id here
7704 $override->roleid = $role->new_id; // restored new role id
7706 // hack to make the correct contextid for course level imports
7707 if ($contextlevel == CONTEXT_COURSE) {
7708 $oldinstance->new_id = $restore->course_id;
7709 } else {
7710 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
7713 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
7714 $override->contextid = $newcontext->id; // new context id
7715 // use assign capability instead so we can add context to context_rel
7716 assign_capability($override->capability, $override->permission, $override->roleid, $override->contextid);
7719 //write activity date changes to the html log file, and update date values in the the xml array
7720 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
7722 global $CFG;
7723 $openlog = false;
7725 // loop through time fields in $TAGS
7726 foreach ($TAGS as $TAG) {
7728 // check $TAG has a sensible value
7729 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
7731 if ($openlog==false) {
7732 $openlog = true; // only come through here once
7734 // open file for writing
7735 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
7736 check_dir_exists($course_dir, true);
7737 $restorelog = fopen("$course_dir/restorelog.html", "a");
7739 // start output for this record
7740 $msg = new stdClass();
7741 $msg->recordtype = $recordtype;
7742 $msg->recordname = $xml[$NAMETAG][0]['#'];
7743 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
7746 // write old date to $restorelog
7747 $value = $xml[$TAG][0]['#'];
7748 $date = usergetdate($value);
7750 $msg = new stdClass();
7751 $msg->TAG = $TAG;
7752 $msg->weekday = $date['weekday'];
7753 $msg->mday = $date['mday'];
7754 $msg->month = $date['month'];
7755 $msg->year = $date['year'];
7756 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
7758 // write new date to $restorelog
7759 $value += $restore->course_startdateoffset;
7760 $date = usergetdate($value);
7762 $msg = new stdClass();
7763 $msg->TAG = $TAG;
7764 $msg->weekday = $date['weekday'];
7765 $msg->mday = $date['mday'];
7766 $msg->month = $date['month'];
7767 $msg->year = $date['year'];
7768 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
7770 // update $value in $xml tree for calling module
7771 $xml[$TAG][0]['#'] = "$value";
7774 // close the restore log, if it was opened
7775 if ($openlog) {
7776 fclose($restorelog);