adding current groupid to grade_export class - soon to be used in plugins
[moodle-pu.git] / backup / restorelib.php
blobfdd939830af6a5feb8976839b35fcb70c32fc296
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 $ggthcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_grades_text_history');
1202 $gihcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_items_history');
1203 $gohcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'grade_outcomes_history');
1205 // we need to know if all grade items that were backed up are being restored
1206 // if that is not the case, we do not restore grade categories nor gradeitems of category type or course type
1207 // i.e. the aggregated grades of that category
1209 $restoreall = true; // set to false if any grade_item is not selected/restored
1211 if ($recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'", "old_id", "old_id, old_id")) {
1212 foreach ($recs as $rec) {
1214 if ($data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id)) {
1216 $info = $data->info;
1217 // do not restore if this grade_item is a mod, and
1218 $itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1221 if ($itemtype == 'mod') {
1223 $iteminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1224 $itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1225 if (!restore_userdata_selected($restore, $itemmodule, $iteminstance)) {
1226 // module instance not selected when restored using granular
1227 // we are not restoring all grade items, set flag to false
1228 // so that we do not process grade categories and related grade items/grades
1229 $restoreall = false;
1230 break;
1237 // return if nothing to restore
1238 if (!$itemscount && !$categoriescount && !$outcomecount) {
1239 return $status;
1242 // Start ul
1243 if (!defined('RESTORE_SILENTLY')) {
1244 echo '<ul>';
1247 // fetch the course grade item
1249 require_once($CFG->libdir.'/grade/grade_item.php');
1250 require_once($CFG->libdir.'/grade/grade_category.php');
1251 require_once($CFG->libdir.'/gradelib.php');
1252 $courseitem = grade_item::fetch_course_item($restore->course_id);
1253 $coursecategory = grade_category::fetch_course_category($restore->course_id);
1255 // Number of records to get in every chunk
1256 $recordset_size = 2;
1257 // Flag to mark if we must continue
1258 $continue = true;
1260 // Process categories
1261 if ($categoriescount && $continue && $restoreall) {
1262 if (!defined('RESTORE_SILENTLY')) {
1263 echo '<li>'.get_string('gradecategories','grades').'</li>';
1265 $counter = 0;
1266 while ($counter < $categoriescount) {
1267 // Fetch recordset_size records in each iteration
1268 $recs = get_records_select("backup_ids","table_name = 'grade_categories' AND backup_code = '$restore->backup_unique_code'",
1269 "old_id",
1270 "old_id, old_id",
1271 $counter,
1272 $recordset_size);
1273 if ($recs) {
1274 foreach ($recs as $rec) {
1275 // Get the full record from backup_ids
1276 $data = backup_getid($restore->backup_unique_code,'grade_categories',$rec->old_id);
1277 if ($data) {
1278 // Now get completed xmlized object
1279 $info = $data->info;
1280 //traverse_xmlize($info); //Debug
1281 //print_object ($GLOBALS['traverse_array']); //Debug
1282 //$GLOBALS['traverse_array']=""; //Debug
1283 //Now build the GRADE_PREFERENCES record structure
1285 $dbrec->courseid = $restore->course_id;
1286 // categories are not backed up during import.
1287 // however, depth 1 categories needs to be skipped during restore into exisiting course
1289 // get the new grade category parent
1291 //if (!empty($info['GRADE_CATEGORY']['#']['PARENT']['0']['#']) && $info['GRADE_CATEGORY']['#']['PARENT']['0']['#'] != '$@NULL@$') {
1293 $parent = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_CATEGORY']['#']['PARENT']['0']['#']));
1294 if (isset($parent->new_id)) {
1295 $dbrec->parent = $parent->new_id;
1296 } else {
1297 // orphans should get adopted by course category
1298 $dbrec->parent = $coursecategory->id;
1302 $dbrec->fullname = backup_todb($info['GRADE_CATEGORY']['#']['FULLNAME']['0']['#']);
1303 $dbrec->aggregation = backup_todb($info['GRADE_CATEGORY']['#']['AGGREGATION']['0']['#']);
1304 $dbrec->keephigh = backup_todb($info['GRADE_CATEGORY']['#']['KEEPHIGH']['0']['#']);
1305 $dbrec->droplow = backup_todb($info['GRADE_CATEGORY']['#']['DROPLOW']['0']['#']);
1306 $dbrec->aggregateoutcomes = backup_todb($info['GRADE_CATEGORY']['#']['AGGREGATEOUTCOMES']['0']['#']);
1308 //Structure is equal to db, insert record
1309 //if the fullname doesn't exist
1310 if (!$prerec = get_record('grade_categories','courseid',$dbrec->courseid,'fullname',$dbrec->fullname)) {
1311 $newid = insert_record('grade_categories',$dbrec);
1312 $status = backup_putid($restore->backup_unique_code,'grade_categories',$rec->old_id,$newid);
1313 // update this record so we can put in the right paths
1314 // this can only be done after we got the new id
1315 $dbrec->id = $newid;
1316 include_once($CFG->dirroot.'/lib/grade/grade_category.php');
1317 // rebuild the path, we need only parents info
1318 // the order of restoring should ensure that the parent and grandparent(s)
1319 // are already restored
1320 $dbrec->path = grade_category::build_path($dbrec);
1321 // this is not needed in the xml because
1322 // given this parent and grandparent(s) we can recalculate the depth
1323 $dbrec->depth = substr_count($dbrec->path, '/');
1324 update_record('grade_categories', $dbrec);
1325 } else {
1326 // if fullname already exists, we should keep the current grade category
1327 $status = backup_putid($restore->backup_unique_code,'grade_categories',$rec->old_id,$rec->oldid);
1330 //Increment counters
1331 $counter++;
1332 //Do some output
1333 if ($counter % 1 == 0) {
1334 if (!defined('RESTORE_SILENTLY')) {
1335 echo ".";
1336 if ($counter % 20 == 0) {
1337 echo "<br />";
1340 backup_flush(300);
1347 // process outcomes
1348 if ($outcomecount && $continue) {
1349 if (!defined('RESTORE_SILENTLY')) {
1350 echo '<li>'.get_string('gradeoutcomes','grades').'</li>';
1352 $counter = 0;
1353 while ($counter < $outcomecount) {
1354 //Fetch recordset_size records in each iteration
1355 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes' AND backup_code = '$restore->backup_unique_code'",
1356 "old_id",
1357 "old_id, old_id",
1358 $counter,
1359 $recordset_size);
1360 if ($recs) {
1361 foreach ($recs as $rec) {
1362 //Get the full record from backup_ids
1363 $data = backup_getid($restore->backup_unique_code,'grade_outcomes',$rec->old_id);
1364 if ($data) {
1365 //Now get completed xmlized object
1366 $info = $data->info;
1367 //traverse_xmlize($info); //Debug
1368 //print_object ($GLOBALS['traverse_array']); //Debug
1369 //$GLOBALS['traverse_array']=""; //Debug
1370 //Now build the GRADE_PREFERENCES record structure
1371 if ($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#']) {
1372 $dbrec->courseid = $restore->course_id;
1373 } else {
1374 $dbrec->courseid = NULL;
1376 $dbrec->shortname = backup_todb($info['GRADE_OUTCOME']['#']['SHORTNAME']['0']['#']);
1377 $dbrec->fullname = backup_todb($info['GRADE_OUTCOME']['#']['FULLNAME']['0']['#']);
1379 if ($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#']) {
1380 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_OUTCOME']['#']['SCALEID']['0']['#']));
1381 $dbrec->scaleid = $scale->new_id;
1384 $modifier = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_OUTCOME']['#']['USERMODIFIED']['0']['#']));
1385 $dbrec->usermodified = $modifier->new_id;
1387 // Structure is equal to db, insert record
1388 // If the shortname doesn't exist
1390 if (empty($info['GRADE_OUTCOME']['#']['COURSEID']['0']['#'])) {
1391 $prerec = get_record_sql("SELECT * FROM {$CFG->prefix}grade_outcomes
1392 WHERE courseid IS NULL
1393 AND shortname = '$dbrec->shortname'");
1394 } else {
1395 $prerec = get_record('grade_outcomes','courseid',$restore->course_id,'shortname',$dbrec->shortname);
1398 if (!$prerec) {
1399 $newid = insert_record('grade_outcomes',$dbrec);
1400 } else {
1401 $newid = $prerec->id;
1404 if ($newid) {
1405 backup_putid($restore->backup_unique_code,"grade_outcomes", $rec->old_id, $newid);
1408 //Increment counters
1409 $counter++;
1410 //Do some output
1411 if ($counter % 1 == 0) {
1412 if (!defined('RESTORE_SILENTLY')) {
1413 echo ".";
1414 if ($counter % 20 == 0) {
1415 echo "<br />";
1418 backup_flush(300);
1425 // process outcomescourses
1426 if ($outcomescoursescount && $continue) {
1427 if (!defined('RESTORE_SILENTLY')) {
1428 echo '<li>'.get_string('gradeoutcomescourses','grades').'</li>';
1430 $counter = 0;
1431 while ($counter < $outcomescoursescount) {
1432 //Fetch recordset_size records in each iteration
1433 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes_courses' AND backup_code = '$restore->backup_unique_code'",
1434 "old_id",
1435 "old_id, old_id",
1436 $counter,
1437 $recordset_size);
1438 if ($recs) {
1439 foreach ($recs as $rec) {
1440 //Get the full record from backup_ids
1441 $data = backup_getid($restore->backup_unique_code,'grade_outcomes_courses',$rec->old_id);
1442 if ($data) {
1443 //Now get completed xmlized object
1444 $info = $data->info;
1445 //traverse_xmlize($info); //Debug
1446 //print_object ($GLOBALS['traverse_array']); //Debug
1447 //$GLOBALS['traverse_array']=""; //Debug
1449 $oldoutcomesid = backup_todb($info['GRADE_OUTCOMES_COURSE']['#']['OUTCOMEID']['0']['#']);
1450 $newoutcome = backup_getid($restore->backup_unique_code,"grade_outcomes",$oldoutcomesid);
1451 unset($dbrec);
1452 $dbrec->courseid = $restore->course_id;
1453 $dbrec->outcomeid = $newoutcome->new_id;
1454 insert_record('grade_outcomes_courses', $dbrec);
1456 //Increment counters
1457 $counter++;
1458 //Do some output
1459 if ($counter % 1 == 0) {
1460 if (!defined('RESTORE_SILENTLY')) {
1461 echo ".";
1462 if ($counter % 20 == 0) {
1463 echo "<br />";
1466 backup_flush(300);
1473 // Process grade items (grade_raw, grade_final, and grade_text)
1474 if ($itemscount && $continue) {
1475 if (!defined('RESTORE_SILENTLY')) {
1476 echo '<li>'.get_string('gradeitems','grades').'</li>';
1478 $counter = 0;
1479 $counteritems = 0;
1480 while ($counteritems < $itemscount) {
1482 //Fetch recordset_size records in each iteration
1483 $recs = get_records_select("backup_ids","table_name = 'grade_items' AND backup_code = '$restore->backup_unique_code'",
1484 "old_id",
1485 "old_id, old_id",
1486 $counteritems,
1487 $recordset_size);
1489 if ($recs) {
1490 foreach ($recs as $rec) {
1491 //Get the full record from backup_ids
1492 $data = backup_getid($restore->backup_unique_code,'grade_items',$rec->old_id);
1493 if ($data) {
1494 //Now get completed xmlized object
1495 $info = $data->info;
1496 //traverse_xmlize($info); //Debug
1497 //print_object ($GLOBALS['traverse_array']); //Debug
1498 //$GLOBALS['traverse_array']=""; //Debug
1500 $dbrec->courseid = $restore->course_id;
1502 if (isset($SESSION->restore->importing)) {
1503 // if we are importing, points all grade_items to the course category
1504 $coursecat = get_record('grade_categories', 'courseid', $restore->course_id, 'depth', 1);
1505 $dbrec->categoryid = $coursecat->id;
1506 } else if (!empty($info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']) && $info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']!='$@NULL@$') {
1507 $category = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_ITEM']['#']['CATEGORYID']['0']['#']));
1508 if ($category->new_id) {
1509 $dbrec->categoryid = $category->new_id;
1510 } else {
1511 // this could be restoring into existing course, and grade item points to the old course grade item (category)
1512 // which was never imported. In this case we just point them to the new course item
1513 $dbrec->categoryid = $coursecategory->id;
1517 $dbrec->itemname = backup_todb($info['GRADE_ITEM']['#']['ITEMNAME']['0']['#']);
1518 $dbrec->itemtype = backup_todb($info['GRADE_ITEM']['#']['ITEMTYPE']['0']['#']);
1519 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM']['#']['ITEMMODULE']['0']['#']);
1520 /// this needs to point to either the new mod id
1521 /// or the category id
1522 $iteminstance = backup_todb($info['GRADE_ITEM']['#']['ITEMINSTANCE']['0']['#']);
1523 // do not restore if this grade_item is a mod, and
1524 if ($dbrec->itemtype == 'mod') {
1526 // iteminstance should point to new mod
1528 $mod = backup_getid($restore->backup_unique_code,$dbrec->itemmodule, $iteminstance);
1529 $dbrec->iteminstance = $mod->new_id;
1531 } else if ($dbrec->itemtype == 'category') {
1532 // the item instance should point to the new grade category
1534 // only proceed if we are restoring all grade items
1535 // need to skip for imports
1536 if ($restoreall && !isset($SESSION->restore->importing)) {
1537 $category = backup_getid($restore->backup_unique_code,'grade_categories', $iteminstance);
1538 $dbrec->iteminstance = $category->new_id;
1539 } else {
1540 // otherwise we can safely ignore this grade item and subsequent
1541 // grade_raws, grade_finals etc
1542 $counteritems++;
1543 continue;
1545 } elseif ($dbrec->itemtype == 'course') { // We don't restore course type to avoid duplicate course items
1547 if ($restoreall && !isset($SESSION->restore->importing) && $restore->restoreto == 2) {
1548 // TODO any special code needed here to restore course item without duplicating it?
1549 // find the course category with depth 1, and course id = current course id
1550 // this would have been already restored
1551 $counteritems++;
1552 continue;
1553 } else {
1554 $counteritems++;
1555 continue;
1559 $dbrec->itemnumber = backup_todb($info['GRADE_ITEM']['#']['ITEMNUMBER']['0']['#']);
1560 $dbrec->iteminfo = backup_todb($info['GRADE_ITEM']['#']['ITEMINFO']['0']['#']);
1561 $dbrec->idnumber = backup_todb($info['GRADE_ITEM']['#']['IDNUMBER']['0']['#']);
1562 $dbrec->calculation = backup_todb($info['GRADE_ITEM']['#']['CALCULATION']['0']['#']);
1563 $dbrec->grademax = backup_todb($info['GRADE_ITEM']['#']['GRADEMAX']['0']['#']);
1564 $dbrec->grademin = backup_todb($info['GRADE_ITEM']['#']['GRADEMIN']['0']['#']);
1565 /// needs to be restored first
1567 if ($info['GRADE_ITEM']['#']['SCALEID']['0']['#']) {
1568 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($info['GRADE_ITEM']['#']['SCALEID']['0']['#']));
1569 $dbrec->scaleid = $scale->new_id;
1572 /// needs to be restored first
1573 $dbrec->outcomeid = backup_getid($restore->backup_unique_code,"grade_outcomes",backup_todb($info['GRADE_ITEM']['#']['OUTCOMEID']['0']['#']));
1575 $dbrec->gradepass = backup_todb($info['GRADE_ITEM']['#']['GRADEPASS']['0']['#']);
1576 $dbrec->multfactor = backup_todb($info['GRADE_ITEM']['#']['MULTFACTOR']['0']['#']);
1577 $dbrec->plusfactor = backup_todb($info['GRADE_ITEM']['#']['PLUSFACTOR']['0']['#']);
1578 $dbrec->hidden = backup_todb($info['GRADE_ITEM']['#']['HIDDEN']['0']['#']);
1579 $dbrec->locked = backup_todb($info['GRADE_ITEM']['#']['LOCKED']['0']['#']);
1580 $dbrec->locktime = backup_todb($info['GRADE_ITEM']['#']['LOCKTIME']['0']['#']);
1582 // get the current sortorder, add 1 to it and use that
1583 if ($lastitem = get_record_sql("SELECT sortorder, id FROM {$CFG->prefix}grade_items
1584 WHERE courseid = $restore->course_id
1585 ORDER BY sortorder DESC ", true)) {
1587 // we just need the first one
1588 $dbrec->sortorder = $lastitem->sortorder + 1;
1589 } else {
1590 // this is the first grade_item
1591 $dbrec->sortorder = 1;
1593 // always insert, since modules restored to existing courses are always inserted
1594 $itemid = insert_record('grade_items',$dbrec);
1595 if ($itemid) {
1596 backup_putid($restore->backup_unique_code,'grade_items', backup_todb($info['GRADE_ITEM']['#']['ID']['0']['#']), $itemid);
1599 // no need to restore grades/grades_text if user data is not selected
1600 if ($dbrec->itemtype == 'mod' && !restore_userdata_selected($restore, $dbrec->itemmodule, $iteminstance)) {
1601 // module instance not selected when restored using granular
1602 // skip this item
1603 $counteritems++;
1604 continue;
1607 /// now, restore grade_grades, grade_text
1608 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']) && ($grades = $info['GRADE_ITEM']['#']['GRADE_GRADES']['0']['#']['GRADE'])) {
1609 //Iterate over items
1610 for($i = 0; $i < sizeof($grades); $i++) {
1611 $ite_info = $grades[$i];
1612 //traverse_xmlize($ite_info);
1613 //Debug
1614 //print_object ($GLOBALS['traverse_array']); //Debug
1615 //$GLOBALS['traverse_array']=""; //Debug
1616 //Now build the GRADE_ITEM record structure
1617 $grade = new object();
1618 $grade->itemid = $itemid;
1619 $user = backup_getid($restore->backup_unique_code,"user", backup_todb($ite_info['#']['USERID']['0']['#']));
1620 $grade->userid = $user->new_id;
1621 $grade->rawgrade = backup_todb($ite_info['#']['RAWGRADE']['0']['#']);
1622 $grade->rawgrademax = backup_todb($ite_info['#']['RAWGRADEMAX']['0']['#']);
1623 $grade->rawgrademin = backup_todb($ite_info['#']['RAWGRADEMIN']['0']['#']);
1624 // need to find scaleid
1625 if ($ite_info['#']['RAWSCALEID']['0']['#']) {
1626 $scale = backup_getid($restore->backup_unique_code,"scale",backup_todb($ite_info['#']['RAWSCALEID']['0']['#']));
1627 $grade->rawscaleid = $scale->new_id;
1629 $grade->finalgrade = backup_todb($ite_info['#']['FINALGRADE']['0']['#']);
1630 $grade->hidden = backup_todb($ite_info['#']['HIDDEN']['0']['#']);
1631 $grade->locked = backup_todb($ite_info['#']['LOCKED']['0']['#']);
1632 $grade->locktime = backup_todb($ite_info['#']['LOCKTIME']['0']['#']);
1633 $grade->exported = backup_todb($ite_info['#']['EXPORTED']['0']['#']);
1634 $grade->overridden = backup_todb($ite_info['#']['OVERRIDDEN']['0']['#']);
1635 $grade->excluded = backup_todb($ite_info['#']['EXCLUDED']['0']['#']);
1637 $newid = insert_record('grade_grades', $grade);
1639 if ($newid) {
1640 backup_putid($restore->backup_unique_code,"grade_grades", backup_todb($ite_info['#']['ID']['0']['#']), $newid);
1642 $counter++;
1643 if ($counter % 20 == 0) {
1644 if (!defined('RESTORE_SILENTLY')) {
1645 echo ".";
1646 if ($counter % 400 == 0) {
1647 echo "<br />";
1650 backup_flush(300);
1657 /// processing grade_grades_text
1658 if (!empty($info['GRADE_ITEM']['#']['GRADE_GRADES_TEXT']['0']['#']) && ($texts = $info['GRADE_ITEM']['#']['GRADE_GRADES_TEXT']['0']['#']['GRADE_TEXT'])) {
1659 //Iterate over items
1660 for($i = 0; $i < sizeof($texts); $i++) {
1661 $ite_info = $texts[$i];
1662 //traverse_xmlize($ite_info); //Debug
1663 //print_object ($GLOBALS['traverse_array']); //Debug
1664 //$GLOBALS['traverse_array']=""; //Debug
1665 $grade = backup_getid($restore->backup_unique_code,"grade_grades", backup_todb($ite_info['#']['GRADEID']['0']['#']));
1667 $text = new object();
1668 $text->gradeid = $grade->new_id;
1669 $text->information = backup_todb($ite_info['#']['INFORMATION']['0']['#']);
1670 $text->informationformat = backup_todb($ite_info['#']['INFORMATIONFORMAT']['0']['#']);
1671 $text->feedback = backup_todb($ite_info['#']['FEEDBACK']['0']['#']);
1672 $text->feedbackformat = backup_todb($ite_info['#']['FEEDBACKFORMAT']['0']['#']);
1674 $newid = insert_record('grade_grades_text', $text);
1675 if ($newid) {
1676 backup_putid($restore->backup_unique_code,'grade_grades_text', backup_todb($ite_info['#']['ID']['0']['#']), $newid);
1678 $counter++;
1679 if ($counter % 20 == 0) {
1680 if (!defined('RESTORE_SILENTLY')) {
1681 echo ".";
1682 if ($counter % 400 == 0) {
1683 echo "<br />";
1686 backup_flush(300);
1691 $counteritems++; // increment item count
1698 // process histories
1699 if ($gchcount && $continue && !isset($SESSION->restore->importing)) {
1700 if (!defined('RESTORE_SILENTLY')) {
1701 echo '<li>'.get_string('gradecategoryhistory','grades').'</li>';
1703 $counter = 0;
1704 while ($counter < $gchcount) {
1705 //Fetch recordset_size records in each iteration
1706 $recs = get_records_select("backup_ids","table_name = 'grade_categories_history' AND backup_code = '$restore->backup_unique_code'",
1707 "old_id",
1708 "old_id, old_id",
1709 $counter,
1710 $recordset_size);
1711 if ($recs) {
1712 foreach ($recs as $rec) {
1713 //Get the full record from backup_ids
1714 $data = backup_getid($restore->backup_unique_code,'grade_categories_history',$rec->old_id);
1715 if ($data) {
1716 //Now get completed xmlized object
1717 $info = $data->info;
1718 //traverse_xmlize($info); //Debug
1719 //print_object ($GLOBALS['traverse_array']); //Debug
1720 //$GLOBALS['traverse_array']=""; //Debug
1722 $oldobj = backup_getid($restore->backup_unique_code,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['OLDID']['0']['#']));
1723 if (empty($oldobj->new_id)) {
1724 // if the old object is not being restored, can't restoring its history
1725 $counter++;
1726 continue;
1728 $dbrec->oldid = $oldobj->new_id;
1729 $dbrec->action = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['ACTION']['0']['#']);
1730 $dbrec->source = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['SOURCE']['0']['#']);
1731 $dbrec->timemodified = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1733 // loggeduser might not be restored, e.g. admin
1734 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1735 $dbrec->loggeduser = $oldobj->new_id;
1738 // this item might not have a parent at all, do not skip it if no parent is specified
1739 if (backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#'])) {
1740 $oldobj = backup_getid($restore->backup_unique_code,"grade_categories", backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PARENT']['0']['#']));
1741 if (empty($oldobj->new_id)) {
1742 // if the parent category not restored
1743 $counter++;
1744 continue;
1747 $dbrec->parent = $oldobj->new_id;
1748 $dbrec->depth = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DEPTH']['0']['#']);
1749 // path needs to be rebuilt
1750 if ($path = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['PATH']['0']['#'])) {
1751 // to preserve the path and make it work, we need to replace the categories one by one
1752 // we first get the list of categories in current path
1753 if ($paths = explode("/", $path)) {
1754 $newpath = '';
1755 foreach ($paths as $catid) {
1756 if ($catid) {
1757 // find the new corresponding path
1758 $oldpath = backup_getid($restore->backup_unique_code,"grade_categories", $catid);
1759 $newpath .= "/$oldpath->new_id";
1762 $dbrec->path = $newpath;
1765 $dbrec->fullname = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['FULLNAME']['0']['#']);
1766 $dbrec->aggregation = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['AGGRETGATION']['0']['#']);
1767 $dbrec->keephigh = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['KEEPHIGH']['0']['#']);
1768 $dbrec->droplow = backup_todb($info['GRADE_CATEGORIES_HISTORY']['#']['DROPLOW']['0']['#']);
1769 $dbrec->courseid = $restore->course_id;
1770 insert_record('grade_categories_history', $dbrec);
1771 unset($dbrec);
1774 //Increment counters
1775 $counter++;
1776 //Do some output
1777 if ($counter % 1 == 0) {
1778 if (!defined('RESTORE_SILENTLY')) {
1779 echo ".";
1780 if ($counter % 20 == 0) {
1781 echo "<br />";
1784 backup_flush(300);
1791 // process histories
1792 if ($gghcount && $continue && !isset($SESSION->restore->importing)) {
1793 if (!defined('RESTORE_SILENTLY')) {
1794 echo '<li>'.get_string('gradegradeshistory','grades').'</li>';
1796 $counter = 0;
1797 while ($counter < $gghcount) {
1798 //Fetch recordset_size records in each iteration
1799 $recs = get_records_select("backup_ids","table_name = 'grade_grades_history' AND backup_code = '$restore->backup_unique_code'",
1800 "old_id",
1801 "old_id, old_id",
1802 $counter,
1803 $recordset_size);
1804 if ($recs) {
1805 foreach ($recs as $rec) {
1806 //Get the full record from backup_ids
1807 $data = backup_getid($restore->backup_unique_code,'grade_grades_history',$rec->old_id);
1808 if ($data) {
1809 //Now get completed xmlized object
1810 $info = $data->info;
1811 //traverse_xmlize($info); //Debug
1812 //print_object ($GLOBALS['traverse_array']); //Debug
1813 //$GLOBALS['traverse_array']=""; //Debug
1815 $oldobj = backup_getid($restore->backup_unique_code,"grade_grades", backup_todb($info['GRADE_GRADES_HISTORY']['#']['OLDID']['0']['#']));
1816 if (empty($oldobj->new_id)) {
1817 // if the old object is not being restored, can't restoring its history
1818 $counter++;
1819 continue;
1821 $dbrec->oldid = $oldobj->new_id;
1822 $dbrec->action = backup_todb($info['GRADE_GRADES_HISTORY']['#']['ACTION']['0']['#']);
1823 $dbrec->source = backup_todb($info['GRADE_GRADES_HISTORY']['#']['SOURCE']['0']['#']);
1824 $dbrec->timemodified = backup_todb($info['GRADE_GRADES_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1825 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1826 $dbrec->loggeduser = $oldobj->new_id;
1828 $oldobj = backup_getid($restore->backup_unique_code,"grade_items", backup_todb($info['GRADE_GRADES_HISTORY']['#']['ITEMID']['0']['#']));
1829 $dbrec->itemid = $oldobj->new_id;
1830 if (empty($dbrec->itemid)) {
1831 $counter++;
1832 continue; // grade item not being restored
1834 $oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERID']['0']['#']));
1835 $dbrec->userid = $oldobj->new_id;
1836 $dbrec->rawgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADE']['0']['#']);
1837 $dbrec->rawgrademax = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMAX']['0']['#']);
1838 $dbrec->rawgrademin = backup_todb($info['GRADE_GRADES_HISTORY']['#']['RAWGRADEMIN']['0']['#']);
1839 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_GRADES_HISTORY']['#']['USERMODIFIED']['0']['#']))) {
1840 $dbrec->usermodified = $oldobj->new_id;
1842 $dbrec->finalgrade = backup_todb($info['GRADE_GRADES_HISTORY']['#']['FINALGRADE']['0']['#']);
1843 $dbrec->hidden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['HIDDEN']['0']['#']);
1844 $dbrec->locked = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKED']['0']['#']);
1845 $dbrec->locktime = backup_todb($info['GRADE_GRADES_HISTORY']['#']['LOCKTIME']['0']['#']);
1846 $dbrec->exported = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXPORTED']['0']['#']);
1847 $dbrec->overridden = backup_todb($info['GRADE_GRADES_HISTORY']['#']['OVERRIDDEN']['0']['#']);
1848 $dbrec->excluded = backup_todb($info['GRADE_GRADES_HISTORY']['#']['EXCLUDED']['0']['#']);
1850 insert_record('grade_grades_history', $dbrec);
1851 unset($dbrec);
1854 //Increment counters
1855 $counter++;
1856 //Do some output
1857 if ($counter % 1 == 0) {
1858 if (!defined('RESTORE_SILENTLY')) {
1859 echo ".";
1860 if ($counter % 20 == 0) {
1861 echo "<br />";
1864 backup_flush(300);
1871 // process histories
1873 if ($ggthcount && $continue && !isset($SESSION->restore->importing)) {
1874 if (!defined('RESTORE_SILENTLY')) {
1875 echo '<li>'.get_string('gradegradestexthistory','grades').'</li>';
1877 $counter = 0;
1878 while ($counter < $ggthcount) {
1879 //Fetch recordset_size records in each iteration
1880 $recs = get_records_select("backup_ids","table_name = 'grade_grades_text_history' AND backup_code = '$restore->backup_unique_code'",
1881 "old_id",
1882 "old_id, old_id",
1883 $counter,
1884 $recordset_size);
1886 if ($recs) {
1887 foreach ($recs as $rec) {
1888 //Get the full record from backup_ids
1889 $data = backup_getid($restore->backup_unique_code,'grade_grades_text_history',$rec->old_id);
1890 if ($data) {
1891 //Now get completed xmlized object
1892 $info = $data->info;
1893 //traverse_xmlize($info); //Debug
1894 //print_object ($GLOBALS['traverse_array']); //Debug
1895 //$GLOBALS['traverse_array']=""; //Debug
1897 $oldobj = backup_getid($restore->backup_unique_code,"grade_grades_text", backup_todb($info['GRADE_TEXT_HISTORY']['#']['OLDID']['0']['#']));
1898 if (empty($oldobj->new_id)) {
1899 // if the old object is not being restored, can't restoring its history
1900 $counter++;
1901 continue;
1903 $dbrec->oldid = $oldobj->new_id;
1904 $dbrec->action = backup_todb($info['GRADE_TEXT_HISTORY']['#']['ACTION']['0']['#']);
1905 $dbrec->source = backup_todb($info['GRADE_TEXT_HISTORY']['#']['SOURCE']['0']['#']);
1906 $dbrec->timemodified = backup_todb($info['GRADE_TEXT_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1907 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_TEXT_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1908 $dbrec->loggeduser = $oldobj->new_id;
1910 $oldobj = backup_getid($restore->backup_unique_code,"grade_grades", backup_todb($info['GRADE_TEXT_HISTORY']['#']['GRADEID']['0']['#']));
1911 $dbrec->gradeid = $oldobj->new_id;
1912 if (empty($dbrec->gradeid)) {
1913 $counter++;
1914 continue; // grade not being restore, possibly because grade item is not restored
1917 $dbrec->information = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATION']['0']['#']);
1918 $dbrec->informationformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['INFORMATIONFORMAT']['0']['#']);
1919 $dbrec->feedback = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACK']['0']['#']);
1920 $dbrec->feedbackformat = backup_todb($info['GRADE_TEXT_HISTORY']['#']['FEEDBACKFORMAT']['0']['#']);
1921 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_TEXT_HISTORY']['#']['USERMODIFIED']['0']['#']))) {
1922 $dbrec->usermodified = $oldobj->new_id;
1925 insert_record('grade_grades_text_history', $dbrec);
1926 unset($dbrec);
1929 //Increment counters
1930 $counter++;
1931 //Do some output
1932 if ($counter % 1 == 0) {
1933 if (!defined('RESTORE_SILENTLY')) {
1934 echo ".";
1935 if ($counter % 20 == 0) {
1936 echo "<br />";
1939 backup_flush(300);
1946 // process histories
1947 if ($gihcount && $continue && !isset($SESSION->restore->importing)) {
1948 if (!defined('RESTORE_SILENTLY')) {
1949 echo '<li>'.get_string('gradeitemshistory','grades').'</li>';
1951 $counter = 0;
1952 while ($counter < $gihcount) {
1953 //Fetch recordset_size records in each iteration
1954 $recs = get_records_select("backup_ids","table_name = 'grade_items_history' AND backup_code = '$restore->backup_unique_code'",
1955 "old_id",
1956 "old_id, old_id",
1957 $counter,
1958 $recordset_size);
1959 if ($recs) {
1960 foreach ($recs as $rec) {
1961 //Get the full record from backup_ids
1962 $data = backup_getid($restore->backup_unique_code,'grade_items_history',$rec->old_id);
1963 if ($data) {
1964 //Now get completed xmlized object
1965 $info = $data->info;
1966 //traverse_xmlize($info); //Debug
1967 //print_object ($GLOBALS['traverse_array']); //Debug
1968 //$GLOBALS['traverse_array']=""; //Debug
1971 $oldobj = backup_getid($restore->backup_unique_code,"grade_items", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OLDID']['0']['#']));
1972 if (empty($oldobj->new_id)) {
1973 // if the old object is not being restored, can't restoring its history
1974 $counter++;
1975 continue;
1977 $dbrec->oldid = $oldobj->new_id;
1978 $dbrec->action = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ACTION']['0']['#']);
1979 $dbrec->source = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SOURCE']['0']['#']);
1980 $dbrec->timemodified = backup_todb($info['GRADE_ITEM_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
1981 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
1982 $dbrec->loggeduser = $oldobj->new_id;
1984 $oldobj = backup_getid($restore->backup_unique_code,'grade_categories',backup_todb($info['GRADE_ITEM_HISTORY']['#']['CATEGORYID']['0']['#']));
1985 $oldobj->categoryid = $category->new_id;
1986 if (empty($oldobj->categoryid)) {
1987 $counter++;
1988 continue; // category not restored
1991 $dbrec->itemname= backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNAME']['0']['#']);
1992 $dbrec->itemtype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMTYPE']['0']['#']);
1993 $dbrec->itemmodule = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMMODULE']['0']['#']);
1995 // code from grade_items restore
1996 $iteminstance = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINSTANCE']['0']['#']);
1997 // do not restore if this grade_item is a mod, and
1998 if ($dbrec->itemtype == 'mod') {
2000 if (!restore_userdata_selected($restore, $dbrec->itemmodule, $iteminstance)) {
2001 // module instance not selected when restored using granular
2002 // skip this item
2003 $counter++;
2004 continue;
2007 // iteminstance should point to new mod
2009 $mod = backup_getid($restore->backup_unique_code,$dbrec->itemmodule, $iteminstance);
2010 $dbrec->iteminstance = $mod->new_id;
2012 } else if ($dbrec->itemtype == 'category') {
2013 // the item instance should point to the new grade category
2015 // only proceed if we are restoring all grade items
2016 if ($restoreall) {
2017 $category = backup_getid($restore->backup_unique_code,'grade_categories', $iteminstance);
2018 $dbrec->iteminstance = $category->new_id;
2019 } else {
2020 // otherwise we can safely ignore this grade item and subsequent
2021 // grade_raws, grade_finals etc
2022 continue;
2024 } elseif ($dbrec->itemtype == 'course') { // We don't restore course type to avoid duplicate course items
2025 if ($restoreall) {
2026 // TODO any special code needed here to restore course item without duplicating it?
2027 // find the course category with depth 1, and course id = current course id
2028 // this would have been already restored
2030 $cat = get_record('grade_categories', 'depth', 1, 'courseid', $restore->course_id);
2031 $dbrec->iteminstance = $cat->id;
2033 } else {
2034 $counter++;
2035 continue;
2039 $dbrec->itemnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMNUMBER']['0']['#']);
2040 $dbrec->iteminfo = backup_todb($info['GRADE_ITEM_HISTORY']['#']['ITEMINFO']['0']['#']);
2041 $dbrec->idnumber = backup_todb($info['GRADE_ITEM_HISTORY']['#']['IDNUMBER']['0']['#']);
2042 $dbrec->calculation = backup_todb($info['GRADE_ITEM_HISTORY']['#']['CALCULATION']['0']['#']);
2043 $dbrec->gradetype = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADETYPE']['0']['#']);
2044 $dbrec->grademax = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMAX']['0']['#']);
2045 $dbrec->grademin = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEMIN']['0']['#']);
2046 if ($oldobj = backup_getid($restore->backup_unique_code,"scale", backup_todb($info['GRADE_ITEM_HISTORY']['#']['SCALEID']['0']['#']))) {
2047 // scaleid is optional
2048 $dbrec->scaleid = $oldobj->new_id;
2050 if ($oldobj = backup_getid($restore->backup_unique_code,"grade_outcomes", backup_todb($info['GRADE_ITEM_HISTORY']['#']['OUTCOMEID']['0']['#']))) {
2051 // outcome is optional
2052 $dbrec->outcomeid = $oldobj->new_id;
2054 $dbrec->gradepass = backup_todb($info['GRADE_ITEM_HISTORY']['#']['GRADEPASS']['0']['#']);
2055 $dbrec->multfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['MULTFACTOR']['0']['#']);
2056 $dbrec->plusfactor = backup_todb($info['GRADE_ITEM_HISTORY']['#']['PLUSFACTOR']['0']['#']);
2057 $dbrec->aggregationcoef = backup_todb($info['GRADE_ITEM_HISTORY']['#']['AGGREGATIONCOEF']['0']['#']);
2058 $dbrec->sortorder = backup_todb($info['GRADE_ITEM_HISTORY']['#']['SORTORDER']['0']['#']);
2059 $dbrec->hidden = backup_todb($info['GRADE_ITEM_HISTORY']['#']['HIDDEN']['0']['#']);
2060 $dbrec->locked = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKED']['0']['#']);
2061 $dbrec->locktime = backup_todb($info['GRADE_ITEM_HISTORY']['#']['LOCKTIME']['0']['#']);
2062 $dbrec->needsupdate = backup_todb($info['GRADE_ITEM_HISTORY']['#']['NEEDSUPDATE']['0']['#']);
2064 insert_record('grade_items_history', $dbrec);
2065 unset($dbrec);
2068 //Increment counters
2069 $counter++;
2070 //Do some output
2071 if ($counter % 1 == 0) {
2072 if (!defined('RESTORE_SILENTLY')) {
2073 echo ".";
2074 if ($counter % 20 == 0) {
2075 echo "<br />";
2078 backup_flush(300);
2085 // process histories
2086 if ($gohcount && $continue && !isset($SESSION->restore->importing)) {
2087 if (!defined('RESTORE_SILENTLY')) {
2088 echo '<li>'.get_string('gradeoutcomeshistory','grades').'</li>';
2090 $counter = 0;
2091 while ($counter < $gohcount) {
2092 //Fetch recordset_size records in each iteration
2093 $recs = get_records_select("backup_ids","table_name = 'grade_outcomes_history' AND backup_code = '$restore->backup_unique_code'",
2094 "old_id",
2095 "old_id, old_id",
2096 $counter,
2097 $recordset_size);
2098 if ($recs) {
2099 foreach ($recs as $rec) {
2100 //Get the full record from backup_ids
2101 $data = backup_getid($restore->backup_unique_code,'grade_outcomes_history',$rec->old_id);
2102 if ($data) {
2103 //Now get completed xmlized object
2104 $info = $data->info;
2105 //traverse_xmlize($info); //Debug
2106 //print_object ($GLOBALS['traverse_array']); //Debug
2107 //$GLOBALS['traverse_array']=""; //Debug
2109 $oldobj = backup_getid($restore->backup_unique_code,"grade_outcomes", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['OLDID']['0']['#']));
2110 if (empty($oldobj->new_id)) {
2111 // if the old object is not being restored, can't restoring its history
2112 $counter++;
2113 continue;
2115 $dbrec->oldid = $oldobj->new_id;
2116 $dbrec->action = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['ACTION']['0']['#']);
2117 $dbrec->source = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SOURCE']['0']['#']);
2118 $dbrec->timemodified = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['TIMEMODIFIED']['0']['#']);
2119 if ($oldobj = backup_getid($restore->backup_unique_code,"user", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['LOGGEDUSER']['0']['#']))) {
2120 $dbrec->loggeduser = $oldobj->new_id;
2122 $dbrec->shortname = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SHORTNAME']['0']['#']);
2123 $dbrec->fullname= backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['FULLNAME']['0']['#']);
2124 $oldobj = backup_getid($restore->backup_unique_code,"scale", backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['SCALEID']['0']['#']));
2125 $dbrec->scaleid = $oldobj->new_id;
2126 $dbrec->description = backup_todb($info['GRADE_OUTCOME_HISTORY']['#']['DESCRIPTION']['0']['#']);
2128 insert_record('grade_outcomes_history', $dbrec);
2129 unset($dbrec);
2132 //Increment counters
2133 $counter++;
2134 //Do some output
2135 if ($counter % 1 == 0) {
2136 if (!defined('RESTORE_SILENTLY')) {
2137 echo ".";
2138 if ($counter % 20 == 0) {
2139 echo "<br />";
2142 backup_flush(300);
2149 if (!defined('RESTORE_SILENTLY')) {
2150 //End ul
2151 echo '</ul>';
2153 return $status;
2156 //This function creates all the user, user_students, user_teachers
2157 //user_course_creators and user_admins from xml
2158 function restore_create_users($restore,$xml_file) {
2160 global $CFG, $db;
2162 $status = true;
2163 //Check it exists
2164 if (!file_exists($xml_file)) {
2165 $status = false;
2167 //Get info from xml
2168 if ($status) {
2169 //info will contain the old_id of every user
2170 //in backup_ids->info will be the real info (serialized)
2171 $info = restore_read_xml_users($restore,$xml_file);
2174 //Now, get evey user_id from $info and user data from $backup_ids
2175 //and create the necessary records (users, user_students, user_teachers
2176 //user_course_creators and user_admins
2177 if (!empty($info->users)) {
2178 // Grab mnethosts keyed by wwwroot, to map to id
2179 $mnethosts = get_records('mnet_host', '', '',
2180 'wwwroot', 'wwwroot, id');
2182 $languages = get_list_of_languages();
2184 foreach ($info->users as $userid) {
2185 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
2186 $user = $rec->info;
2188 //Now, recode some languages (Moodle 1.5)
2189 if ($user->lang == 'ma_nt') {
2190 $user->lang = 'mi_nt';
2194 //If language does not exist here - use site default
2195 if (!array_key_exists($user->lang, $languages)) {
2196 $user->lang = $CFG->lang;
2199 //Check if it's admin and coursecreator
2200 $is_admin = !empty($user->roles['admin']);
2201 $is_coursecreator = !empty($user->roles['coursecreator']);
2203 //Check if it's teacher and student
2204 $is_teacher = !empty($user->roles['teacher']);
2205 $is_student = !empty($user->roles['student']);
2207 //Check if it's needed
2208 $is_needed = !empty($user->roles['needed']);
2210 //Calculate if it is a course user
2211 //Has role teacher or student or needed
2212 $is_course_user = ($is_teacher or $is_student or $is_needed);
2214 //Calculate mnethostid
2215 if (empty($user->mnethosturl) || $user->mnethosturl===$CFG->wwwroot) {
2216 $user->mnethostid = $CFG->mnet_localhost_id;
2217 } else {
2218 // fast url-to-id lookups
2219 if (isset($mnethosts[$user->mnethosturl])) {
2220 $user->mnethostid = $mnethosts[$user->mnethosturl]->id;
2221 } else {
2222 // should not happen, as we check in restore_chech.php
2223 // but handle the error if it does
2224 error("This backup file contains external Moodle Network Hosts that are not configured locally.");
2227 unset($user->mnethosturl);
2229 //To store new ids created
2230 $newid=null;
2231 //check if it exists (by username) and get its id
2232 $user_exists = true;
2233 $user_data = get_record("user","username",addslashes($user->username),
2234 'mnethostid', $user->mnethostid);
2235 if (!$user_data) {
2236 $user_exists = false;
2237 } else {
2238 $newid = $user_data->id;
2240 //Flags to see if we have to create the user, roles and preferences
2241 $create_user = true;
2242 $create_roles = true;
2243 $create_preferences = true;
2245 //If we are restoring course users and it isn't a course user
2246 if ($restore->users == 1 and !$is_course_user) {
2247 //If only restoring course_users and user isn't a course_user, inform to $backup_ids
2248 $status = backup_putid($restore->backup_unique_code,"user",$userid,null,'notincourse');
2249 $create_user = false;
2250 $create_roles = false;
2251 $create_preferences = false;
2254 if ($user_exists and $create_user) {
2255 //If user exists mark its newid in backup_ids (the same than old)
2256 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,'exists');
2257 $create_user = false;
2260 //Here, if create_user, do it
2261 if ($create_user) {
2262 //Unset the id because it's going to be inserted with a new one
2263 unset ($user->id);
2264 //We addslashes to necessary fields
2265 $user->username = addslashes($user->username);
2266 $user->firstname = addslashes($user->firstname);
2267 $user->lastname = addslashes($user->lastname);
2268 $user->email = addslashes($user->email);
2269 $user->institution = addslashes($user->institution);
2270 $user->department = addslashes($user->department);
2271 $user->address = addslashes($user->address);
2272 $user->city = addslashes($user->city);
2273 $user->url = addslashes($user->url);
2274 $user->description = backup_todb($user->description);
2276 //We need to analyse the AUTH field to recode it:
2277 // - if the field isn't set, we are in a pre 1.4 backup and we'll
2278 // use manual
2280 if (empty($user->auth)) {
2281 if ($CFG->registerauth == 'email') {
2282 $user->auth = 'email';
2283 } else {
2284 $user->auth = 'manual';
2288 //We need to process the POLICYAGREED field to recalculate it:
2289 // - if the destination site is different (by wwwroot) reset it.
2290 // - if the destination site is the same (by wwwroot), leave it unmodified
2292 if ($restore->original_wwwroot != $CFG->wwwroot) {
2293 $user->policyagreed = 0;
2294 } else {
2295 //Nothing to do, we are in the same server
2298 //Check if the theme exists in destination server
2299 $themes = get_list_of_themes();
2300 if (!in_array($user->theme, $themes)) {
2301 $user->theme = '';
2304 //We are going to create the user
2305 //The structure is exactly as we need
2306 $newid = insert_record ("user",$user);
2307 //Put the new id
2308 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,"new");
2311 //Here, if create_roles, do it as necessary
2312 if ($create_roles) {
2313 //Get the newid and current info from backup_ids
2314 $data = backup_getid($restore->backup_unique_code,"user",$userid);
2315 $newid = $data->new_id;
2316 $currinfo = $data->info.",";
2318 //Now, depending of the role, create records in user_studentes and user_teacher
2319 //and/or mark it in backup_ids
2321 if ($is_admin) {
2322 //If the record (user_admins) doesn't exists
2323 //Only put status in backup_ids
2324 $currinfo = $currinfo."admin,";
2325 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2327 if ($is_coursecreator) {
2328 //If the record (user_coursecreators) doesn't exists
2329 //Only put status in backup_ids
2330 $currinfo = $currinfo."coursecreator,";
2331 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2333 if ($is_needed) {
2334 //Only put status in backup_ids
2335 $currinfo = $currinfo."needed,";
2336 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2338 if ($is_teacher) {
2339 //If the record (teacher) doesn't exists
2340 //Put status in backup_ids
2341 $currinfo = $currinfo."teacher,";
2342 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2343 //Set course and user
2344 $user->roles['teacher']->course = $restore->course_id;
2345 $user->roles['teacher']->userid = $newid;
2347 //Need to analyse the enrol field
2348 // - if it isn't set, set it to $CFG->enrol
2349 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2350 // - if we are in the same server (by wwwroot), maintain it unmodified.
2351 if (empty($user->roles['teacher']->enrol)) {
2352 $user->roles['teacher']->enrol = $CFG->enrol;
2353 } else if ($restore->original_wwwroot != $CFG->wwwroot) {
2354 $user->roles['teacher']->enrol = $CFG->enrol;
2355 } else {
2356 //Nothing to do. Leave it unmodified
2359 $rolesmapping = $restore->rolesmapping;
2360 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
2361 if ($user->roles['teacher']->editall) {
2362 role_assign($rolesmapping['defaultteacheredit'],
2363 $newid,
2365 $context->id,
2366 $user->roles['teacher']->timestart,
2367 $user->roles['teacher']->timeend,
2369 $user->roles['teacher']->enrol);
2371 // editting teacher
2372 } else {
2373 // non editting teacher
2374 role_assign($rolesmapping['defaultteacher'],
2375 $newid,
2377 $context->id,
2378 $user->roles['teacher']->timestart,
2379 $user->roles['teacher']->timeend,
2381 $user->roles['teacher']->enrol);
2384 if ($is_student) {
2386 //Put status in backup_ids
2387 $currinfo = $currinfo."student,";
2388 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2389 //Set course and user
2390 $user->roles['student']->course = $restore->course_id;
2391 $user->roles['student']->userid = $newid;
2393 //Need to analyse the enrol field
2394 // - if it isn't set, set it to $CFG->enrol
2395 // - if we are in a different server (by wwwroot), set it to $CFG->enrol
2396 // - if we are in the same server (by wwwroot), maintain it unmodified.
2397 if (empty($user->roles['student']->enrol)) {
2398 $user->roles['student']->enrol = $CFG->enrol;
2399 } else if ($restore->original_wwwroot != $CFG->wwwroot) {
2400 $user->roles['student']->enrol = $CFG->enrol;
2401 } else {
2402 //Nothing to do. Leave it unmodified
2404 $rolesmapping = $restore->rolesmapping;
2405 $context = get_context_instance(CONTEXT_COURSE, $restore->course_id);
2407 role_assign($rolesmapping['defaultstudent'],
2408 $newid,
2410 $context->id,
2411 $user->roles['student']->timestart,
2412 $user->roles['student']->timeend,
2414 $user->roles['student']->enrol);
2417 if (!$is_course_user) {
2418 //If the record (user) doesn't exists
2419 if (!record_exists("user","id",$newid)) {
2420 //Put status in backup_ids
2421 $currinfo = $currinfo."user,";
2422 $status = backup_putid($restore->backup_unique_code,"user",$userid,$newid,$currinfo);
2427 //Here, if create_preferences, do it as necessary
2428 if ($create_preferences) {
2429 //echo "Checking for preferences of user ".$user->username."<br />"; //Debug
2430 //Get user new id from backup_ids
2431 $data = backup_getid($restore->backup_unique_code,"user",$userid);
2432 $newid = $data->new_id;
2433 if (isset($user->user_preferences)) {
2434 //echo "Preferences exist in backup file<br />"; //Debug
2435 foreach($user->user_preferences as $user_preference) {
2436 //echo $user_preference->name." = ".$user_preference->value."<br />"; //Debug
2437 //We check if that user_preference exists in DB
2438 if (!record_exists("user_preferences","userid",$newid,"name",$user_preference->name)) {
2439 //echo "Creating it<br />"; //Debug
2440 //Prepare the record and insert it
2441 $user_preference->userid = $newid;
2442 $status = insert_record("user_preferences",$user_preference);
2450 return $status;
2453 //This function creates all the structures messages and contacts
2454 function restore_create_messages($restore,$xml_file) {
2456 global $CFG;
2458 $status = true;
2459 //Check it exists
2460 if (!file_exists($xml_file)) {
2461 $status = false;
2463 //Get info from xml
2464 if ($status) {
2465 //info will contain the id and name of every table
2466 //(message, message_read and message_contacts)
2467 //in backup_ids->info will be the real info (serialized)
2468 $info = restore_read_xml_messages($restore,$xml_file);
2470 //If we have info, then process messages & contacts
2471 if ($info > 0) {
2472 //Count how many we have
2473 $unreadcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message');
2474 $readcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_read');
2475 $contactcount = count_records ('backup_ids', 'backup_code', $restore->backup_unique_code, 'table_name', 'message_contacts');
2476 if ($unreadcount || $readcount || $contactcount) {
2477 //Start ul
2478 if (!defined('RESTORE_SILENTLY')) {
2479 echo '<ul>';
2481 //Number of records to get in every chunk
2482 $recordset_size = 4;
2484 //Process unread
2485 if ($unreadcount) {
2486 if (!defined('RESTORE_SILENTLY')) {
2487 echo '<li>'.get_string('unreadmessages','message').'</li>';
2489 $counter = 0;
2490 while ($counter < $unreadcount) {
2491 //Fetch recordset_size records in each iteration
2492 $recs = get_records_select("backup_ids","table_name = 'message' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
2493 if ($recs) {
2494 foreach ($recs as $rec) {
2495 //Get the full record from backup_ids
2496 $data = backup_getid($restore->backup_unique_code,"message",$rec->old_id);
2497 if ($data) {
2498 //Now get completed xmlized object
2499 $info = $data->info;
2500 //traverse_xmlize($info); //Debug
2501 //print_object ($GLOBALS['traverse_array']); //Debug
2502 //$GLOBALS['traverse_array']=""; //Debug
2503 //Now build the MESSAGE record structure
2504 $dbrec = new object();
2505 $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2506 $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2507 $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2508 $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2509 $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2510 $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2511 //We have to recode the useridfrom field
2512 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
2513 if ($user) {
2514 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2515 $dbrec->useridfrom = $user->new_id;
2517 //We have to recode the useridto field
2518 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
2519 if ($user) {
2520 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2521 $dbrec->useridto = $user->new_id;
2523 //Check if the record doesn't exist in DB!
2524 $exist = get_record('message','useridfrom',$dbrec->useridfrom,
2525 'useridto', $dbrec->useridto,
2526 'timecreated',$dbrec->timecreated);
2527 if (!$exist) {
2528 //Not exist. Insert
2529 $status = insert_record('message',$dbrec);
2530 } else {
2531 //Duplicate. Do nothing
2534 //Do some output
2535 $counter++;
2536 if ($counter % 10 == 0) {
2537 if (!defined('RESTORE_SILENTLY')) {
2538 echo ".";
2539 if ($counter % 200 == 0) {
2540 echo "<br />";
2543 backup_flush(300);
2550 //Process read
2551 if ($readcount) {
2552 if (!defined('RESTORE_SILENTLY')) {
2553 echo '<li>'.get_string('readmessages','message').'</li>';
2555 $counter = 0;
2556 while ($counter < $readcount) {
2557 //Fetch recordset_size records in each iteration
2558 $recs = get_records_select("backup_ids","table_name = 'message_read' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
2559 if ($recs) {
2560 foreach ($recs as $rec) {
2561 //Get the full record from backup_ids
2562 $data = backup_getid($restore->backup_unique_code,"message_read",$rec->old_id);
2563 if ($data) {
2564 //Now get completed xmlized object
2565 $info = $data->info;
2566 //traverse_xmlize($info); //Debug
2567 //print_object ($GLOBALS['traverse_array']); //Debug
2568 //$GLOBALS['traverse_array']=""; //Debug
2569 //Now build the MESSAGE_READ record structure
2570 $dbrec->useridfrom = backup_todb($info['MESSAGE']['#']['USERIDFROM']['0']['#']);
2571 $dbrec->useridto = backup_todb($info['MESSAGE']['#']['USERIDTO']['0']['#']);
2572 $dbrec->message = backup_todb($info['MESSAGE']['#']['MESSAGE']['0']['#']);
2573 $dbrec->format = backup_todb($info['MESSAGE']['#']['FORMAT']['0']['#']);
2574 $dbrec->timecreated = backup_todb($info['MESSAGE']['#']['TIMECREATED']['0']['#']);
2575 $dbrec->messagetype = backup_todb($info['MESSAGE']['#']['MESSAGETYPE']['0']['#']);
2576 $dbrec->timeread = backup_todb($info['MESSAGE']['#']['TIMEREAD']['0']['#']);
2577 $dbrec->mailed = backup_todb($info['MESSAGE']['#']['MAILED']['0']['#']);
2578 //We have to recode the useridfrom field
2579 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridfrom);
2580 if ($user) {
2581 //echo "User ".$dbrec->useridfrom." to user ".$user->new_id."<br />"; //Debug
2582 $dbrec->useridfrom = $user->new_id;
2584 //We have to recode the useridto field
2585 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->useridto);
2586 if ($user) {
2587 //echo "User ".$dbrec->useridto." to user ".$user->new_id."<br />"; //Debug
2588 $dbrec->useridto = $user->new_id;
2590 //Check if the record doesn't exist in DB!
2591 $exist = get_record('message_read','useridfrom',$dbrec->useridfrom,
2592 'useridto', $dbrec->useridto,
2593 'timecreated',$dbrec->timecreated);
2594 if (!$exist) {
2595 //Not exist. Insert
2596 $status = insert_record('message_read',$dbrec);
2597 } else {
2598 //Duplicate. Do nothing
2601 //Do some output
2602 $counter++;
2603 if ($counter % 10 == 0) {
2604 if (!defined('RESTORE_SILENTLY')) {
2605 echo ".";
2606 if ($counter % 200 == 0) {
2607 echo "<br />";
2610 backup_flush(300);
2617 //Process contacts
2618 if ($contactcount) {
2619 if (!defined('RESTORE_SILENTLY')) {
2620 echo '<li>'.moodle_strtolower(get_string('contacts','message')).'</li>';
2622 $counter = 0;
2623 while ($counter < $contactcount) {
2624 //Fetch recordset_size records in each iteration
2625 $recs = get_records_select("backup_ids","table_name = 'message_contacts' AND backup_code = '$restore->backup_unique_code'","old_id","old_id, old_id",$counter,$recordset_size);
2626 if ($recs) {
2627 foreach ($recs as $rec) {
2628 //Get the full record from backup_ids
2629 $data = backup_getid($restore->backup_unique_code,"message_contacts",$rec->old_id);
2630 if ($data) {
2631 //Now get completed xmlized object
2632 $info = $data->info;
2633 //traverse_xmlize($info); //Debug
2634 //print_object ($GLOBALS['traverse_array']); //Debug
2635 //$GLOBALS['traverse_array']=""; //Debug
2636 //Now build the MESSAGE_CONTACTS record structure
2637 $dbrec->userid = backup_todb($info['CONTACT']['#']['USERID']['0']['#']);
2638 $dbrec->contactid = backup_todb($info['CONTACT']['#']['CONTACTID']['0']['#']);
2639 $dbrec->blocked = backup_todb($info['CONTACT']['#']['BLOCKED']['0']['#']);
2640 //We have to recode the userid field
2641 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->userid);
2642 if ($user) {
2643 //echo "User ".$dbrec->userid." to user ".$user->new_id."<br />"; //Debug
2644 $dbrec->userid = $user->new_id;
2646 //We have to recode the contactid field
2647 $user = backup_getid($restore->backup_unique_code,"user",$dbrec->contactid);
2648 if ($user) {
2649 //echo "User ".$dbrec->contactid." to user ".$user->new_id."<br />"; //Debug
2650 $dbrec->contactid = $user->new_id;
2652 //Check if the record doesn't exist in DB!
2653 $exist = get_record('message_contacts','userid',$dbrec->userid,
2654 'contactid', $dbrec->contactid);
2655 if (!$exist) {
2656 //Not exist. Insert
2657 $status = insert_record('message_contacts',$dbrec);
2658 } else {
2659 //Duplicate. Do nothing
2662 //Do some output
2663 $counter++;
2664 if ($counter % 10 == 0) {
2665 if (!defined('RESTORE_SILENTLY')) {
2666 echo ".";
2667 if ($counter % 200 == 0) {
2668 echo "<br />";
2671 backup_flush(300);
2677 if (!defined('RESTORE_SILENTLY')) {
2678 //End ul
2679 echo '</ul>';
2685 return $status;
2688 //This function creates all the categories and questions
2689 //from xml
2690 function restore_create_questions($restore,$xml_file) {
2692 global $CFG, $db;
2694 $status = true;
2695 //Check it exists
2696 if (!file_exists($xml_file)) {
2697 $status = false;
2699 //Get info from xml
2700 if ($status) {
2701 //info will contain the old_id of every category
2702 //in backup_ids->info will be the real info (serialized)
2703 $info = restore_read_xml_questions($restore,$xml_file);
2705 //Now, if we have anything in info, we have to restore that
2706 //categories/questions
2707 if ($info) {
2708 if ($info !== true) {
2709 $status = $status && restore_question_categories($info, $restore);
2711 } else {
2712 $status = false;
2714 return $status;
2717 //This function creates all the scales
2718 function restore_create_scales($restore,$xml_file) {
2720 global $CFG, $db;
2722 $status = true;
2723 //Check it exists
2724 if (!file_exists($xml_file)) {
2725 $status = false;
2727 //Get info from xml
2728 if ($status) {
2729 //scales will contain the old_id of every scale
2730 //in backup_ids->info will be the real info (serialized)
2731 $scales = restore_read_xml_scales($restore,$xml_file);
2733 //Now, if we have anything in scales, we have to restore that
2734 //scales
2735 if ($scales) {
2736 //Get admin->id for later use
2737 $admin = get_admin();
2738 $adminid = $admin->id;
2739 if ($scales !== true) {
2740 //Iterate over each scale
2741 foreach ($scales as $scale) {
2742 //Get record from backup_ids
2743 $data = backup_getid($restore->backup_unique_code,"scale",$scale->id);
2744 //Init variables
2745 $create_scale = false;
2747 if ($data) {
2748 //Now get completed xmlized object
2749 $info = $data->info;
2750 //traverse_xmlize($info); //Debug
2751 //print_object ($GLOBALS['traverse_array']); //Debug
2752 //$GLOBALS['traverse_array']=""; //Debug
2754 //Now build the SCALE record structure
2755 $sca = new object();
2756 $sca->courseid = backup_todb($info['SCALE']['#']['COURSEID']['0']['#']);
2757 $sca->userid = backup_todb($info['SCALE']['#']['USERID']['0']['#']);
2758 $sca->name = backup_todb($info['SCALE']['#']['NAME']['0']['#']);
2759 $sca->scale = backup_todb($info['SCALE']['#']['SCALETEXT']['0']['#']);
2760 $sca->description = backup_todb($info['SCALE']['#']['DESCRIPTION']['0']['#']);
2761 $sca->timemodified = backup_todb($info['SCALE']['#']['TIMEMODIFIED']['0']['#']);
2763 //Now search if that scale exists (by scale field) in course 0 (Standar scale)
2764 //or in restore->course_id course (Personal scale)
2765 if ($sca->courseid == 0) {
2766 $course_to_search = 0;
2767 } else {
2768 $course_to_search = $restore->course_id;
2771 // scale is not course unique, use get_record_sql to suppress warning
2773 $sca_db = get_record_sql("SELECT * FROM {$CFG->prefix}scale
2774 WHERE scale = '$sca->scale'
2775 AND courseid = $course_to_search", true);
2777 //If it doesn't exist, create
2778 if (!$sca_db) {
2779 $create_scale = true;
2781 //If we must create the scale
2782 if ($create_scale) {
2783 //Me must recode the courseid if it's <> 0 (common scale)
2784 if ($sca->courseid != 0) {
2785 $sca->courseid = $restore->course_id;
2787 //We must recode the userid
2788 $user = backup_getid($restore->backup_unique_code,"user",$sca->userid);
2789 if ($user) {
2790 $sca->userid = $user->new_id;
2791 } else {
2792 //Assign it to admin
2793 $sca->userid = $adminid;
2795 //The structure is equal to the db, so insert the scale
2796 $newid = insert_record ("scale",$sca);
2797 } else {
2798 //get current scale id
2799 $newid = $sca_db->id;
2801 if ($newid) {
2802 //We have the newid, update backup_ids
2803 backup_putid($restore->backup_unique_code,"scale",
2804 $scale->id, $newid);
2809 } else {
2810 $status = false;
2812 return $status;
2815 //This function creates all the groups
2816 function restore_create_groups($restore,$xml_file) {
2818 //Check it exists
2819 if (!file_exists($xml_file)) {
2820 return false;
2822 //Get info from xml
2823 if (!$groups = restore_read_xml_groups($restore,$xml_file)) {
2824 //groups will contain the old_id of every group
2825 //in backup_ids->info will be the real info (serialized)
2826 return false;
2828 } else if ($groups === true) {
2829 return true;
2832 $status = true;
2834 //Iterate over each group
2835 foreach ($groups as $group) {
2836 //Get record from backup_ids
2837 $data = backup_getid($restore->backup_unique_code,"groups",$group->id);
2839 if ($data) {
2840 //Now get completed xmlized object
2841 $info = $data->info;
2842 //traverse_xmlize($info); //Debug
2843 //print_object ($GLOBALS['traverse_array']); //Debug
2844 //$GLOBALS['traverse_array']=""; //Debug
2845 //Now build the GROUP record structure
2846 $gro = new Object();
2847 $gro->courseid = $restore->course_id;
2848 $gro->name = backup_todb($info['GROUP']['#']['NAME']['0']['#']);
2849 $gro->description = backup_todb($info['GROUP']['#']['DESCRIPTION']['0']['#']);
2850 if (isset($info['GROUP']['#']['ENROLMENTKEY']['0']['#'])) {
2851 $gro->enrolmentkey = backup_todb($info['GROUP']['#']['ENROLMENTKEY']['0']['#']);
2852 } else {
2853 $gro->enrolmentkey = backup_todb($info['GROUP']['#']['PASSWORD']['0']['#']);
2855 $gro->picture = backup_todb($info['GROUP']['#']['PICTURE']['0']['#']);
2856 $gro->hidepicture = backup_todb($info['GROUP']['#']['HIDEPICTURE']['0']['#']);
2857 $gro->timecreated = backup_todb($info['GROUP']['#']['TIMECREATED']['0']['#']);
2858 $gro->timemodified = backup_todb($info['GROUP']['#']['TIMEMODIFIED']['0']['#']);
2860 //Now search if that group exists (by name and description field) in
2861 if (!$gro_db = get_record('groups', 'courseid', $restore->course_id, 'name', $gro->name, 'description', $gro->description)) {
2862 //If it doesn't exist, create
2863 $newid = insert_record('groups', $gro);
2865 } else {
2866 //get current group id
2867 $newid = $gro_db->id;
2870 if ($newid) {
2871 //We have the newid, update backup_ids
2872 backup_putid($restore->backup_unique_code,"groups", $group->id, $newid);
2873 } else {
2875 $status = false;
2876 continue;
2879 //Now restore members in the groups_members, only if
2880 //users are included
2881 if ($restore->users != 2) {
2882 if (!restore_create_groups_members($newid,$info,$restore)) {
2883 $status = false;
2889 //Now, restore group_files
2890 if ($status) {
2891 $status = restore_group_files($restore);
2894 return $status;
2897 //This function restores the groups_members
2898 function restore_create_groups_members($group_id,$info,$restore) {
2900 if (! isset($info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'])) {
2901 //OK, some groups have no members.
2902 return true;
2904 //Get the members array
2905 $members = $info['GROUP']['#']['MEMBERS']['0']['#']['MEMBER'];
2907 $status = true;
2909 //Iterate over members
2910 for($i = 0; $i < sizeof($members); $i++) {
2911 $mem_info = $members[$i];
2912 //traverse_xmlize($mem_info); //Debug
2913 //print_object ($GLOBALS['traverse_array']); //Debug
2914 //$GLOBALS['traverse_array']=""; //Debug
2916 //Now, build the GROUPS_MEMBERS record structure
2917 $group_member = new Object();
2918 $group_member->groupid = $group_id;
2919 $group_member->userid = backup_todb($mem_info['#']['USERID']['0']['#']);
2920 $group_member->timeadded = backup_todb($mem_info['#']['TIMEADDED']['0']['#']);
2922 $newid = false;
2924 //We have to recode the userid field
2925 if (!$user = backup_getid($restore->backup_unique_code,"user",$group_member->userid)) {
2926 $status = false;
2927 continue;
2930 $group_member->userid = $user->new_id;
2932 //The structure is equal to the db, so insert the groups_members
2933 if (!insert_record ("groups_members", $group_member)) {
2934 $status = false;
2935 continue;
2938 //Do some output
2939 if (($i+1) % 50 == 0) {
2940 if (!defined('RESTORE_SILENTLY')) {
2941 echo ".";
2942 if (($i+1) % 1000 == 0) {
2943 echo "<br />";
2946 backup_flush(300);
2950 return $status;
2953 //This function creates all the groupings
2954 function restore_create_groupings($restore,$xml_file) {
2956 //Check it exists
2957 if (!file_exists($xml_file)) {
2958 return false;
2960 //Get info from xml
2961 if (!$groupings = restore_read_xml_groupings($restore,$xml_file)) {
2962 return false;
2964 } else if ($groupings === true) {
2965 return true;
2968 $status = true;
2970 //Iterate over each group
2971 foreach ($groupings as $grouping) {
2972 if ($data = backup_getid($restore->backup_unique_code,"groupings",$grouping->id)) {
2973 //Now get completed xmlized object
2974 $info = $data->info;
2975 //Now build the GROUPING record structure
2976 $gro = new Object();
2977 ///$gro->id = backup_todb($info['GROUPING']['#']['ID']['0']['#']);
2978 $gro->courseid = $restore->course_id;
2979 $gro->name = backup_todb($info['GROUPING']['#']['NAME']['0']['#']);
2980 $gro->description = backup_todb($info['GROUPING']['#']['DESCRIPTION']['0']['#']);
2981 $gro->configdata = backup_todb($info['GROUPING']['#']['CONFIGDATA']['0']['#']);
2982 $gro->timecreated = backup_todb($info['GROUPING']['#']['TIMECREATED']['0']['#']);
2984 //Now search if that group exists (by name and description field) in
2985 if ($gro_db = get_record('groupings', 'courseid', $restore->course_id, 'name', $gro->name, 'description', $gro->description)) {
2986 //get current group id
2987 $newid = $gro_db->id;
2989 } else {
2990 //The structure is equal to the db, so insert the grouping
2991 if (!$newid = insert_record('groupings', $gro)) {
2992 $status = false;
2993 continue;
2997 //We have the newid, update backup_ids
2998 backup_putid($restore->backup_unique_code,"groupings",
2999 $grouping->id, $newid);
3004 // now fix the defaultgroupingid in course
3005 $course = get_record('course', 'id', $restore->course_id);
3006 if ($course->defaultgroupingid) {
3007 if ($grouping = backup_getid($restore->backup_unique_code,"groupings",$course->defaultgroupingid)) {
3008 set_field('course', 'defaultgroupingid', $grouping->new_id, 'id', $course->id);
3009 } else {
3010 set_field('course', 'defaultgroupingid', 0, 'id', $course->id);
3014 return $status;
3017 //This function creates all the groupingsgroups
3018 function restore_create_groupings_groups($restore,$xml_file) {
3020 //Check it exists
3021 if (!file_exists($xml_file)) {
3022 return false;
3024 //Get info from xml
3025 if (!$groupingsgroups = restore_read_xml_groupings_groups($restore,$xml_file)) {
3026 return false;
3028 } else if ($groupingsgroups === true) {
3029 return true;
3032 $status = true;
3034 //Iterate over each group
3035 foreach ($groupingsgroups as $groupinggroup) {
3036 if ($data = backup_getid($restore->backup_unique_code,"groupingsgroups",$groupinggroup->id)) {
3037 //Now get completed xmlized object
3038 $info = $data->info;
3039 //Now build the GROUPING record structure
3040 $gro_member = new Object();
3041 $gro_member->groupingid = backup_todb($info['GROUPINGGROUP']['#']['GROUPINGID']['0']['#']);
3042 $gro_member->groupid = backup_todb($info['GROUPINGGROUP']['#']['GROUPID']['0']['#']);
3043 $gro_member->timeadded = backup_todb($info['GROUPINGGROUP']['#']['TIMEADDED']['0']['#']);
3045 if (!$grouping = backup_getid($restore->backup_unique_code,"groupings",$gro_member->groupingid)) {
3046 $status = false;
3047 continue;
3050 if (!$group = backup_getid($restore->backup_unique_code,"groups",$gro_member->groupid)) {
3051 $status = false;
3052 continue;
3055 $gro_member->groupid = $group->new_id;
3056 $gro_member->groupingid = $grouping->new_id;
3057 if (!get_record('groupings_groups', 'groupid', $gro_member->groupid, 'groupingid', $gro_member->groupingid)) {
3058 if (!insert_record('groupings_groups', $gro_member)) {
3059 $status = false;
3065 return $status;
3068 //This function creates all the course events
3069 function restore_create_events($restore,$xml_file) {
3071 global $CFG, $db;
3073 $status = true;
3074 //Check it exists
3075 if (!file_exists($xml_file)) {
3076 $status = false;
3078 //Get info from xml
3079 if ($status) {
3080 //events will contain the old_id of every event
3081 //in backup_ids->info will be the real info (serialized)
3082 $events = restore_read_xml_events($restore,$xml_file);
3085 //Get admin->id for later use
3086 $admin = get_admin();
3087 $adminid = $admin->id;
3089 //Now, if we have anything in events, we have to restore that
3090 //events
3091 if ($events) {
3092 if ($events !== true) {
3093 //Iterate over each event
3094 foreach ($events as $event) {
3095 //Get record from backup_ids
3096 $data = backup_getid($restore->backup_unique_code,"event",$event->id);
3097 //Init variables
3098 $create_event = false;
3100 if ($data) {
3101 //Now get completed xmlized object
3102 $info = $data->info;
3103 //traverse_xmlize($info); //Debug
3104 //print_object ($GLOBALS['traverse_array']); //Debug
3105 //$GLOBALS['traverse_array']=""; //Debug
3107 //if necessary, write to restorelog and adjust date/time fields
3108 if ($restore->course_startdateoffset) {
3109 restore_log_date_changes('Events', $restore, $info['EVENT']['#'], array('TIMESTART'));
3112 //Now build the EVENT record structure
3113 $eve->name = backup_todb($info['EVENT']['#']['NAME']['0']['#']);
3114 $eve->description = backup_todb($info['EVENT']['#']['DESCRIPTION']['0']['#']);
3115 $eve->format = backup_todb($info['EVENT']['#']['FORMAT']['0']['#']);
3116 $eve->courseid = $restore->course_id;
3117 $eve->groupid = backup_todb($info['EVENT']['#']['GROUPID']['0']['#']);
3118 $eve->userid = backup_todb($info['EVENT']['#']['USERID']['0']['#']);
3119 $eve->repeatid = backup_todb($info['EVENT']['#']['REPEATID']['0']['#']);
3120 $eve->modulename = "";
3121 if (!empty($info['EVENT']['#']['MODULENAME'])) {
3122 $eve->modulename = backup_todb($info['EVENT']['#']['MODULENAME']['0']['#']);
3124 $eve->instance = 0;
3125 $eve->eventtype = backup_todb($info['EVENT']['#']['EVENTTYPE']['0']['#']);
3126 $eve->timestart = backup_todb($info['EVENT']['#']['TIMESTART']['0']['#']);
3127 $eve->timeduration = backup_todb($info['EVENT']['#']['TIMEDURATION']['0']['#']);
3128 $eve->visible = backup_todb($info['EVENT']['#']['VISIBLE']['0']['#']);
3129 $eve->timemodified = backup_todb($info['EVENT']['#']['TIMEMODIFIED']['0']['#']);
3131 //Now search if that event exists (by name, description, timestart fields) in
3132 //restore->course_id course
3133 $eve_db = get_record_select("event",
3134 "courseid={$eve->courseid} AND name='{$eve->name}' AND description='{$eve->description}' AND timestart=$eve->timestart");
3135 //If it doesn't exist, create
3136 if (!$eve_db) {
3137 $create_event = true;
3139 //If we must create the event
3140 if ($create_event) {
3142 //We must recode the userid
3143 $user = backup_getid($restore->backup_unique_code,"user",$eve->userid);
3144 if ($user) {
3145 $eve->userid = $user->new_id;
3146 } else {
3147 //Assign it to admin
3148 $eve->userid = $adminid;
3151 //We must recode the repeatid if the event has it
3152 if (!empty($eve->repeatid)) {
3153 $repeat_rec = backup_getid($restore->backup_unique_code,"event_repeatid",$eve->repeatid);
3154 if ($repeat_rec) { //Exists, so use it...
3155 $eve->repeatid = $repeat_rec->new_id;
3156 } else { //Doesn't exists, calculate the next and save it
3157 $oldrepeatid = $eve->repeatid;
3158 $max_rec = get_record_sql('SELECT 1, MAX(repeatid) AS repeatid FROM '.$CFG->prefix.'event');
3159 $eve->repeatid = empty($max_rec) ? 1 : $max_rec->repeatid + 1;
3160 backup_putid($restore->backup_unique_code,"event_repeatid", $oldrepeatid, $eve->repeatid);
3164 //We have to recode the groupid field
3165 $group = backup_getid($restore->backup_unique_code,"groups",$eve->groupid);
3166 if ($group) {
3167 $eve->groupid = $group->new_id;
3168 } else {
3169 //Assign it to group 0
3170 $eve->groupid = 0;
3173 //The structure is equal to the db, so insert the event
3174 $newid = insert_record ("event",$eve);
3175 } else {
3176 //get current event id
3177 $newid = $eve_db->id;
3179 if ($newid) {
3180 //We have the newid, update backup_ids
3181 backup_putid($restore->backup_unique_code,"event",
3182 $event->id, $newid);
3187 } else {
3188 $status = false;
3190 return $status;
3193 //This function decode things to make restore multi-site fully functional
3194 //It does this conversions:
3195 // - $@FILEPHP@$ ---|------------> $CFG->wwwroot/file.php/courseid (slasharguments on)
3196 // |------------> $CFG->wwwroot/file.php?file=/courseid (slasharguments off)
3198 //Note: Inter-activities linking is being implemented as a final
3199 //step in the restore execution, because we need to have it
3200 //finished to know all the oldid, newid equivaleces
3201 function restore_decode_absolute_links($content) {
3203 global $CFG,$restore;
3205 // MDL-10770
3206 // This function was replacing null with empty string
3207 // Nullity check is added in backup_todb(), this function will no longer not be called from backup_todb() if content is null
3208 // I noticed some parts of the restore code is calling this directly instead of calling backup_todb(), so just in case
3209 // 3rd party mod etc are doing the same
3210 if ($content === NULL) {
3211 return NULL;
3214 //Now decode wwwroot and file.php calls
3215 $search = array ("$@FILEPHP@$");
3217 //Check for the status of the slasharguments config variable
3218 $slash = $CFG->slasharguments;
3220 //Build the replace string as needed
3221 if ($slash == 1) {
3222 $replace = array ($CFG->wwwroot."/file.php/".$restore->course_id);
3223 } else {
3224 $replace = array ($CFG->wwwroot."/file.php?file=/".$restore->course_id);
3227 $result = str_replace($search,$replace,$content);
3229 if ($result != $content && debugging()) { //Debug
3230 if (!defined('RESTORE_SILENTLY')) {
3231 echo '<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />'; //Debug
3233 } //Debug
3235 return $result;
3238 //This function restores the userfiles from the temp (user_files) directory to the
3239 //dataroot/users directory
3240 function restore_user_files($restore) {
3242 global $CFG;
3244 $status = true;
3246 $counter = 0;
3248 //First, we check to "users" exists and create is as necessary
3249 //in CFG->dataroot
3250 $dest_dir = $CFG->dataroot."/users";
3251 $status = check_dir_exists($dest_dir,true);
3253 //Now, we iterate over "user_files" records to check if that user dir must be
3254 //copied (and renamed) to the "users" dir.
3255 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/user_files";
3256 //Check if directory exists
3257 if (is_dir($rootdir)) {
3258 $list = list_directories ($rootdir);
3259 if ($list) {
3260 //Iterate
3261 $counter = 0;
3262 foreach ($list as $dir) {
3263 //Look for dir like username in backup_ids
3264 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
3265 "table_name","user",
3266 "old_id",$dir);
3267 //If thar user exists in backup_ids
3268 if ($data) {
3269 //Only it user has been created now
3270 //or if it existed previously, but he hasn't image (see bug 1123)
3271 if ((strpos($data->info,"new") !== false) or
3272 (!check_dir_exists($dest_dir."/".$data->new_id,false))) {
3273 //Copy the old_dir to its new location (and name) !!
3274 //Only if destination doesn't exists
3275 if (!file_exists($dest_dir."/".$data->new_id)) {
3276 $status = backup_copy_file($rootdir."/".$dir,
3277 $dest_dir."/".$data->new_id,true);
3278 $counter ++;
3280 //Do some output
3281 if ($counter % 2 == 0) {
3282 if (!defined('RESTORE_SILENTLY')) {
3283 echo ".";
3284 if ($counter % 40 == 0) {
3285 echo "<br />";
3288 backup_flush(300);
3295 //If status is ok and whe have dirs created, returns counter to inform
3296 if ($status and $counter) {
3297 return $counter;
3298 } else {
3299 return $status;
3303 //This function restores the groupfiles from the temp (group_files) directory to the
3304 //dataroot/groups directory
3305 function restore_group_files($restore) {
3307 global $CFG;
3309 $status = true;
3311 $counter = 0;
3313 //First, we check to "groups" exists and create is as necessary
3314 //in CFG->dataroot
3315 $dest_dir = $CFG->dataroot.'/groups';
3316 $status = check_dir_exists($dest_dir,true);
3318 //Now, we iterate over "group_files" records to check if that user dir must be
3319 //copied (and renamed) to the "groups" dir.
3320 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/group_files";
3321 //Check if directory exists
3322 if (is_dir($rootdir)) {
3323 $list = list_directories ($rootdir);
3324 if ($list) {
3325 //Iterate
3326 $counter = 0;
3327 foreach ($list as $dir) {
3328 //Look for dir like groupid in backup_ids
3329 $data = get_record ("backup_ids","backup_code",$restore->backup_unique_code,
3330 "table_name","groups",
3331 "old_id",$dir);
3332 //If that group exists in backup_ids
3333 if ($data) {
3334 if (!file_exists($dest_dir."/".$data->new_id)) {
3335 $status = backup_copy_file($rootdir."/".$dir, $dest_dir."/".$data->new_id,true);
3336 $counter ++;
3338 //Do some output
3339 if ($counter % 2 == 0) {
3340 if (!defined('RESTORE_SILENTLY')) {
3341 echo ".";
3342 if ($counter % 40 == 0) {
3343 echo "<br />";
3346 backup_flush(300);
3352 //If status is ok and whe have dirs created, returns counter to inform
3353 if ($status and $counter) {
3354 return $counter;
3355 } else {
3356 return $status;
3360 //This function restores the course files from the temp (course_files) directory to the
3361 //dataroot/course_id directory
3362 function restore_course_files($restore) {
3364 global $CFG;
3366 $status = true;
3368 $counter = 0;
3370 //First, we check to "course_id" exists and create is as necessary
3371 //in CFG->dataroot
3372 $dest_dir = $CFG->dataroot."/".$restore->course_id;
3373 $status = check_dir_exists($dest_dir,true);
3375 //Now, we iterate over "course_files" records to check if that file/dir must be
3376 //copied to the "dest_dir" dir.
3377 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/course_files";
3378 //Check if directory exists
3379 if (is_dir($rootdir)) {
3380 $list = list_directories_and_files ($rootdir);
3381 if ($list) {
3382 //Iterate
3383 $counter = 0;
3384 foreach ($list as $dir) {
3385 //Copy the dir to its new location
3386 //Only if destination file/dir doesn exists
3387 if (!file_exists($dest_dir."/".$dir)) {
3388 $status = backup_copy_file($rootdir."/".$dir,
3389 $dest_dir."/".$dir,true);
3390 $counter ++;
3392 //Do some output
3393 if ($counter % 2 == 0) {
3394 if (!defined('RESTORE_SILENTLY')) {
3395 echo ".";
3396 if ($counter % 40 == 0) {
3397 echo "<br />";
3400 backup_flush(300);
3405 //If status is ok and whe have dirs created, returns counter to inform
3406 if ($status and $counter) {
3407 return $counter;
3408 } else {
3409 return $status;
3413 //This function restores the site files from the temp (site_files) directory to the
3414 //dataroot/SITEID directory
3415 function restore_site_files($restore) {
3417 global $CFG;
3419 $status = true;
3421 $counter = 0;
3423 //First, we check to "course_id" exists and create is as necessary
3424 //in CFG->dataroot
3425 $dest_dir = $CFG->dataroot."/".SITEID;
3426 $status = check_dir_exists($dest_dir,true);
3428 //Now, we iterate over "site_files" files to check if that file/dir must be
3429 //copied to the "dest_dir" dir.
3430 $rootdir = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/site_files";
3431 //Check if directory exists
3432 if (is_dir($rootdir)) {
3433 $list = list_directories_and_files ($rootdir);
3434 if ($list) {
3435 //Iterate
3436 $counter = 0;
3437 foreach ($list as $dir) {
3438 //Copy the dir to its new location
3439 //Only if destination file/dir doesn exists
3440 if (!file_exists($dest_dir."/".$dir)) {
3441 $status = backup_copy_file($rootdir."/".$dir,
3442 $dest_dir."/".$dir,true);
3443 $counter ++;
3445 //Do some output
3446 if ($counter % 2 == 0) {
3447 if (!defined('RESTORE_SILENTLY')) {
3448 echo ".";
3449 if ($counter % 40 == 0) {
3450 echo "<br />";
3453 backup_flush(300);
3458 //If status is ok and whe have dirs created, returns counter to inform
3459 if ($status and $counter) {
3460 return $counter;
3461 } else {
3462 return $status;
3467 //This function creates all the structures for every module in backup file
3468 //Depending what has been selected.
3469 function restore_create_modules($restore,$xml_file) {
3471 global $CFG;
3472 $status = true;
3473 //Check it exists
3474 if (!file_exists($xml_file)) {
3475 $status = false;
3477 //Get info from xml
3478 if ($status) {
3479 //info will contain the id and modtype of every module
3480 //in backup_ids->info will be the real info (serialized)
3481 $info = restore_read_xml_modules($restore,$xml_file);
3483 //Now, if we have anything in info, we have to restore that mods
3484 //from backup_ids (calling every mod restore function)
3485 if ($info) {
3486 if ($info !== true) {
3487 if (!defined('RESTORE_SILENTLY')) {
3488 echo '<ul>';
3490 //Iterate over each module
3491 foreach ($info as $mod) {
3492 if (empty($restore->mods[$mod->modtype]->granular) // We don't care about per instance, i.e. restore all instances.
3493 || (array_key_exists($mod->id,$restore->mods[$mod->modtype]->instances)
3494 && !empty($restore->mods[$mod->modtype]->instances[$mod->id]->restore))) {
3495 $modrestore = $mod->modtype."_restore_mods";
3496 if (function_exists($modrestore)) { //Debug
3497 // we want to restore all mods even when one fails
3498 // incorrect code here ignored any errors during module restore in 1.6-1.8
3499 $status = $status && $modrestore($mod,$restore);
3500 } else {
3501 //Something was wrong. Function should exist.
3502 $status = false;
3506 if (!defined('RESTORE_SILENTLY')) {
3507 echo '</ul>';
3510 } else {
3511 $status = false;
3513 return $status;
3516 //This function creates all the structures for every log in backup file
3517 //Depending what has been selected.
3518 function restore_create_logs($restore,$xml_file) {
3520 global $CFG,$db;
3522 //Number of records to get in every chunk
3523 $recordset_size = 4;
3524 //Counter, points to current record
3525 $counter = 0;
3526 //To count all the recods to restore
3527 $count_logs = 0;
3529 $status = true;
3530 //Check it exists
3531 if (!file_exists($xml_file)) {
3532 $status = false;
3534 //Get info from xml
3535 if ($status) {
3536 //count_logs will contain the number of logs entries to process
3537 //in backup_ids->info will be the real info (serialized)
3538 $count_logs = restore_read_xml_logs($restore,$xml_file);
3541 //Now, if we have records in count_logs, we have to restore that logs
3542 //from backup_ids. This piece of code makes calls to:
3543 // - restore_log_course() if it's a course log
3544 // - restore_log_user() if it's a user log
3545 // - restore_log_module() if it's a module log.
3546 //And all is segmented in chunks to allow large recordsets to be restored !!
3547 if ($count_logs > 0) {
3548 while ($counter < $count_logs) {
3549 //Get a chunk of records
3550 //Take old_id twice to avoid adodb limitation
3551 $logs = get_records_select("backup_ids","table_name = 'log' AND backup_code = '$restore->backup_unique_code'","old_id","old_id,old_id",$counter,$recordset_size);
3552 //We have logs
3553 if ($logs) {
3554 //Iterate
3555 foreach ($logs as $log) {
3556 //Get the full record from backup_ids
3557 $data = backup_getid($restore->backup_unique_code,"log",$log->old_id);
3558 if ($data) {
3559 //Now get completed xmlized object
3560 $info = $data->info;
3561 //traverse_xmlize($info); //Debug
3562 //print_object ($GLOBALS['traverse_array']); //Debug
3563 //$GLOBALS['traverse_array']=""; //Debug
3564 //Now build the LOG record structure
3565 $dblog = new object();
3566 $dblog->time = backup_todb($info['LOG']['#']['TIME']['0']['#']);
3567 $dblog->userid = backup_todb($info['LOG']['#']['USERID']['0']['#']);
3568 $dblog->ip = backup_todb($info['LOG']['#']['IP']['0']['#']);
3569 $dblog->course = $restore->course_id;
3570 $dblog->module = backup_todb($info['LOG']['#']['MODULE']['0']['#']);
3571 $dblog->cmid = backup_todb($info['LOG']['#']['CMID']['0']['#']);
3572 $dblog->action = backup_todb($info['LOG']['#']['ACTION']['0']['#']);
3573 $dblog->url = backup_todb($info['LOG']['#']['URL']['0']['#']);
3574 $dblog->info = backup_todb($info['LOG']['#']['INFO']['0']['#']);
3575 //We have to recode the userid field
3576 $user = backup_getid($restore->backup_unique_code,"user",$dblog->userid);
3577 if ($user) {
3578 //echo "User ".$dblog->userid." to user ".$user->new_id."<br />"; //Debug
3579 $dblog->userid = $user->new_id;
3581 //We have to recode the cmid field (if module isn't "course" or "user")
3582 if ($dblog->module != "course" and $dblog->module != "user") {
3583 $cm = backup_getid($restore->backup_unique_code,"course_modules",$dblog->cmid);
3584 if ($cm) {
3585 //echo "Module ".$dblog->cmid." to module ".$cm->new_id."<br />"; //Debug
3586 $dblog->cmid = $cm->new_id;
3587 } else {
3588 $dblog->cmid = 0;
3591 //print_object ($dblog); //Debug
3592 //Now, we redirect to the needed function to make all the work
3593 if ($dblog->module == "course") {
3594 //It's a course log,
3595 $stat = restore_log_course($restore,$dblog);
3596 } elseif ($dblog->module == "user") {
3597 //It's a user log,
3598 $stat = restore_log_user($restore,$dblog);
3599 } else {
3600 //It's a module log,
3601 $stat = restore_log_module($restore,$dblog);
3605 //Do some output
3606 $counter++;
3607 if ($counter % 10 == 0) {
3608 if (!defined('RESTORE_SILENTLY')) {
3609 echo ".";
3610 if ($counter % 200 == 0) {
3611 echo "<br />";
3614 backup_flush(300);
3617 } else {
3618 //We never should arrive here
3619 $counter = $count_logs;
3620 $status = false;
3625 return $status;
3628 //This function inserts a course log record, calculating the URL field as necessary
3629 function restore_log_course($restore,$log) {
3631 $status = true;
3632 $toinsert = false;
3634 //echo "<hr />Before transformations<br />"; //Debug
3635 //print_object($log); //Debug
3636 //Depending of the action, we recode different things
3637 switch ($log->action) {
3638 case "view":
3639 $log->url = "view.php?id=".$log->course;
3640 $log->info = $log->course;
3641 $toinsert = true;
3642 break;
3643 case "guest":
3644 $log->url = "view.php?id=".$log->course;
3645 $toinsert = true;
3646 break;
3647 case "user report":
3648 //recode the info field (it's the user id)
3649 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3650 if ($user) {
3651 $log->info = $user->new_id;
3652 //Now, extract the mode from the url field
3653 $mode = substr(strrchr($log->url,"="),1);
3654 $log->url = "user.php?id=".$log->course."&user=".$log->info."&mode=".$mode;
3655 $toinsert = true;
3657 break;
3658 case "add mod":
3659 //Extract the course_module from the url field
3660 $cmid = substr(strrchr($log->url,"="),1);
3661 //recode the course_module to see it it has been restored
3662 $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
3663 if ($cm) {
3664 $cmid = $cm->new_id;
3665 //Extract the module name and the module id from the info field
3666 $modname = strtok($log->info," ");
3667 $modid = strtok(" ");
3668 //recode the module id to see if it has been restored
3669 $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
3670 if ($mod) {
3671 $modid = $mod->new_id;
3672 //Now I have everything so reconstruct url and info
3673 $log->info = $modname." ".$modid;
3674 $log->url = "../mod/".$modname."/view.php?id=".$cmid;
3675 $toinsert = true;
3678 break;
3679 case "update mod":
3680 //Extract the course_module from the url field
3681 $cmid = substr(strrchr($log->url,"="),1);
3682 //recode the course_module to see it it has been restored
3683 $cm = backup_getid($restore->backup_unique_code,"course_modules",$cmid);
3684 if ($cm) {
3685 $cmid = $cm->new_id;
3686 //Extract the module name and the module id from the info field
3687 $modname = strtok($log->info," ");
3688 $modid = strtok(" ");
3689 //recode the module id to see if it has been restored
3690 $mod = backup_getid($restore->backup_unique_code,$modname,$modid);
3691 if ($mod) {
3692 $modid = $mod->new_id;
3693 //Now I have everything so reconstruct url and info
3694 $log->info = $modname." ".$modid;
3695 $log->url = "../mod/".$modname."/view.php?id=".$cmid;
3696 $toinsert = true;
3699 break;
3700 case "delete mod":
3701 $log->url = "view.php?id=".$log->course;
3702 $toinsert = true;
3703 break;
3704 case "update":
3705 $log->url = "edit.php?id=".$log->course;
3706 $log->info = "";
3707 $toinsert = true;
3708 break;
3709 case "unenrol":
3710 //recode the info field (it's the user id)
3711 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3712 if ($user) {
3713 $log->info = $user->new_id;
3714 $log->url = "view.php?id=".$log->course;
3715 $toinsert = true;
3717 break;
3718 case "enrol":
3719 //recode the info field (it's the user id)
3720 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3721 if ($user) {
3722 $log->info = $user->new_id;
3723 $log->url = "view.php?id=".$log->course;
3724 $toinsert = true;
3726 break;
3727 case "editsection":
3728 //Extract the course_section from the url field
3729 $secid = substr(strrchr($log->url,"="),1);
3730 //recode the course_section to see if it has been restored
3731 $sec = backup_getid($restore->backup_unique_code,"course_sections",$secid);
3732 if ($sec) {
3733 $secid = $sec->new_id;
3734 //Now I have everything so reconstruct url and info
3735 $log->url = "editsection.php?id=".$secid;
3736 $toinsert = true;
3738 break;
3739 case "new":
3740 $log->url = "view.php?id=".$log->course;
3741 $log->info = "";
3742 $toinsert = true;
3743 break;
3744 case "recent":
3745 $log->url = "recent.php?id=".$log->course;
3746 $log->info = "";
3747 $toinsert = true;
3748 break;
3749 case "report log":
3750 $log->url = "report/log/index.php?id=".$log->course;
3751 $log->info = $log->course;
3752 $toinsert = true;
3753 break;
3754 case "report live":
3755 $log->url = "report/log/live.php?id=".$log->course;
3756 $log->info = $log->course;
3757 $toinsert = true;
3758 break;
3759 case "report outline":
3760 $log->url = "report/outline/index.php?id=".$log->course;
3761 $log->info = $log->course;
3762 $toinsert = true;
3763 break;
3764 case "report participation":
3765 $log->url = "report/participation/index.php?id=".$log->course;
3766 $log->info = $log->course;
3767 $toinsert = true;
3768 break;
3769 case "report stats":
3770 $log->url = "report/stats/index.php?id=".$log->course;
3771 $log->info = $log->course;
3772 $toinsert = true;
3773 break;
3774 default:
3775 echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug
3776 break;
3779 //echo "After transformations<br />"; //Debug
3780 //print_object($log); //Debug
3782 //Now if $toinsert is set, insert the record
3783 if ($toinsert) {
3784 //echo "Inserting record<br />"; //Debug
3785 $status = insert_record("log",$log);
3787 return $status;
3790 //This function inserts a user log record, calculating the URL field as necessary
3791 function restore_log_user($restore,$log) {
3793 $status = true;
3794 $toinsert = false;
3796 //echo "<hr />Before transformations<br />"; //Debug
3797 //print_object($log); //Debug
3798 //Depending of the action, we recode different things
3799 switch ($log->action) {
3800 case "view":
3801 //recode the info field (it's the user id)
3802 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3803 if ($user) {
3804 $log->info = $user->new_id;
3805 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3806 $toinsert = true;
3808 break;
3809 case "change password":
3810 //recode the info field (it's the user id)
3811 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3812 if ($user) {
3813 $log->info = $user->new_id;
3814 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3815 $toinsert = true;
3817 break;
3818 case "login":
3819 //recode the info field (it's the user id)
3820 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3821 if ($user) {
3822 $log->info = $user->new_id;
3823 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3824 $toinsert = true;
3826 break;
3827 case "logout":
3828 //recode the info field (it's the user id)
3829 $user = backup_getid($restore->backup_unique_code,"user",$log->info);
3830 if ($user) {
3831 $log->info = $user->new_id;
3832 $log->url = "view.php?id=".$log->info."&course=".$log->course;
3833 $toinsert = true;
3835 break;
3836 case "view all":
3837 $log->url = "view.php?id=".$log->course;
3838 $log->info = "";
3839 $toinsert = true;
3840 case "update":
3841 //We split the url by ampersand char
3842 $first_part = strtok($log->url,"&");
3843 //Get data after the = char. It's the user being updated
3844 $userid = substr(strrchr($first_part,"="),1);
3845 //Recode the user
3846 $user = backup_getid($restore->backup_unique_code,"user",$userid);
3847 if ($user) {
3848 $log->info = "";
3849 $log->url = "view.php?id=".$user->new_id."&course=".$log->course;
3850 $toinsert = true;
3852 break;
3853 default:
3854 echo "action (".$log->module."-".$log->action.") unknown. Not restored<br />"; //Debug
3855 break;
3858 //echo "After transformations<br />"; //Debug
3859 //print_object($log); //Debug
3861 //Now if $toinsert is set, insert the record
3862 if ($toinsert) {
3863 //echo "Inserting record<br />"; //Debug
3864 $status = insert_record("log",$log);
3866 return $status;
3869 //This function inserts a module log record, calculating the URL field as necessary
3870 function restore_log_module($restore,$log) {
3872 $status = true;
3873 $toinsert = false;
3875 //echo "<hr />Before transformations<br />"; //Debug
3876 //print_object($log); //Debug
3878 //Now we see if the required function in the module exists
3879 $function = $log->module."_restore_logs";
3880 if (function_exists($function)) {
3881 //Call the function
3882 $log = $function($restore,$log);
3883 //If everything is ok, mark the insert flag
3884 if ($log) {
3885 $toinsert = true;
3889 //echo "After transformations<br />"; //Debug
3890 //print_object($log); //Debug
3892 //Now if $toinsert is set, insert the record
3893 if ($toinsert) {
3894 //echo "Inserting record<br />"; //Debug
3895 $status = insert_record("log",$log);
3897 return $status;
3900 //This function adjusts the instance field into course_modules. It's executed after
3901 //modules restore. There, we KNOW the new instance id !!
3902 function restore_check_instances($restore) {
3904 global $CFG;
3906 $status = true;
3908 //We are going to iterate over each course_module saved in backup_ids
3909 $course_modules = get_records_sql("SELECT old_id,new_id
3910 FROM {$CFG->prefix}backup_ids
3911 WHERE backup_code = '$restore->backup_unique_code' AND
3912 table_name = 'course_modules'");
3913 if ($course_modules) {
3914 foreach($course_modules as $cm) {
3915 //Get full record, using backup_getids
3916 $cm_module = backup_getid($restore->backup_unique_code,"course_modules",$cm->old_id);
3917 //Now we are going to the REAL course_modules to get its type (field module)
3918 $module = get_record("course_modules","id",$cm_module->new_id);
3919 if ($module) {
3920 //We know the module type id. Get the name from modules
3921 $type = get_record("modules","id",$module->module);
3922 if ($type) {
3923 //We know the type name and the old_id. Get its new_id
3924 //from backup_ids. It's the instance !!!
3925 $instance = backup_getid($restore->backup_unique_code,$type->name,$cm_module->info);
3926 if ($instance) {
3927 //We have the new instance, so update the record in course_modules
3928 $module->instance = $instance->new_id;
3929 //print_object ($module); //Debug
3930 $status = update_record("course_modules",$module);
3931 } else {
3932 $status = false;
3934 } else {
3935 $status = false;
3937 } else {
3938 $status = false;
3944 return $status;
3947 //=====================================================================================
3948 //== ==
3949 //== XML Functions (SAX) ==
3950 //== ==
3951 //=====================================================================================
3953 //This is the class used to do all the xml parse
3954 class MoodleParser {
3956 var $level = 0; //Level we are
3957 var $counter = 0; //Counter
3958 var $tree = array(); //Array of levels we are
3959 var $content = ""; //Content under current level
3960 var $todo = ""; //What we hav to do when parsing
3961 var $info = ""; //Information collected. Temp storage. Used to return data after parsing.
3962 var $temp = ""; //Temp storage.
3963 var $preferences = ""; //Preferences about what to load !!
3964 var $finished = false; //Flag to say xml_parse to stop
3966 //This function is used to get the current contents property value
3967 //They are trimed (and converted from utf8 if needed)
3968 function getContents() {
3969 return trim($this->content);
3972 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3973 function startElementInfo($parser, $tagName, $attrs) {
3974 //Refresh properties
3975 $this->level++;
3976 $this->tree[$this->level] = $tagName;
3978 //Output something to avoid browser timeouts...
3979 backup_flush();
3981 //Check if we are into INFO zone
3982 //if ($this->tree[2] == "INFO") //Debug
3983 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
3986 //This is the startTag handler we use where we are reading the info zone (todo="INFO")
3987 function startElementRoles($parser, $tagName, $attrs) {
3988 //Refresh properties
3989 $this->level++;
3990 $this->tree[$this->level] = $tagName;
3992 //Output something to avoid browser timeouts...
3993 backup_flush();
3995 //Check if we are into INFO zone
3996 //if ($this->tree[2] == "INFO") //Debug
3997 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4001 //This is the startTag handler we use where we are reading the course header zone (todo="COURSE_HEADER")
4002 function startElementCourseHeader($parser, $tagName, $attrs) {
4003 //Refresh properties
4004 $this->level++;
4005 $this->tree[$this->level] = $tagName;
4007 //Output something to avoid browser timeouts...
4008 backup_flush();
4010 //Check if we are into COURSE_HEADER zone
4011 //if ($this->tree[3] == "HEADER") //Debug
4012 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4015 //This is the startTag handler we use where we are reading the blocks zone (todo="BLOCKS")
4016 function startElementBlocks($parser, $tagName, $attrs) {
4017 //Refresh properties
4018 $this->level++;
4019 $this->tree[$this->level] = $tagName;
4021 //Output something to avoid browser timeouts...
4022 backup_flush();
4024 //Check if we are into BLOCKS zone
4025 //if ($this->tree[3] == "BLOCKS") //Debug
4026 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4029 //This is the startTag handler we use where we are reading the sections zone (todo="SECTIONS")
4030 function startElementSections($parser, $tagName, $attrs) {
4031 //Refresh properties
4032 $this->level++;
4033 $this->tree[$this->level] = $tagName;
4035 //Output something to avoid browser timeouts...
4036 backup_flush();
4038 //Check if we are into SECTIONS zone
4039 //if ($this->tree[3] == "SECTIONS") //Debug
4040 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4043 //This is the startTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
4044 function startElementFormatData($parser, $tagName, $attrs) {
4045 //Refresh properties
4046 $this->level++;
4047 $this->tree[$this->level] = $tagName;
4049 //Output something to avoid browser timeouts...
4050 backup_flush();
4052 //Accumulate all the data inside this tag
4053 if (isset($this->tree[3]) && $this->tree[3] == "FORMATDATA") {
4054 if (!isset($this->temp)) {
4055 $this->temp = '';
4057 $this->temp .= "<".$tagName.">";
4060 //Check if we are into FORMATDATA zone
4061 //if ($this->tree[3] == "FORMATDATA") //Debug
4062 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4065 //This is the startTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
4066 function startElementMetacourse($parser, $tagName, $attrs) {
4068 //Refresh properties
4069 $this->level++;
4070 $this->tree[$this->level] = $tagName;
4072 //Output something to avoid browser timeouts...
4073 backup_flush();
4075 //Check if we are into METACOURSE zone
4076 //if ($this->tree[3] == "METACOURSE") //Debug
4077 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4080 //This is the startTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
4081 function startElementGradebook($parser, $tagName, $attrs) {
4083 //Refresh properties
4084 $this->level++;
4085 $this->tree[$this->level] = $tagName;
4087 //Output something to avoid browser timeouts...
4088 backup_flush();
4090 //Check if we are into GRADEBOOK zone
4091 //if ($this->tree[3] == "GRADEBOOK") //Debug
4092 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4094 //If we are under a GRADE_PREFERENCE, GRADE_LETTER or GRADE_CATEGORY tag under a GRADEBOOK zone, accumule it
4095 if (isset($this->tree[5]) and isset($this->tree[3])) {
4096 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")) {
4098 if (!isset($this->temp)) {
4099 $this->temp = "";
4101 $this->temp .= "<".$tagName.">";
4107 //This is the startTag handler we use where we are reading the user zone (todo="USERS")
4108 function startElementUsers($parser, $tagName, $attrs) {
4109 //Refresh properties
4110 $this->level++;
4111 $this->tree[$this->level] = $tagName;
4113 //Check if we are into USERS zone
4114 //if ($this->tree[3] == "USERS") //Debug
4115 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4118 //This is the startTag handler we use where we are reading the messages zone (todo="MESSAGES")
4119 function startElementMessages($parser, $tagName, $attrs) {
4120 //Refresh properties
4121 $this->level++;
4122 $this->tree[$this->level] = $tagName;
4124 //Output something to avoid browser timeouts...
4125 backup_flush();
4127 //Check if we are into MESSAGES zone
4128 //if ($this->tree[3] == "MESSAGES") //Debug
4129 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4131 //If we are under a MESSAGE tag under a MESSAGES zone, accumule it
4132 if (isset($this->tree[4]) and isset($this->tree[3])) {
4133 if (($this->tree[4] == "MESSAGE" || $this->tree[5] == "CONTACT" ) and ($this->tree[3] == "MESSAGES")) {
4134 if (!isset($this->temp)) {
4135 $this->temp = "";
4137 $this->temp .= "<".$tagName.">";
4141 //This is the startTag handler we use where we are reading the questions zone (todo="QUESTIONS")
4142 function startElementQuestions($parser, $tagName, $attrs) {
4143 //Refresh properties
4144 $this->level++;
4145 $this->tree[$this->level] = $tagName;
4147 //if ($tagName == "QUESTION_CATEGORY" && $this->tree[3] == "QUESTION_CATEGORIES") { //Debug
4148 // echo "<P>QUESTION_CATEGORY: ".strftime ("%X",time()),"-"; //Debug
4149 //} //Debug
4151 //Output something to avoid browser timeouts...
4152 backup_flush();
4154 //Check if we are into QUESTION_CATEGORIES zone
4155 //if ($this->tree[3] == "QUESTION_CATEGORIES") //Debug
4156 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4158 //If we are under a QUESTION_CATEGORY tag under a QUESTION_CATEGORIES zone, accumule it
4159 if (isset($this->tree[4]) and isset($this->tree[3])) {
4160 if (($this->tree[4] == "QUESTION_CATEGORY") and ($this->tree[3] == "QUESTION_CATEGORIES")) {
4161 if (!isset($this->temp)) {
4162 $this->temp = "";
4164 $this->temp .= "<".$tagName.">";
4169 //This is the startTag handler we use where we are reading the scales zone (todo="SCALES")
4170 function startElementScales($parser, $tagName, $attrs) {
4171 //Refresh properties
4172 $this->level++;
4173 $this->tree[$this->level] = $tagName;
4175 //if ($tagName == "SCALE" && $this->tree[3] == "SCALES") { //Debug
4176 // echo "<P>SCALE: ".strftime ("%X",time()),"-"; //Debug
4177 //} //Debug
4179 //Output something to avoid browser timeouts...
4180 backup_flush();
4182 //Check if we are into SCALES zone
4183 //if ($this->tree[3] == "SCALES") //Debug
4184 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4186 //If we are under a SCALE tag under a SCALES zone, accumule it
4187 if (isset($this->tree[4]) and isset($this->tree[3])) {
4188 if (($this->tree[4] == "SCALE") and ($this->tree[3] == "SCALES")) {
4189 if (!isset($this->temp)) {
4190 $this->temp = "";
4192 $this->temp .= "<".$tagName.">";
4197 function startElementGroups($parser, $tagName, $attrs) {
4198 //Refresh properties
4199 $this->level++;
4200 $this->tree[$this->level] = $tagName;
4202 //if ($tagName == "GROUP" && $this->tree[3] == "GROUPS") { //Debug
4203 // echo "<P>GROUP: ".strftime ("%X",time()),"-"; //Debug
4204 //} //Debug
4206 //Output something to avoid browser timeouts...
4207 backup_flush();
4209 //Check if we are into GROUPS zone
4210 //if ($this->tree[3] == "GROUPS") //Debug
4211 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4213 //If we are under a GROUP tag under a GROUPS zone, accumule it
4214 if (isset($this->tree[4]) and isset($this->tree[3])) {
4215 if (($this->tree[4] == "GROUP") and ($this->tree[3] == "GROUPS")) {
4216 if (!isset($this->temp)) {
4217 $this->temp = "";
4219 $this->temp .= "<".$tagName.">";
4224 function startElementGroupings($parser, $tagName, $attrs) {
4225 //Refresh properties
4226 $this->level++;
4227 $this->tree[$this->level] = $tagName;
4229 //if ($tagName == "GROUPING" && $this->tree[3] == "GROUPINGS") { //Debug
4230 // echo "<P>GROUPING: ".strftime ("%X",time()),"-"; //Debug
4231 //} //Debug
4233 //Output something to avoid browser timeouts...
4234 backup_flush();
4236 //Check if we are into GROUPINGS zone
4237 //if ($this->tree[3] == "GROUPINGS") //Debug
4238 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4240 //If we are under a GROUPING tag under a GROUPINGS zone, accumule it
4241 if (isset($this->tree[4]) and isset($this->tree[3])) {
4242 if (($this->tree[4] == "GROUPING") and ($this->tree[3] == "GROUPINGS")) {
4243 if (!isset($this->temp)) {
4244 $this->temp = "";
4246 $this->temp .= "<".$tagName.">";
4251 function startElementGroupingsGroups($parser, $tagName, $attrs) {
4252 //Refresh properties
4253 $this->level++;
4254 $this->tree[$this->level] = $tagName;
4256 //if ($tagName == "GROUPINGGROUP" && $this->tree[3] == "GROUPINGSGROUPS") { //Debug
4257 // echo "<P>GROUPINGSGROUP: ".strftime ("%X",time()),"-"; //Debug
4258 //} //Debug
4260 //Output something to avoid browser timeouts...
4261 backup_flush();
4263 //Check if we are into GROUPINGSGROUPS zone
4264 //if ($this->tree[3] == "GROUPINGSGROUPS") //Debug
4265 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4267 //If we are under a GROUPINGGROUP tag under a GROUPINGSGROUPS zone, accumule it
4268 if (isset($this->tree[4]) and isset($this->tree[3])) {
4269 if (($this->tree[4] == "GROUPINGGROUP") and ($this->tree[3] == "GROUPINGSGROUPS")) {
4270 if (!isset($this->temp)) {
4271 $this->temp = "";
4273 $this->temp .= "<".$tagName.">";
4278 //This is the startTag handler we use where we are reading the events zone (todo="EVENTS")
4279 function startElementEvents($parser, $tagName, $attrs) {
4280 //Refresh properties
4281 $this->level++;
4282 $this->tree[$this->level] = $tagName;
4284 //if ($tagName == "EVENT" && $this->tree[3] == "EVENTS") { //Debug
4285 // echo "<P>EVENT: ".strftime ("%X",time()),"-"; //Debug
4286 //} //Debug
4288 //Output something to avoid browser timeouts...
4289 backup_flush();
4291 //Check if we are into EVENTS zone
4292 //if ($this->tree[3] == "EVENTS") //Debug
4293 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4295 //If we are under a EVENT tag under a EVENTS zone, accumule it
4296 if (isset($this->tree[4]) and isset($this->tree[3])) {
4297 if (($this->tree[4] == "EVENT") and ($this->tree[3] == "EVENTS")) {
4298 if (!isset($this->temp)) {
4299 $this->temp = "";
4301 $this->temp .= "<".$tagName.">";
4306 //This is the startTag handler we use where we are reading the modules zone (todo="MODULES")
4307 function startElementModules($parser, $tagName, $attrs) {
4308 //Refresh properties
4309 $this->level++;
4310 $this->tree[$this->level] = $tagName;
4312 //if ($tagName == "MOD" && $this->tree[3] == "MODULES") { //Debug
4313 // echo "<P>MOD: ".strftime ("%X",time()),"-"; //Debug
4314 //} //Debug
4316 //Output something to avoid browser timeouts...
4317 backup_flush();
4319 //Check if we are into MODULES zone
4320 //if ($this->tree[3] == "MODULES") //Debug
4321 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4323 //If we are under a MOD tag under a MODULES zone, accumule it
4324 if (isset($this->tree[4]) and isset($this->tree[3])) {
4325 if (($this->tree[4] == "MOD") and ($this->tree[3] == "MODULES")) {
4326 if (!isset($this->temp)) {
4327 $this->temp = "";
4329 $this->temp .= "<".$tagName.">";
4334 //This is the startTag handler we use where we are reading the logs zone (todo="LOGS")
4335 function startElementLogs($parser, $tagName, $attrs) {
4336 //Refresh properties
4337 $this->level++;
4338 $this->tree[$this->level] = $tagName;
4340 //if ($tagName == "LOG" && $this->tree[3] == "LOGS") { //Debug
4341 // echo "<P>LOG: ".strftime ("%X",time()),"-"; //Debug
4342 //} //Debug
4344 //Output something to avoid browser timeouts...
4345 backup_flush();
4347 //Check if we are into LOGS zone
4348 //if ($this->tree[3] == "LOGS") //Debug
4349 // echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4351 //If we are under a LOG tag under a LOGS zone, accumule it
4352 if (isset($this->tree[4]) and isset($this->tree[3])) {
4353 if (($this->tree[4] == "LOG") and ($this->tree[3] == "LOGS")) {
4354 if (!isset($this->temp)) {
4355 $this->temp = "";
4357 $this->temp .= "<".$tagName.">";
4362 //This is the startTag default handler we use when todo is undefined
4363 function startElement($parser, $tagName, $attrs) {
4364 $this->level++;
4365 $this->tree[$this->level] = $tagName;
4367 //Output something to avoid browser timeouts...
4368 backup_flush();
4370 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;".$tagName."&gt;<br />\n"; //Debug
4373 //This is the endTag handler we use where we are reading the info zone (todo="INFO")
4374 function endElementInfo($parser, $tagName) {
4375 //Check if we are into INFO zone
4376 if ($this->tree[2] == "INFO") {
4377 //if (trim($this->content)) //Debug
4378 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4379 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4380 //Dependig of different combinations, do different things
4381 if ($this->level == 3) {
4382 switch ($tagName) {
4383 case "NAME":
4384 $this->info->backup_name = $this->getContents();
4385 break;
4386 case "MOODLE_VERSION":
4387 $this->info->backup_moodle_version = $this->getContents();
4388 break;
4389 case "MOODLE_RELEASE":
4390 $this->info->backup_moodle_release = $this->getContents();
4391 break;
4392 case "BACKUP_VERSION":
4393 $this->info->backup_backup_version = $this->getContents();
4394 break;
4395 case "BACKUP_RELEASE":
4396 $this->info->backup_backup_release = $this->getContents();
4397 break;
4398 case "DATE":
4399 $this->info->backup_date = $this->getContents();
4400 break;
4401 case "ORIGINAL_WWWROOT":
4402 $this->info->original_wwwroot = $this->getContents();
4403 break;
4404 case "MNET_EXTERNALUSERS":
4405 $this->info->mnet_externalusers = $this->getContents();
4406 break;
4409 if ($this->tree[3] == "DETAILS") {
4410 if ($this->level == 4) {
4411 switch ($tagName) {
4412 case "METACOURSE":
4413 $this->info->backup_metacourse = $this->getContents();
4414 break;
4415 case "USERS":
4416 $this->info->backup_users = $this->getContents();
4417 break;
4418 case "LOGS":
4419 $this->info->backup_logs = $this->getContents();
4420 break;
4421 case "USERFILES":
4422 $this->info->backup_user_files = $this->getContents();
4423 break;
4424 case "COURSEFILES":
4425 $this->info->backup_course_files = $this->getContents();
4426 break;
4427 case "SITEFILES":
4428 $this->info->backup_site_files = $this->getContents();
4429 break;
4430 case "MESSAGES":
4431 $this->info->backup_messages = $this->getContents();
4432 break;
4433 case 'BLOCKFORMAT':
4434 $this->info->backup_block_format = $this->getContents();
4435 break;
4438 if ($this->level == 5) {
4439 switch ($tagName) {
4440 case "NAME":
4441 $this->info->tempName = $this->getContents();
4442 break;
4443 case "INCLUDED":
4444 $this->info->mods[$this->info->tempName]->backup = $this->getContents();
4445 break;
4446 case "USERINFO":
4447 $this->info->mods[$this->info->tempName]->userinfo = $this->getContents();
4448 break;
4451 if ($this->level == 7) {
4452 switch ($tagName) {
4453 case "ID":
4454 $this->info->tempId = $this->getContents();
4455 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->id = $this->info->tempId;
4456 break;
4457 case "NAME":
4458 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->name = $this->getContents();
4459 break;
4460 case "INCLUDED":
4461 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->backup = $this->getContents();
4462 break;
4463 case "USERINFO":
4464 $this->info->mods[$this->info->tempName]->instances[$this->info->tempId]->userinfo = $this->getContents();
4465 break;
4471 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
4472 //Speed up a lot (avoid parse all)
4473 if ($tagName == "INFO") {
4474 $this->finished = true;
4477 //Clear things
4478 $this->tree[$this->level] = "";
4479 $this->level--;
4480 $this->content = "";
4484 function endElementRoles($parser, $tagName) {
4485 //Check if we are into INFO zone
4486 if ($this->tree[2] == "ROLES") {
4488 if ($this->tree[3] == "ROLE") {
4489 if ($this->level == 4) {
4490 switch ($tagName) {
4491 case "NAME":
4492 $this->info->tempname = $this->getContents();
4494 break;
4495 case "SHORTNAME":
4496 $this->info->tempshortname = $this->getContents();
4497 break;
4498 case "ID": // this is the old id
4499 $this->info->tempid = $this->getContents();
4500 break;
4503 if ($this->level == 6) {
4504 switch ($tagName) {
4505 case "NAME":
4506 $this->info->roles[$this->info->tempid]->name = $this->info->tempname;
4507 $this->info->roles[$this->info->tempid]->shortname = $this->info->tempshortname;
4509 $this->info->tempcapname = $this->getContents();
4510 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->name = $this->getContents();
4511 break;
4512 case "PERMISSION":
4513 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->permission = $this->getContents();
4514 break;
4515 case "TIMEMODIFIED":
4516 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->timemodified = $this->getContents();
4517 break;
4518 case "MODIFIERID":
4519 $this->info->roles[$this->info->tempid]->capabilities[$this->info->tempcapname]->modifierid = $this->getContents();
4520 break;
4526 //Stop parsing if todo = INFO and tagName = INFO (en of the tag, of course)
4527 //Speed up a lot (avoid parse all)
4528 if ($tagName == "ROLES") {
4529 $this->finished = true;
4532 //Clear things
4533 $this->tree[$this->level] = "";
4534 $this->level--;
4535 $this->content = "";
4539 //This is the endTag handler we use where we are reading the course_header zone (todo="COURSE_HEADER")
4540 function endElementCourseHeader($parser, $tagName) {
4541 //Check if we are into COURSE_HEADER zone
4542 if ($this->tree[3] == "HEADER") {
4543 //if (trim($this->content)) //Debug
4544 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4545 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4546 //Dependig of different combinations, do different things
4547 if ($this->level == 4) {
4548 switch ($tagName) {
4549 case "ID":
4550 $this->info->course_id = $this->getContents();
4551 break;
4552 case "PASSWORD":
4553 $this->info->course_password = $this->getContents();
4554 break;
4555 case "FULLNAME":
4556 $this->info->course_fullname = $this->getContents();
4557 break;
4558 case "SHORTNAME":
4559 $this->info->course_shortname = $this->getContents();
4560 break;
4561 case "IDNUMBER":
4562 $this->info->course_idnumber = $this->getContents();
4563 break;
4564 case "SUMMARY":
4565 $this->info->course_summary = $this->getContents();
4566 break;
4567 case "FORMAT":
4568 $this->info->course_format = $this->getContents();
4569 break;
4570 case "SHOWGRADES":
4571 $this->info->course_showgrades = $this->getContents();
4572 break;
4573 case "BLOCKINFO":
4574 $this->info->blockinfo = $this->getContents();
4575 break;
4576 case "NEWSITEMS":
4577 $this->info->course_newsitems = $this->getContents();
4578 break;
4579 case "TEACHER":
4580 $this->info->course_teacher = $this->getContents();
4581 break;
4582 case "TEACHERS":
4583 $this->info->course_teachers = $this->getContents();
4584 break;
4585 case "STUDENT":
4586 $this->info->course_student = $this->getContents();
4587 break;
4588 case "STUDENTS":
4589 $this->info->course_students = $this->getContents();
4590 break;
4591 case "GUEST":
4592 $this->info->course_guest = $this->getContents();
4593 break;
4594 case "STARTDATE":
4595 $this->info->course_startdate = $this->getContents();
4596 break;
4597 case "NUMSECTIONS":
4598 $this->info->course_numsections = $this->getContents();
4599 break;
4600 //case "SHOWRECENT": INFO: This is out in 1.3
4601 // $this->info->course_showrecent = $this->getContents();
4602 // break;
4603 case "MAXBYTES":
4604 $this->info->course_maxbytes = $this->getContents();
4605 break;
4606 case "SHOWREPORTS":
4607 $this->info->course_showreports = $this->getContents();
4608 break;
4609 case "GROUPMODE":
4610 $this->info->course_groupmode = $this->getContents();
4611 break;
4612 case "GROUPMODEFORCE":
4613 $this->info->course_groupmodeforce = $this->getContents();
4614 break;
4615 case "DEFAULTGROUPINGID":
4616 $this->info->course_defaultgroupingid = $this->getContents();
4617 break;
4618 case "LANG":
4619 $this->info->course_lang = $this->getContents();
4620 break;
4621 case "THEME":
4622 $this->info->course_theme = $this->getContents();
4623 break;
4624 case "COST":
4625 $this->info->course_cost = $this->getContents();
4626 break;
4627 case "CURRENCY":
4628 $this->info->course_currency = $this->getContents();
4629 break;
4630 case "MARKER":
4631 $this->info->course_marker = $this->getContents();
4632 break;
4633 case "VISIBLE":
4634 $this->info->course_visible = $this->getContents();
4635 break;
4636 case "HIDDENSECTIONS":
4637 $this->info->course_hiddensections = $this->getContents();
4638 break;
4639 case "TIMECREATED":
4640 $this->info->course_timecreated = $this->getContents();
4641 break;
4642 case "TIMEMODIFIED":
4643 $this->info->course_timemodified = $this->getContents();
4644 break;
4645 case "METACOURSE":
4646 $this->info->course_metacourse = $this->getContents();
4647 break;
4648 case "EXPIRENOTIFY":
4649 $this->info->course_expirynotify = $this->getContents();
4650 break;
4651 case "NOTIFYSTUDENTS":
4652 $this->info->course_notifystudents = $this->getContents();
4653 break;
4654 case "EXPIRYTHRESHOLD":
4655 $this->info->course_expirythreshold = $this->getContents();
4656 break;
4657 case "ENROLLABLE":
4658 $this->info->course_enrollable = $this->getContents();
4659 break;
4660 case "ENROLSTARTDATE":
4661 $this->info->course_enrolstartdate = $this->getContents();
4662 break;
4663 case "ENROLENDDATE":
4664 $this->info->course_enrolenddate = $this->getContents();
4665 break;
4666 case "ENROLPERIOD":
4667 $this->info->course_enrolperiod = $this->getContents();
4668 break;
4671 if ($this->tree[4] == "CATEGORY") {
4672 if ($this->level == 5) {
4673 switch ($tagName) {
4674 case "ID":
4675 $this->info->category->id = $this->getContents();
4676 break;
4677 case "NAME":
4678 $this->info->category->name = $this->getContents();
4679 break;
4684 if ($this->tree[4] == "ROLES_ASSIGNMENTS") {
4685 if ($this->level == 6) {
4686 switch ($tagName) {
4687 case "NAME":
4688 $this->info->tempname = $this->getContents();
4689 break;
4690 case "SHORTNAME":
4691 $this->info->tempshortname = $this->getContents();
4692 break;
4693 case "ID":
4694 $this->info->tempid = $this->getContents();
4695 break;
4699 if ($this->level == 8) {
4700 switch ($tagName) {
4701 case "USERID":
4702 $this->info->roleassignments[$this->info->tempid]->name = $this->info->tempname;
4703 $this->info->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
4704 $this->info->tempuser = $this->getContents();
4705 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
4706 break;
4707 case "HIDDEN":
4708 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
4709 break;
4710 case "TIMESTART":
4711 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
4712 break;
4713 case "TIMEEND":
4714 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
4715 break;
4716 case "TIMEMODIFIED":
4717 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
4718 break;
4719 case "MODIFIERID":
4720 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
4721 break;
4722 case "ENROL":
4723 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
4724 break;
4725 case "SORTORDER":
4726 $this->info->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
4727 break;
4731 } /// ends role_assignments
4733 if ($this->tree[4] == "ROLES_OVERRIDES") {
4734 if ($this->level == 6) {
4735 switch ($tagName) {
4736 case "NAME":
4737 $this->info->tempname = $this->getContents();
4738 break;
4739 case "SHORTNAME":
4740 $this->info->tempshortname = $this->getContents();
4741 break;
4742 case "ID":
4743 $this->info->tempid = $this->getContents();
4744 break;
4748 if ($this->level == 8) {
4749 switch ($tagName) {
4750 case "NAME":
4751 $this->info->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
4752 $this->info->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
4753 $this->info->tempname = $this->getContents(); // change to name of capability
4754 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
4755 break;
4756 case "PERMISSION":
4757 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
4758 break;
4759 case "TIMEMODIFIED":
4760 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
4761 break;
4762 case "MODIFIERID":
4763 $this->info->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
4764 break;
4767 } /// ends role_overrides
4770 //Stop parsing if todo = COURSE_HEADER and tagName = HEADER (en of the tag, of course)
4771 //Speed up a lot (avoid parse all)
4772 if ($tagName == "HEADER") {
4773 $this->finished = true;
4776 //Clear things
4777 $this->tree[$this->level] = "";
4778 $this->level--;
4779 $this->content = "";
4783 //This is the endTag handler we use where we are reading the sections zone (todo="BLOCKS")
4784 function endElementBlocks($parser, $tagName) {
4785 //Check if we are into BLOCKS zone
4786 if ($this->tree[3] == 'BLOCKS') {
4787 //if (trim($this->content)) //Debug
4788 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4789 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4790 //Dependig of different combinations, do different things
4791 if ($this->level == 4) {
4792 switch ($tagName) {
4793 case 'BLOCK':
4794 //We've finalized a block, get it
4795 $this->info->instances[] = $this->info->tempinstance;
4796 unset($this->info->tempinstance);
4797 break;
4798 default:
4799 die($tagName);
4802 if ($this->level == 5) {
4803 switch ($tagName) {
4804 case 'ID':
4805 $this->info->tempinstance->id = $this->getContents();
4806 case 'NAME':
4807 $this->info->tempinstance->name = $this->getContents();
4808 break;
4809 case 'PAGEID':
4810 $this->info->tempinstance->pageid = $this->getContents();
4811 break;
4812 case 'PAGETYPE':
4813 $this->info->tempinstance->pagetype = $this->getContents();
4814 break;
4815 case 'POSITION':
4816 $this->info->tempinstance->position = $this->getContents();
4817 break;
4818 case 'WEIGHT':
4819 $this->info->tempinstance->weight = $this->getContents();
4820 break;
4821 case 'VISIBLE':
4822 $this->info->tempinstance->visible = $this->getContents();
4823 break;
4824 case 'CONFIGDATA':
4825 $this->info->tempinstance->configdata = $this->getContents();
4826 break;
4827 default:
4828 break;
4832 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
4833 if ($this->level == 7) {
4834 switch ($tagName) {
4835 case "NAME":
4836 $this->info->tempname = $this->getContents();
4837 break;
4838 case "SHORTNAME":
4839 $this->info->tempshortname = $this->getContents();
4840 break;
4841 case "ID":
4842 $this->info->tempid = $this->getContents(); // temp roleid
4843 break;
4847 if ($this->level == 9) {
4849 switch ($tagName) {
4850 case "USERID":
4851 $this->info->tempinstance->roleassignments[$this->info->tempid]->name = $this->info->tempname;
4853 $this->info->tempinstance->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
4855 $this->info->tempuser = $this->getContents();
4857 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
4858 break;
4859 case "HIDDEN":
4860 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
4861 break;
4862 case "TIMESTART":
4863 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
4864 break;
4865 case "TIMEEND":
4866 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
4867 break;
4868 case "TIMEMODIFIED":
4869 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
4870 break;
4871 case "MODIFIERID":
4872 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
4873 break;
4874 case "ENROL":
4875 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
4876 break;
4877 case "SORTORDER":
4878 $this->info->tempinstance->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
4879 break;
4883 } /// ends role_assignments
4885 if ($this->tree[5] == "ROLES_OVERRIDES") {
4886 if ($this->level == 7) {
4887 switch ($tagName) {
4888 case "NAME":
4889 $this->info->tempname = $this->getContents();
4890 break;
4891 case "SHORTNAME":
4892 $this->info->tempshortname = $this->getContents();
4893 break;
4894 case "ID":
4895 $this->info->tempid = $this->getContents(); // temp roleid
4896 break;
4900 if ($this->level == 9) {
4901 switch ($tagName) {
4902 case "NAME":
4904 $this->info->tempinstance->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
4905 $this->info->tempinstance->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
4906 $this->info->tempname = $this->getContents(); // change to name of capability
4907 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
4908 break;
4909 case "PERMISSION":
4910 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
4911 break;
4912 case "TIMEMODIFIED":
4913 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
4914 break;
4915 case "MODIFIERID":
4916 $this->info->tempinstance->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
4917 break;
4920 } /// ends role_overrides
4923 //Stop parsing if todo = BLOCKS and tagName = BLOCKS (en of the tag, of course)
4924 //Speed up a lot (avoid parse all)
4925 //WARNING: ONLY EXIT IF todo = BLOCKS (thus tree[3] = "BLOCKS") OTHERWISE
4926 // THE BLOCKS TAG IN THE HEADER WILL TERMINATE US!
4927 if ($this->tree[3] == 'BLOCKS' && $tagName == 'BLOCKS') {
4928 $this->finished = true;
4931 //Clear things
4932 $this->tree[$this->level] = '';
4933 $this->level--;
4934 $this->content = "";
4937 //This is the endTag handler we use where we are reading the sections zone (todo="SECTIONS")
4938 function endElementSections($parser, $tagName) {
4939 //Check if we are into SECTIONS zone
4940 if ($this->tree[3] == "SECTIONS") {
4941 //if (trim($this->content)) //Debug
4942 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
4943 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
4944 //Dependig of different combinations, do different things
4945 if ($this->level == 4) {
4946 switch ($tagName) {
4947 case "SECTION":
4948 //We've finalized a section, get it
4949 $this->info->sections[$this->info->tempsection->id] = $this->info->tempsection;
4950 unset($this->info->tempsection);
4953 if ($this->level == 5) {
4954 switch ($tagName) {
4955 case "ID":
4956 $this->info->tempsection->id = $this->getContents();
4957 break;
4958 case "NUMBER":
4959 $this->info->tempsection->number = $this->getContents();
4960 break;
4961 case "SUMMARY":
4962 $this->info->tempsection->summary = $this->getContents();
4963 break;
4964 case "VISIBLE":
4965 $this->info->tempsection->visible = $this->getContents();
4966 break;
4969 if ($this->level == 6) {
4970 switch ($tagName) {
4971 case "MOD":
4972 if (!isset($this->info->tempmod->groupmode)) {
4973 $this->info->tempmod->groupmode = 0;
4975 if (!isset($this->info->tempmod->groupingid)) {
4976 $this->info->tempmod->groupingid = 0;
4978 if (!isset($this->info->tempmod->groupmembersonly)) {
4979 $this->info->tempmod->groupmembersonly = 0;
4982 //We've finalized a mod, get it
4983 $this->info->tempsection->mods[$this->info->tempmod->id]->type =
4984 $this->info->tempmod->type;
4985 $this->info->tempsection->mods[$this->info->tempmod->id]->instance =
4986 $this->info->tempmod->instance;
4987 $this->info->tempsection->mods[$this->info->tempmod->id]->added =
4988 $this->info->tempmod->added;
4989 $this->info->tempsection->mods[$this->info->tempmod->id]->score =
4990 $this->info->tempmod->score;
4991 $this->info->tempsection->mods[$this->info->tempmod->id]->indent =
4992 $this->info->tempmod->indent;
4993 $this->info->tempsection->mods[$this->info->tempmod->id]->visible =
4994 $this->info->tempmod->visible;
4995 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmode =
4996 $this->info->tempmod->groupmode;
4997 $this->info->tempsection->mods[$this->info->tempmod->id]->groupingid =
4998 $this->info->tempmod->groupingid;
4999 $this->info->tempsection->mods[$this->info->tempmod->id]->groupmembersonly =
5000 $this->info->tempmod->groupmembersonly;
5002 unset($this->info->tempmod);
5005 if ($this->level == 7) {
5006 switch ($tagName) {
5007 case "ID":
5008 $this->info->tempmod->id = $this->getContents();
5009 break;
5010 case "TYPE":
5011 $this->info->tempmod->type = $this->getContents();
5012 break;
5013 case "INSTANCE":
5014 $this->info->tempmod->instance = $this->getContents();
5015 break;
5016 case "ADDED":
5017 $this->info->tempmod->added = $this->getContents();
5018 break;
5019 case "SCORE":
5020 $this->info->tempmod->score = $this->getContents();
5021 break;
5022 case "INDENT":
5023 $this->info->tempmod->indent = $this->getContents();
5024 break;
5025 case "VISIBLE":
5026 $this->info->tempmod->visible = $this->getContents();
5027 break;
5028 case "GROUPMODE":
5029 $this->info->tempmod->groupmode = $this->getContents();
5030 break;
5031 case "GROUPINGID":
5032 $this->info->tempmod->groupingid = $this->getContents();
5033 break;
5034 case "GROUPMEMBERSONLY":
5035 $this->info->tempmod->groupmembersonly = $this->getContents();
5036 break;
5037 default:
5038 break;
5042 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_ASSIGNMENTS") {
5044 if ($this->level == 9) {
5045 switch ($tagName) {
5046 case "NAME":
5047 $this->info->tempname = $this->getContents();
5048 break;
5049 case "SHORTNAME":
5050 $this->info->tempshortname = $this->getContents();
5051 break;
5052 case "ID":
5053 $this->info->tempid = $this->getContents(); // temp roleid
5054 break;
5058 if ($this->level == 11) {
5059 switch ($tagName) {
5060 case "USERID":
5061 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5063 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5065 $this->info->tempuser = $this->getContents();
5067 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->userid = $this->getContents();
5068 break;
5069 case "HIDDEN":
5070 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->hidden = $this->getContents();
5071 break;
5072 case "TIMESTART":
5073 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timestart = $this->getContents();
5074 break;
5075 case "TIMEEND":
5076 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timeend = $this->getContents();
5077 break;
5078 case "TIMEMODIFIED":
5079 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->timemodified = $this->getContents();
5080 break;
5081 case "MODIFIERID":
5082 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->modifierid = $this->getContents();
5083 break;
5084 case "ENROL":
5085 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->enrol = $this->getContents();
5086 break;
5087 case "SORTORDER":
5088 $this->info->tempsection->mods[$this->info->tempmod->id]->roleassignments[$this->info->tempid]->assignments[$this->info->tempuser]->sortorder = $this->getContents();
5089 break;
5093 } /// ends role_assignments
5095 if (isset($this->tree[7]) && $this->tree[7] == "ROLES_OVERRIDES") {
5096 if ($this->level == 9) {
5097 switch ($tagName) {
5098 case "NAME":
5099 $this->info->tempname = $this->getContents();
5100 break;
5101 case "SHORTNAME":
5102 $this->info->tempshortname = $this->getContents();
5103 break;
5104 case "ID":
5105 $this->info->tempid = $this->getContents(); // temp roleid
5106 break;
5110 if ($this->level == 11) {
5111 switch ($tagName) {
5112 case "NAME":
5114 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5115 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5116 $this->info->tempname = $this->getContents(); // change to name of capability
5117 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5118 break;
5119 case "PERMISSION":
5120 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5121 break;
5122 case "TIMEMODIFIED":
5123 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5124 break;
5125 case "MODIFIERID":
5126 $this->info->tempsection->mods[$this->info->tempmod->id]->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5127 break;
5130 } /// ends role_overrides
5134 //Stop parsing if todo = SECTIONS and tagName = SECTIONS (en of the tag, of course)
5135 //Speed up a lot (avoid parse all)
5136 if ($tagName == "SECTIONS") {
5137 $this->finished = true;
5140 //Clear things
5141 $this->tree[$this->level] = "";
5142 $this->level--;
5143 $this->content = "";
5147 //This is the endTag handler we use where we are reading the optional format data zone (todo="FORMATDATA")
5148 function endElementFormatData($parser, $tagName) {
5149 //Check if we are into FORMATDATA zone
5150 if ($this->tree[3] == 'FORMATDATA') {
5151 if (!isset($this->temp)) {
5152 $this->temp = '';
5154 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5157 if($tagName=='FORMATDATA') {
5158 //Did we have any data? If not don't bother
5159 if($this->temp!='<FORMATDATA></FORMATDATA>') {
5160 //Prepend XML standard header to info gathered
5161 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5162 $this->temp='';
5164 //Call to xmlize for this portion of xml data (the FORMATDATA block)
5165 $this->info->format_data = xmlize($xml_data,0);
5167 //Stop parsing at end of FORMATDATA
5168 $this->finished=true;
5171 //Clear things
5172 $this->tree[$this->level] = "";
5173 $this->level--;
5174 $this->content = "";
5177 //This is the endTag handler we use where we are reading the metacourse zone (todo="METACOURSE")
5178 function endElementMetacourse($parser, $tagName) {
5179 //Check if we are into METACOURSE zone
5180 if ($this->tree[3] == 'METACOURSE') {
5181 //if (trim($this->content)) //Debug
5182 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5183 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5184 //Dependig of different combinations, do different things
5185 if ($this->level == 5) {
5186 switch ($tagName) {
5187 case 'CHILD':
5188 //We've finalized a child, get it
5189 $this->info->childs[] = $this->info->tempmeta;
5190 unset($this->info->tempmeta);
5191 break;
5192 case 'PARENT':
5193 //We've finalized a parent, get it
5194 $this->info->parents[] = $this->info->tempmeta;
5195 unset($this->info->tempmeta);
5196 break;
5197 default:
5198 die($tagName);
5201 if ($this->level == 6) {
5202 switch ($tagName) {
5203 case 'ID':
5204 $this->info->tempmeta->id = $this->getContents();
5205 break;
5206 case 'IDNUMBER':
5207 $this->info->tempmeta->idnumber = $this->getContents();
5208 break;
5209 case 'SHORTNAME':
5210 $this->info->tempmeta->shortname = $this->getContents();
5211 break;
5216 //Stop parsing if todo = METACOURSE and tagName = METACOURSE (en of the tag, of course)
5217 //Speed up a lot (avoid parse all)
5218 if ($this->tree[3] == 'METACOURSE' && $tagName == 'METACOURSE') {
5219 $this->finished = true;
5222 //Clear things
5223 $this->tree[$this->level] = '';
5224 $this->level--;
5225 $this->content = "";
5228 //This is the endTag handler we use where we are reading the gradebook zone (todo="GRADEBOOK")
5229 function endElementGradebook($parser, $tagName) {
5230 //Check if we are into GRADEBOOK zone
5231 if ($this->tree[3] == "GRADEBOOK") {
5232 //if (trim($this->content)) //Debug
5233 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5234 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
5235 //Acumulate data to info (content + close tag)
5236 //Reconvert: strip htmlchars again and trim to generate xml data
5237 if (!isset($this->temp)) {
5238 $this->temp = "";
5240 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5241 // We have finished outcome, grade_category or grade_item, reset accumulated
5242 // data because they are close tags
5243 if ($this->level == 4) {
5244 $this->temp = "";
5246 //If we've finished a grade item, xmlize it an save to db
5247 if (($this->level == 5) and ($tagName == "GRADE_ITEM")) {
5248 //Prepend XML standard header to info gathered
5249 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5250 //Call to xmlize for this portion of xml data (one PREFERENCE)
5251 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5252 $data = xmlize($xml_data,0);
5253 //echo strftime ("%X",time())."<p>"; //Debug
5254 //traverse_xmlize($data); //Debug
5255 //print_object ($GLOBALS['traverse_array']); //Debug
5256 //$GLOBALS['traverse_array']=""; //Debug
5257 //Now, save data to db. We'll use it later
5258 //Get id and status from data
5259 $item_id = $data["GRADE_ITEM"]["#"]["ID"]["0"]["#"];
5260 $this->counter++;
5261 //Save to db
5263 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items', $item_id,
5264 null,$data);
5265 //Create returning info
5266 $this->info = $this->counter;
5267 //Reset temp
5269 unset($this->temp);
5272 //If we've finished a grade_category, xmlize it an save to db
5273 if (($this->level == 5) and ($tagName == "GRADE_CATEGORY")) {
5274 //Prepend XML standard header to info gathered
5275 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5276 //Call to xmlize for this portion of xml data (one CATECORY)
5277 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5278 $data = xmlize($xml_data,0);
5279 //echo strftime ("%X",time())."<p>"; //Debug
5280 //traverse_xmlize($data); //Debug
5281 //print_object ($GLOBALS['traverse_array']); //Debug
5282 //$GLOBALS['traverse_array']=""; //Debug
5283 //Now, save data to db. We'll use it later
5284 //Get id and status from data
5285 $category_id = $data["GRADE_CATEGORY"]["#"]["ID"]["0"]["#"];
5286 $this->counter++;
5287 //Save to db
5288 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories' ,$category_id,
5289 null,$data);
5290 //Create returning info
5291 $this->info = $this->counter;
5292 //Reset temp
5293 unset($this->temp);
5296 //If we've finished a grade_outcome, xmlize it an save to db
5297 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME")) {
5298 //Prepend XML standard header to info gathered
5299 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5300 //Call to xmlize for this portion of xml data (one CATECORY)
5301 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5302 $data = xmlize($xml_data,0);
5303 //echo strftime ("%X",time())."<p>"; //Debug
5304 //traverse_xmlize($data); //Debug
5305 //print_object ($GLOBALS['traverse_array']); //Debug
5306 //$GLOBALS['traverse_array']=""; //Debug
5307 //Now, save data to db. We'll use it later
5308 //Get id and status from data
5309 $outcome_id = $data["GRADE_OUTCOME"]["#"]["ID"]["0"]["#"];
5310 $this->counter++;
5311 //Save to db
5312 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes' ,$outcome_id,
5313 null,$data);
5314 //Create returning info
5315 $this->info = $this->counter;
5316 //Reset temp
5317 unset($this->temp);
5320 //If we've finished a grade_outcomes_course, xmlize it an save to db
5321 if (($this->level == 5) and ($tagName == "GRADE_OUTCOMES_COURSE")) {
5322 //Prepend XML standard header to info gathered
5323 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5324 //Call to xmlize for this portion of xml data (one CATECORY)
5325 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5326 $data = xmlize($xml_data,0);
5327 //echo strftime ("%X",time())."<p>"; //Debug
5328 //traverse_xmlize($data); //Debug
5329 //print_object ($GLOBALS['traverse_array']); //Debug
5330 //$GLOBALS['traverse_array']=""; //Debug
5331 //Now, save data to db. We'll use it later
5332 //Get id and status from data
5333 $outcomes_course_id = $data["GRADE_OUTCOMES_COURSE"]["#"]["ID"]["0"]["#"];
5334 $this->counter++;
5335 //Save to db
5336 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_courses' ,$outcomes_course_id,
5337 null,$data);
5338 //Create returning info
5339 $this->info = $this->counter;
5340 //Reset temp
5341 unset($this->temp);
5344 if (($this->level == 5) and ($tagName == "GRADE_CATEGORIES_HISTORY")) {
5345 //Prepend XML standard header to info gathered
5346 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5347 //Call to xmlize for this portion of xml data (one PREFERENCE)
5348 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5349 $data = xmlize($xml_data,0);
5350 //echo strftime ("%X",time())."<p>"; //Debug
5351 //traverse_xmlize($data); //Debug
5352 //print_object ($GLOBALS['traverse_array']); //Debug
5353 //$GLOBALS['traverse_array']=""; //Debug
5354 //Now, save data to db. We'll use it later
5355 //Get id and status from data
5356 $id = $data["GRADE_CATEGORIES_HISTORY"]["#"]["ID"]["0"]["#"];
5357 $this->counter++;
5358 //Save to db
5360 $status = backup_putid($this->preferences->backup_unique_code, 'grade_categories_history', $id,
5361 null,$data);
5362 //Create returning info
5363 $this->info = $this->counter;
5364 //Reset temp
5366 unset($this->temp);
5369 if (($this->level == 5) and ($tagName == "GRADE_GRADES_HISTORY")) {
5370 //Prepend XML standard header to info gathered
5371 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5372 //Call to xmlize for this portion of xml data (one PREFERENCE)
5373 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5374 $data = xmlize($xml_data,0);
5375 //echo strftime ("%X",time())."<p>"; //Debug
5376 //traverse_xmlize($data); //Debug
5377 //print_object ($GLOBALS['traverse_array']); //Debug
5378 //$GLOBALS['traverse_array']=""; //Debug
5379 //Now, save data to db. We'll use it later
5380 //Get id and status from data
5381 $id = $data["GRADE_GRADES_HISTORY"]["#"]["ID"]["0"]["#"];
5382 $this->counter++;
5383 //Save to db
5385 $status = backup_putid($this->preferences->backup_unique_code, 'grade_grades_history', $id,
5386 null,$data);
5387 //Create returning info
5388 $this->info = $this->counter;
5389 //Reset temp
5391 unset($this->temp);
5394 if (($this->level == 5) and ($tagName == "GRADE_TEXT_HISTORY")) {
5395 //Prepend XML standard header to info gathered
5396 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5397 //Call to xmlize for this portion of xml data (one PREFERENCE)
5398 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5399 $data = xmlize($xml_data,0);
5400 //echo strftime ("%X",time())."<p>"; //Debug
5401 //traverse_xmlize($data); //Debug
5402 //print_object ($GLOBALS['traverse_array']); //Debug
5403 //$GLOBALS['traverse_array']=""; //Debug
5404 //Now, save data to db. We'll use it later
5405 //Get id and status from data
5406 $id = $data["GRADE_TEXT_HISTORY"]["#"]["ID"]["0"]["#"];
5407 $this->counter++;
5408 //Save to db
5409 $status = backup_putid($this->preferences->backup_unique_code, 'grade_grades_text_history', $id,
5410 null,$data);
5411 //Create returning info
5412 $this->info = $this->counter;
5413 //Reset temp
5415 unset($this->temp);
5418 if (($this->level == 5) and ($tagName == "GRADE_ITEM_HISTORY")) {
5419 //Prepend XML standard header to info gathered
5420 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5421 //Call to xmlize for this portion of xml data (one PREFERENCE)
5422 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5423 $data = xmlize($xml_data,0);
5424 //echo strftime ("%X",time())."<p>"; //Debug
5425 //traverse_xmlize($data); //Debug
5426 //print_object ($GLOBALS['traverse_array']); //Debug
5427 //$GLOBALS['traverse_array']=""; //Debug
5428 //Now, save data to db. We'll use it later
5429 //Get id and status from data
5430 $id = $data["GRADE_ITEM_HISTORY"]["#"]["ID"]["0"]["#"];
5431 $this->counter++;
5432 //Save to db
5434 $status = backup_putid($this->preferences->backup_unique_code, 'grade_items_history', $id,
5435 null,$data);
5436 //Create returning info
5437 $this->info = $this->counter;
5438 //Reset temp
5440 unset($this->temp);
5443 if (($this->level == 5) and ($tagName == "GRADE_OUTCOME_HISTORY")) {
5444 //Prepend XML standard header to info gathered
5445 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5446 //Call to xmlize for this portion of xml data (one PREFERENCE)
5447 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5448 $data = xmlize($xml_data,0);
5449 //echo strftime ("%X",time())."<p>"; //Debug
5450 //traverse_xmlize($data); //Debug
5451 //print_object ($GLOBALS['traverse_array']); //Debug
5452 //$GLOBALS['traverse_array']=""; //Debug
5453 //Now, save data to db. We'll use it later
5454 //Get id and status from data
5455 $id = $data["GRADE_OUTCOME_HISTORY"]["#"]["ID"]["0"]["#"];
5456 $this->counter++;
5457 //Save to db
5459 $status = backup_putid($this->preferences->backup_unique_code, 'grade_outcomes_history', $id,
5460 null,$data);
5461 //Create returning info
5462 $this->info = $this->counter;
5463 //Reset temp
5465 unset($this->temp);
5469 //Stop parsing if todo = GRADEBOOK and tagName = GRADEBOOK (en of the tag, of course)
5470 //Speed up a lot (avoid parse all)
5471 if ($tagName == "GRADEBOOK" and $this->level == 3) {
5472 $this->finished = true;
5473 $this->counter = 0;
5476 //Clear things
5477 $this->tree[$this->level] = "";
5478 $this->level--;
5479 $this->content = "";
5483 //This is the endTag handler we use where we are reading the users zone (todo="USERS")
5484 function endElementUsers($parser, $tagName) {
5485 global $CFG;
5486 //Check if we are into USERS zone
5487 if ($this->tree[3] == "USERS") {
5488 //if (trim($this->content)) //Debug
5489 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5490 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5491 //Dependig of different combinations, do different things
5492 if ($this->level == 4) {
5493 switch ($tagName) {
5494 case "USER":
5495 //Increment counter
5496 $this->counter++;
5497 //Save to db, only save if record not already exist
5498 // if there already is an new_id for this entry, just use that new_id?
5499 $newuser = backup_getid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id);
5500 if (isset($newuser->new_id)) {
5501 $newid = $newuser->new_id;
5502 } else {
5503 $newid = null;
5506 backup_putid($this->preferences->backup_unique_code,"user",$this->info->tempuser->id,
5507 $newid,$this->info->tempuser);
5509 //Do some output
5510 if ($this->counter % 10 == 0) {
5511 if (!defined('RESTORE_SILENTLY')) {
5512 echo ".";
5513 if ($this->counter % 200 == 0) {
5514 echo "<br />";
5517 backup_flush(300);
5520 //Delete temp obejct
5521 unset($this->info->tempuser);
5522 break;
5525 if ($this->level == 5) {
5526 switch ($tagName) {
5527 case "ID":
5528 $this->info->users[$this->getContents()] = $this->getContents();
5529 $this->info->tempuser->id = $this->getContents();
5530 break;
5531 case "AUTH":
5532 $this->info->tempuser->auth = $this->getContents();
5533 break;
5534 case "CONFIRMED":
5535 $this->info->tempuser->confirmed = $this->getContents();
5536 break;
5537 case "POLICYAGREED":
5538 $this->info->tempuser->policyagreed = $this->getContents();
5539 break;
5540 case "DELETED":
5541 $this->info->tempuser->deleted = $this->getContents();
5542 break;
5543 case "USERNAME":
5544 $this->info->tempuser->username = $this->getContents();
5545 break;
5546 case "PASSWORD":
5547 $this->info->tempuser->password = $this->getContents();
5548 break;
5549 case "IDNUMBER":
5550 $this->info->tempuser->idnumber = $this->getContents();
5551 break;
5552 case "FIRSTNAME":
5553 $this->info->tempuser->firstname = $this->getContents();
5554 break;
5555 case "LASTNAME":
5556 $this->info->tempuser->lastname = $this->getContents();
5557 break;
5558 case "EMAIL":
5559 $this->info->tempuser->email = $this->getContents();
5560 break;
5561 case "EMAILSTOP":
5562 $this->info->tempuser->emailstop = $this->getContents();
5563 break;
5564 case "ICQ":
5565 $this->info->tempuser->icq = $this->getContents();
5566 break;
5567 case "SKYPE":
5568 $this->info->tempuser->skype = $this->getContents();
5569 break;
5570 case "AIM":
5571 $this->info->tempuser->aim = $this->getContents();
5572 break;
5573 case "YAHOO":
5574 $this->info->tempuser->yahoo = $this->getContents();
5575 break;
5576 case "MSN":
5577 $this->info->tempuser->msn = $this->getContents();
5578 break;
5579 case "PHONE1":
5580 $this->info->tempuser->phone1 = $this->getContents();
5581 break;
5582 case "PHONE2":
5583 $this->info->tempuser->phone2 = $this->getContents();
5584 break;
5585 case "INSTITUTION":
5586 $this->info->tempuser->institution = $this->getContents();
5587 break;
5588 case "DEPARTMENT":
5589 $this->info->tempuser->department = $this->getContents();
5590 break;
5591 case "ADDRESS":
5592 $this->info->tempuser->address = $this->getContents();
5593 break;
5594 case "CITY":
5595 $this->info->tempuser->city = $this->getContents();
5596 break;
5597 case "COUNTRY":
5598 $this->info->tempuser->country = $this->getContents();
5599 break;
5600 case "LANG":
5601 $this->info->tempuser->lang = $this->getContents();
5602 break;
5603 case "THEME":
5604 $this->info->tempuser->theme = $this->getContents();
5605 break;
5606 case "TIMEZONE":
5607 $this->info->tempuser->timezone = $this->getContents();
5608 break;
5609 case "FIRSTACCESS":
5610 $this->info->tempuser->firstaccess = $this->getContents();
5611 break;
5612 case "LASTACCESS":
5613 $this->info->tempuser->lastaccess = $this->getContents();
5614 break;
5615 case "LASTLOGIN":
5616 $this->info->tempuser->lastlogin = $this->getContents();
5617 break;
5618 case "CURRENTLOGIN":
5619 $this->info->tempuser->currentlogin = $this->getContents();
5620 break;
5621 case "LASTIP":
5622 $this->info->tempuser->lastip = $this->getContents();
5623 break;
5624 case "SECRET":
5625 $this->info->tempuser->secret = $this->getContents();
5626 break;
5627 case "PICTURE":
5628 $this->info->tempuser->picture = $this->getContents();
5629 break;
5630 case "URL":
5631 $this->info->tempuser->url = $this->getContents();
5632 break;
5633 case "DESCRIPTION":
5634 $this->info->tempuser->description = $this->getContents();
5635 break;
5636 case "MAILFORMAT":
5637 $this->info->tempuser->mailformat = $this->getContents();
5638 break;
5639 case "MAILDIGEST":
5640 $this->info->tempuser->maildigest = $this->getContents();
5641 break;
5642 case "MAILDISPLAY":
5643 $this->info->tempuser->maildisplay = $this->getContents();
5644 break;
5645 case "HTMLEDITOR":
5646 $this->info->tempuser->htmleditor = $this->getContents();
5647 break;
5648 case "AJAX":
5649 $this->info->tempuser->ajax = $this->getContents();
5650 break;
5651 case "AUTOSUBSCRIBE":
5652 $this->info->tempuser->autosubscribe = $this->getContents();
5653 break;
5654 case "TRACKFORUMS":
5655 $this->info->tempuser->trackforums = $this->getContents();
5656 break;
5657 case "MNETHOSTURL":
5658 $this->info->tempuser->mnethosturl = $this->getContents();
5659 break;
5660 case "TIMEMODIFIED":
5661 $this->info->tempuser->timemodified = $this->getContents();
5662 break;
5663 default:
5664 break;
5667 if ($this->level == 6 && $this->tree[5]!="ROLES_ASSIGNMENTS" && $this->tree[5]!="ROLES_OVERRIDES") {
5668 switch ($tagName) {
5669 case "ROLE":
5670 //We've finalized a role, get it
5671 $this->info->tempuser->roles[$this->info->temprole->type] = $this->info->temprole;
5672 unset($this->info->temprole);
5673 break;
5674 case "USER_PREFERENCE":
5675 //We've finalized a user_preference, get it
5676 $this->info->tempuser->user_preferences[$this->info->tempuserpreference->name] = $this->info->tempuserpreference;
5677 unset($this->info->tempuserpreference);
5678 break;
5682 if ($this->level == 7) {
5683 switch ($tagName) {
5684 case "TYPE":
5685 $this->info->temprole->type = $this->getContents();
5686 break;
5687 case "AUTHORITY":
5688 $this->info->temprole->authority = $this->getContents();
5689 break;
5690 case "TEA_ROLE":
5691 $this->info->temprole->tea_role = $this->getContents();
5692 break;
5693 case "EDITALL":
5694 $this->info->temprole->editall = $this->getContents();
5695 break;
5696 case "TIMESTART":
5697 $this->info->temprole->timestart = $this->getContents();
5698 break;
5699 case "TIMEEND":
5700 $this->info->temprole->timeend = $this->getContents();
5701 break;
5702 case "TIMEMODIFIED":
5703 $this->info->temprole->timemodified = $this->getContents();
5704 break;
5705 case "TIMESTART":
5706 $this->info->temprole->timestart = $this->getContents();
5707 break;
5708 case "TIMEEND":
5709 $this->info->temprole->timeend = $this->getContents();
5710 break;
5711 case "TIME":
5712 $this->info->temprole->time = $this->getContents();
5713 break;
5714 case "TIMEACCESS":
5715 $this->info->temprole->timeaccess = $this->getContents();
5716 break;
5717 case "ENROL":
5718 $this->info->temprole->enrol = $this->getContents();
5719 break;
5720 case "NAME":
5721 $this->info->tempuserpreference->name = $this->getContents();
5722 break;
5723 case "VALUE":
5724 $this->info->tempuserpreference->value = $this->getContents();
5725 break;
5726 default:
5727 break;
5732 if ($this->tree[5] == "ROLES_ASSIGNMENTS") {
5734 if ($this->level == 7) {
5735 switch ($tagName) {
5736 case "NAME":
5737 $this->info->tempname = $this->getContents();
5738 break;
5739 case "SHORTNAME":
5740 $this->info->tempshortname = $this->getContents();
5741 break;
5742 case "ID":
5743 $this->info->tempid = $this->getContents(); // temp roleid
5744 break;
5748 if ($this->level == 9) {
5750 switch ($tagName) {
5751 case "USERID":
5752 $this->info->tempuser->roleassignments[$this->info->tempid]->name = $this->info->tempname;
5754 $this->info->tempuser->roleassignments[$this->info->tempid]->shortname = $this->info->tempshortname;
5756 $this->info->tempuserid = $this->getContents();
5758 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->userid = $this->getContents();
5759 break;
5760 case "HIDDEN":
5761 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->hidden = $this->getContents();
5762 break;
5763 case "TIMESTART":
5764 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timestart = $this->getContents();
5765 break;
5766 case "TIMEEND":
5767 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timeend = $this->getContents();
5768 break;
5769 case "TIMEMODIFIED":
5770 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->timemodified = $this->getContents();
5771 break;
5772 case "MODIFIERID":
5773 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->modifierid = $this->getContents();
5774 break;
5775 case "ENROL":
5776 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->enrol = $this->getContents();
5777 break;
5778 case "SORTORDER":
5779 $this->info->tempuser->roleassignments[$this->info->tempid]->assignments[$this->info->tempuserid]->sortorder = $this->getContents();
5780 break;
5784 } /// ends role_assignments
5786 if ($this->tree[5] == "ROLES_OVERRIDES") {
5787 if ($this->level == 7) {
5788 switch ($tagName) {
5789 case "NAME":
5790 $this->info->tempname = $this->getContents();
5791 break;
5792 case "SHORTNAME":
5793 $this->info->tempshortname = $this->getContents();
5794 break;
5795 case "ID":
5796 $this->info->tempid = $this->getContents(); // temp roleid
5797 break;
5801 if ($this->level == 9) {
5802 switch ($tagName) {
5803 case "NAME":
5805 $this->info->tempuser->roleoverrides[$this->info->tempid]->name = $this->info->tempname;
5806 $this->info->tempuser->roleoverrides[$this->info->tempid]->shortname = $this->info->tempshortname;
5807 $this->info->tempname = $this->getContents(); // change to name of capability
5808 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->name = $this->getContents();
5809 break;
5810 case "PERMISSION":
5811 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->permission = $this->getContents();
5812 break;
5813 case "TIMEMODIFIED":
5814 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->timemodified = $this->getContents();
5815 break;
5816 case "MODIFIERID":
5817 $this->info->tempuser->roleoverrides[$this->info->tempid]->overrides[$this->info->tempname]->modifierid = $this->getContents();
5818 break;
5821 } /// ends role_overrides
5823 } // closes if this->tree[3]=="users"
5825 //Stop parsing if todo = USERS and tagName = USERS (en of the tag, of course)
5826 //Speed up a lot (avoid parse all)
5827 if ($tagName == "USERS" and $this->level == 3) {
5828 $this->finished = true;
5829 $this->counter = 0;
5832 //Clear things
5833 $this->tree[$this->level] = "";
5834 $this->level--;
5835 $this->content = "";
5839 //This is the endTag handler we use where we are reading the messages zone (todo="MESSAGES")
5840 function endElementMessages($parser, $tagName) {
5841 //Check if we are into MESSAGES zone
5842 if ($this->tree[3] == "MESSAGES") {
5843 //if (trim($this->content)) //Debug
5844 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5845 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n";//Debug
5846 //Acumulate data to info (content + close tag)
5847 //Reconvert: strip htmlchars again and trim to generate xml data
5848 if (!isset($this->temp)) {
5849 $this->temp = "";
5851 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5852 //If we've finished a message, xmlize it an save to db
5853 if (($this->level == 4) and ($tagName == "MESSAGE")) {
5854 //Prepend XML standard header to info gathered
5855 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5856 //Call to xmlize for this portion of xml data (one MESSAGE)
5857 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5858 $data = xmlize($xml_data,0);
5859 //echo strftime ("%X",time())."<p>"; //Debug
5860 //traverse_xmlize($data); //Debug
5861 //print_object ($GLOBALS['traverse_array']); //Debug
5862 //$GLOBALS['traverse_array']=""; //Debug
5863 //Now, save data to db. We'll use it later
5864 //Get id and status from data
5865 $message_id = $data["MESSAGE"]["#"]["ID"]["0"]["#"];
5866 $message_status = $data["MESSAGE"]["#"]["STATUS"]["0"]["#"];
5867 if ($message_status == "READ") {
5868 $table = "message_read";
5869 } else {
5870 $table = "message";
5872 $this->counter++;
5873 //Save to db
5874 $status = backup_putid($this->preferences->backup_unique_code, $table,$message_id,
5875 null,$data);
5876 //Create returning info
5877 $this->info = $this->counter;
5878 //Reset temp
5879 unset($this->temp);
5881 //If we've finished a contact, xmlize it an save to db
5882 if (($this->level == 5) and ($tagName == "CONTACT")) {
5883 //Prepend XML standard header to info gathered
5884 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5885 //Call to xmlize for this portion of xml data (one MESSAGE)
5886 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5887 $data = xmlize($xml_data,0);
5888 //echo strftime ("%X",time())."<p>"; //Debug
5889 //traverse_xmlize($data); //Debug
5890 //print_object ($GLOBALS['traverse_array']); //Debug
5891 //$GLOBALS['traverse_array']=""; //Debug
5892 //Now, save data to db. We'll use it later
5893 //Get id and status from data
5894 $contact_id = $data["CONTACT"]["#"]["ID"]["0"]["#"];
5895 $this->counter++;
5896 //Save to db
5897 $status = backup_putid($this->preferences->backup_unique_code, 'message_contacts' ,$contact_id,
5898 null,$data);
5899 //Create returning info
5900 $this->info = $this->counter;
5901 //Reset temp
5902 unset($this->temp);
5906 //Stop parsing if todo = MESSAGES and tagName = MESSAGES (en of the tag, of course)
5907 //Speed up a lot (avoid parse all)
5908 if ($tagName == "MESSAGES" and $this->level == 3) {
5909 $this->finished = true;
5910 $this->counter = 0;
5913 //Clear things
5914 $this->tree[$this->level] = "";
5915 $this->level--;
5916 $this->content = "";
5920 //This is the endTag handler we use where we are reading the questions zone (todo="QUESTIONS")
5921 function endElementQuestions($parser, $tagName) {
5922 //Check if we are into QUESTION_CATEGORIES zone
5923 if ($this->tree[3] == "QUESTION_CATEGORIES") {
5924 //if (trim($this->content)) //Debug
5925 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5926 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5927 //Acumulate data to info (content + close tag)
5928 //Reconvert: strip htmlchars again and trim to generate xml data
5929 if (!isset($this->temp)) {
5930 $this->temp = "";
5932 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5933 //If we've finished a mod, xmlize it an save to db
5934 if (($this->level == 4) and ($tagName == "QUESTION_CATEGORY")) {
5935 //Prepend XML standard header to info gathered
5936 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5937 //Call to xmlize for this portion of xml data (one QUESTION_CATEGORY)
5938 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5939 $data = xmlize($xml_data,0);
5940 //echo strftime ("%X",time())."<p>"; //Debug
5941 //traverse_xmlize($data); //Debug
5942 //print_object ($GLOBALS['traverse_array']); //Debug
5943 //$GLOBALS['traverse_array']=""; //Debug
5944 //Now, save data to db. We'll use it later
5945 //Get id from data
5946 $category_id = $data["QUESTION_CATEGORY"]["#"]["ID"]["0"]["#"];
5947 //Save to db
5948 $status = backup_putid($this->preferences->backup_unique_code,"question_categories",$category_id,
5949 null,$data);
5950 //Create returning info
5951 $ret_info = new object();
5952 $ret_info->id = $category_id;
5953 $this->info[] = $ret_info;
5954 //Reset temp
5955 unset($this->temp);
5959 //Stop parsing if todo = QUESTION_CATEGORIES and tagName = QUESTION_CATEGORY (en of the tag, of course)
5960 //Speed up a lot (avoid parse all)
5961 if ($tagName == "QUESTION_CATEGORIES" and $this->level == 3) {
5962 $this->finished = true;
5965 //Clear things
5966 $this->tree[$this->level] = "";
5967 $this->level--;
5968 $this->content = "";
5972 //This is the endTag handler we use where we are reading the scales zone (todo="SCALES")
5973 function endElementScales($parser, $tagName) {
5974 //Check if we are into SCALES zone
5975 if ($this->tree[3] == "SCALES") {
5976 //if (trim($this->content)) //Debug
5977 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
5978 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
5979 //Acumulate data to info (content + close tag)
5980 //Reconvert: strip htmlchars again and trim to generate xml data
5981 if (!isset($this->temp)) {
5982 $this->temp = "";
5984 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
5985 //If we've finished a scale, xmlize it an save to db
5986 if (($this->level == 4) and ($tagName == "SCALE")) {
5987 //Prepend XML standard header to info gathered
5988 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
5989 //Call to xmlize for this portion of xml data (one SCALE)
5990 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
5991 $data = xmlize($xml_data,0);
5992 //echo strftime ("%X",time())."<p>"; //Debug
5993 //traverse_xmlize($data); //Debug
5994 //print_object ($GLOBALS['traverse_array']); //Debug
5995 //$GLOBALS['traverse_array']=""; //Debug
5996 //Now, save data to db. We'll use it later
5997 //Get id and from data
5998 $scale_id = $data["SCALE"]["#"]["ID"]["0"]["#"];
5999 //Save to db
6000 $status = backup_putid($this->preferences->backup_unique_code,"scale",$scale_id,
6001 null,$data);
6002 //Create returning info
6003 $ret_info = new object();
6004 $ret_info->id = $scale_id;
6005 $this->info[] = $ret_info;
6006 //Reset temp
6007 unset($this->temp);
6011 //Stop parsing if todo = SCALES and tagName = SCALE (en of the tag, of course)
6012 //Speed up a lot (avoid parse all)
6013 if ($tagName == "SCALES" and $this->level == 3) {
6014 $this->finished = true;
6017 //Clear things
6018 $this->tree[$this->level] = "";
6019 $this->level--;
6020 $this->content = "";
6024 //This is the endTag handler we use where we are reading the groups zone (todo="GROUPS")
6025 function endElementGroups($parser, $tagName) {
6026 //Check if we are into GROUPS zone
6027 if ($this->tree[3] == "GROUPS") {
6028 //if (trim($this->content)) //Debug
6029 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6030 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6031 //Acumulate data to info (content + close tag)
6032 //Reconvert: strip htmlchars again and trim to generate xml data
6033 if (!isset($this->temp)) {
6034 $this->temp = "";
6036 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6037 //If we've finished a group, xmlize it an save to db
6038 if (($this->level == 4) and ($tagName == "GROUP")) {
6039 //Prepend XML standard header to info gathered
6040 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6041 //Call to xmlize for this portion of xml data (one GROUP)
6042 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6043 $data = xmlize($xml_data,0);
6044 //echo strftime ("%X",time())."<p>"; //Debug
6045 //traverse_xmlize($data); //Debug
6046 //print_object ($GLOBALS['traverse_array']); //Debug
6047 //$GLOBALS['traverse_array']=""; //Debug
6048 //Now, save data to db. We'll use it later
6049 //Get id and from data
6050 $group_id = $data["GROUP"]["#"]["ID"]["0"]["#"];
6051 //Save to db
6052 $status = backup_putid($this->preferences->backup_unique_code,"groups",$group_id,
6053 null,$data);
6054 //Create returning info
6055 $ret_info = new Object();
6056 $ret_info->id = $group_id;
6057 $this->info[] = $ret_info;
6058 //Reset temp
6059 unset($this->temp);
6063 //Stop parsing if todo = GROUPS and tagName = GROUP (en of the tag, of course)
6064 //Speed up a lot (avoid parse all)
6065 if ($tagName == "GROUPS" and $this->level == 3) {
6066 $this->finished = true;
6069 //Clear things
6070 $this->tree[$this->level] = "";
6071 $this->level--;
6072 $this->content = "";
6076 //This is the endTag handler we use where we are reading the groupings zone (todo="GROUPINGS")
6077 function endElementGroupings($parser, $tagName) {
6078 //Check if we are into GROUPINGS zone
6079 if ($this->tree[3] == "GROUPINGS") {
6080 //Acumulate data to info (content + close tag)
6081 //Reconvert: strip htmlchars again and trim to generate xml data
6082 if (!isset($this->temp)) {
6083 $this->temp = "";
6085 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6086 //If we've finished a group, xmlize it an save to db
6087 if (($this->level == 4) and ($tagName == "GROUPING")) {
6088 //Prepend XML standard header to info gathered
6089 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6090 //Call to xmlize for this portion of xml data (one GROUPING)
6091 $data = xmlize($xml_data,0);
6092 //Now, save data to db. We'll use it later
6093 //Get id and from data
6094 $grouping_id = $data["GROUPING"]["#"]["ID"]["0"]["#"];
6095 //Save to db
6096 $status = backup_putid($this->preferences->backup_unique_code,"groupings",$grouping_id,
6097 null,$data);
6098 //Create returning info
6099 $ret_info = new Object();
6100 $ret_info->id = $grouping_id;
6101 $this->info[] = $ret_info;
6102 //Reset temp
6103 unset($this->temp);
6107 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6108 //Speed up a lot (avoid parse all)
6109 if ($tagName == "GROUPINGS" and $this->level == 3) {
6110 $this->finished = true;
6113 //Clear things
6114 $this->tree[$this->level] = "";
6115 $this->level--;
6116 $this->content = "";
6120 //This is the endTag handler we use where we are reading the groupingsgroups zone (todo="GROUPINGGROUPS")
6121 function endElementGroupingsGroups($parser, $tagName) {
6122 //Check if we are into GROUPINGSGROUPS zone
6123 if ($this->tree[3] == "GROUPINGSGROUPS") {
6124 //Acumulate data to info (content + close tag)
6125 //Reconvert: strip htmlchars again and trim to generate xml data
6126 if (!isset($this->temp)) {
6127 $this->temp = "";
6129 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6130 //If we've finished a group, xmlize it an save to db
6131 if (($this->level == 4) and ($tagName == "GROUPINGGROUP")) {
6132 //Prepend XML standard header to info gathered
6133 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6134 //Call to xmlize for this portion of xml data (one GROUPING)
6135 $data = xmlize($xml_data,0);
6136 //Now, save data to db. We'll use it later
6137 //Get id and from data
6138 $groupinggroup_id = $data["GROUPINGGROUP"]["#"]["ID"]["0"]["#"];
6139 //Save to db
6140 $status = backup_putid($this->preferences->backup_unique_code,"groupingsgroups",$groupinggroup_id,
6141 null,$data);
6142 //Create returning info
6143 $ret_info = new Object();
6144 $ret_info->id = $groupinggroup_id;
6145 $this->info[] = $ret_info;
6146 //Reset temp
6147 unset($this->temp);
6151 //Stop parsing if todo = GROUPINGS and tagName = GROUPING (en of the tag, of course)
6152 //Speed up a lot (avoid parse all)
6153 if ($tagName == "GROUPINGSGROUPS" and $this->level == 3) {
6154 $this->finished = true;
6157 //Clear things
6158 $this->tree[$this->level] = "";
6159 $this->level--;
6160 $this->content = "";
6164 //This is the endTag handler we use where we are reading the events zone (todo="EVENTS")
6165 function endElementEvents($parser, $tagName) {
6166 //Check if we are into EVENTS zone
6167 if ($this->tree[3] == "EVENTS") {
6168 //if (trim($this->content)) //Debug
6169 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6170 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6171 //Acumulate data to info (content + close tag)
6172 //Reconvert: strip htmlchars again and trim to generate xml data
6173 if (!isset($this->temp)) {
6174 $this->temp = "";
6176 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6177 //If we've finished a event, xmlize it an save to db
6178 if (($this->level == 4) and ($tagName == "EVENT")) {
6179 //Prepend XML standard header to info gathered
6180 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6181 //Call to xmlize for this portion of xml data (one EVENT)
6182 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6183 $data = xmlize($xml_data,0);
6184 //echo strftime ("%X",time())."<p>"; //Debug
6185 //traverse_xmlize($data); //Debug
6186 //print_object ($GLOBALS['traverse_array']); //Debug
6187 //$GLOBALS['traverse_array']=""; //Debug
6188 //Now, save data to db. We'll use it later
6189 //Get id and from data
6190 $event_id = $data["EVENT"]["#"]["ID"]["0"]["#"];
6191 //Save to db
6192 $status = backup_putid($this->preferences->backup_unique_code,"event",$event_id,
6193 null,$data);
6194 //Create returning info
6195 $ret_info = new object();
6196 $ret_info->id = $event_id;
6197 $this->info[] = $ret_info;
6198 //Reset temp
6199 unset($this->temp);
6203 //Stop parsing if todo = EVENTS and tagName = EVENT (en of the tag, of course)
6204 //Speed up a lot (avoid parse all)
6205 if ($tagName == "EVENTS" and $this->level == 3) {
6206 $this->finished = true;
6209 //Clear things
6210 $this->tree[$this->level] = "";
6211 $this->level--;
6212 $this->content = "";
6216 //This is the endTag handler we use where we are reading the modules zone (todo="MODULES")
6217 function endElementModules($parser, $tagName) {
6218 //Check if we are into MODULES zone
6219 if ($this->tree[3] == "MODULES") {
6220 //if (trim($this->content)) //Debug
6221 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6222 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6223 //Acumulate data to info (content + close tag)
6224 //Reconvert: strip htmlchars again and trim to generate xml data
6225 if (!isset($this->temp)) {
6226 $this->temp = "";
6228 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6229 //If we've finished a mod, xmlize it an save to db
6230 if (($this->level == 4) and ($tagName == "MOD")) {
6231 //Prepend XML standard header to info gathered
6232 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6233 //Call to xmlize for this portion of xml data (one MOD)
6234 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6235 $data = xmlize($xml_data,0);
6236 //echo strftime ("%X",time())."<p>"; //Debug
6237 //traverse_xmlize($data); //Debug
6238 //print_object ($GLOBALS['traverse_array']); //Debug
6239 //$GLOBALS['traverse_array']=""; //Debug
6240 //Now, save data to db. We'll use it later
6241 //Get id and modtype from data
6242 $mod_id = $data["MOD"]["#"]["ID"]["0"]["#"];
6243 $mod_type = $data["MOD"]["#"]["MODTYPE"]["0"]["#"];
6244 //Only if we've selected to restore it
6245 if (!empty($this->preferences->mods[$mod_type]->restore)) {
6246 //Save to db
6247 $status = backup_putid($this->preferences->backup_unique_code,$mod_type,$mod_id,
6248 null,$data);
6249 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6250 //Create returning info
6251 $ret_info = new object();
6252 $ret_info->id = $mod_id;
6253 $ret_info->modtype = $mod_type;
6254 $this->info[] = $ret_info;
6256 //Reset temp
6257 unset($this->temp);
6263 //Stop parsing if todo = MODULES and tagName = MODULES (en of the tag, of course)
6264 //Speed up a lot (avoid parse all)
6265 if ($tagName == "MODULES" and $this->level == 3) {
6266 $this->finished = true;
6269 //Clear things
6270 $this->tree[$this->level] = "";
6271 $this->level--;
6272 $this->content = "";
6276 //This is the endTag handler we use where we are reading the logs zone (todo="LOGS")
6277 function endElementLogs($parser, $tagName) {
6278 //Check if we are into LOGS zone
6279 if ($this->tree[3] == "LOGS") {
6280 //if (trim($this->content)) //Debug
6281 // echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6282 //echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6283 //Acumulate data to info (content + close tag)
6284 //Reconvert: strip htmlchars again and trim to generate xml data
6285 if (!isset($this->temp)) {
6286 $this->temp = "";
6288 $this->temp .= htmlspecialchars(trim($this->content))."</".$tagName.">";
6289 //If we've finished a log, xmlize it an save to db
6290 if (($this->level == 4) and ($tagName == "LOG")) {
6291 //Prepend XML standard header to info gathered
6292 $xml_data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".$this->temp;
6293 //Call to xmlize for this portion of xml data (one LOG)
6294 //echo "-XMLIZE: ".strftime ("%X",time()),"-"; //Debug
6295 $data = xmlize($xml_data,0);
6296 //echo strftime ("%X",time())."<p>"; //Debug
6297 //traverse_xmlize($data); //Debug
6298 //print_object ($GLOBALS['traverse_array']); //Debug
6299 //$GLOBALS['traverse_array']=""; //Debug
6300 //Now, save data to db. We'll use it later
6301 //Get id and modtype from data
6302 $log_id = $data["LOG"]["#"]["ID"]["0"]["#"];
6303 $log_module = $data["LOG"]["#"]["MODULE"]["0"]["#"];
6304 //We only save log entries from backup file if they are:
6305 // - Course logs
6306 // - User logs
6307 // - Module logs about one restored module
6308 if ($log_module == "course" or
6309 $log_module == "user" or
6310 $this->preferences->mods[$log_module]->restore) {
6311 //Increment counter
6312 $this->counter++;
6313 //Save to db
6314 $status = backup_putid($this->preferences->backup_unique_code,"log",$log_id,
6315 null,$data);
6316 //echo "<p>id: ".$mod_id."-".$mod_type." len.: ".strlen($sla_mod_temp)." to_db: ".$status."<p>"; //Debug
6317 //Create returning info
6318 $this->info = $this->counter;
6320 //Reset temp
6321 unset($this->temp);
6325 //Stop parsing if todo = LOGS and tagName = LOGS (en of the tag, of course)
6326 //Speed up a lot (avoid parse all)
6327 if ($tagName == "LOGS" and $this->level == 3) {
6328 $this->finished = true;
6329 $this->counter = 0;
6332 //Clear things
6333 $this->tree[$this->level] = "";
6334 $this->level--;
6335 $this->content = "";
6339 //This is the endTag default handler we use when todo is undefined
6340 function endElement($parser, $tagName) {
6341 if (trim($this->content)) //Debug
6342 echo "C".str_repeat("&nbsp;",($this->level+2)*2).$this->getContents()."<br />\n"; //Debug
6343 echo $this->level.str_repeat("&nbsp;",$this->level*2)."&lt;/".$tagName."&gt;<br />\n"; //Debug
6345 //Clear things
6346 $this->tree[$this->level] = "";
6347 $this->level--;
6348 $this->content = "";
6351 //This is the handler to read data contents (simple accumule it)
6352 function characterData($parser, $data) {
6353 $this->content .= $data;
6357 //This function executes the MoodleParser
6358 function restore_read_xml ($xml_file,$todo,$preferences) {
6360 $status = true;
6362 $xml_parser = xml_parser_create('UTF-8');
6363 $moodle_parser = new MoodleParser();
6364 $moodle_parser->todo = $todo;
6365 $moodle_parser->preferences = $preferences;
6366 xml_set_object($xml_parser,$moodle_parser);
6367 //Depending of the todo we use some element_handler or another
6368 if ($todo == "INFO") {
6369 //Define handlers to that zone
6370 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
6371 } else if ($todo == "ROLES") {
6372 // Define handlers to that zone
6373 xml_set_element_handler($xml_parser, "startElementRoles", "endElementRoles");
6374 } else if ($todo == "COURSE_HEADER") {
6375 //Define handlers to that zone
6376 xml_set_element_handler($xml_parser, "startElementCourseHeader", "endElementCourseHeader");
6377 } else if ($todo == 'BLOCKS') {
6378 //Define handlers to that zone
6379 xml_set_element_handler($xml_parser, "startElementBlocks", "endElementBlocks");
6380 } else if ($todo == "SECTIONS") {
6381 //Define handlers to that zone
6382 xml_set_element_handler($xml_parser, "startElementSections", "endElementSections");
6383 } else if ($todo == 'FORMATDATA') {
6384 //Define handlers to that zone
6385 xml_set_element_handler($xml_parser, "startElementFormatData", "endElementFormatData");
6386 } else if ($todo == "METACOURSE") {
6387 //Define handlers to that zone
6388 xml_set_element_handler($xml_parser, "startElementMetacourse", "endElementMetacourse");
6389 } else if ($todo == "GRADEBOOK") {
6390 //Define handlers to that zone
6391 xml_set_element_handler($xml_parser, "startElementGradebook", "endElementGradebook");
6392 } else if ($todo == "USERS") {
6393 //Define handlers to that zone
6394 xml_set_element_handler($xml_parser, "startElementUsers", "endElementUsers");
6395 } else if ($todo == "MESSAGES") {
6396 //Define handlers to that zone
6397 xml_set_element_handler($xml_parser, "startElementMessages", "endElementMessages");
6398 } else if ($todo == "QUESTIONS") {
6399 //Define handlers to that zone
6400 xml_set_element_handler($xml_parser, "startElementQuestions", "endElementQuestions");
6401 } else if ($todo == "SCALES") {
6402 //Define handlers to that zone
6403 xml_set_element_handler($xml_parser, "startElementScales", "endElementScales");
6404 } else if ($todo == "GROUPS") {
6405 //Define handlers to that zone
6406 xml_set_element_handler($xml_parser, "startElementGroups", "endElementGroups");
6407 } else if ($todo == "GROUPINGS") {
6408 //Define handlers to that zone
6409 xml_set_element_handler($xml_parser, "startElementGroupings", "endElementGroupings");
6410 } else if ($todo == "GROUPINGSGROUPS") {
6411 //Define handlers to that zone
6412 xml_set_element_handler($xml_parser, "startElementGroupingsGroups", "endElementGroupingsGroups");
6413 } else if ($todo == "EVENTS") {
6414 //Define handlers to that zone
6415 xml_set_element_handler($xml_parser, "startElementEvents", "endElementEvents");
6416 } else if ($todo == "MODULES") {
6417 //Define handlers to that zone
6418 xml_set_element_handler($xml_parser, "startElementModules", "endElementModules");
6419 } else if ($todo == "LOGS") {
6420 //Define handlers to that zone
6421 xml_set_element_handler($xml_parser, "startElementLogs", "endElementLogs");
6422 } else {
6423 //Define default handlers (must no be invoked when everything become finished)
6424 xml_set_element_handler($xml_parser, "startElementInfo", "endElementInfo");
6426 xml_set_character_data_handler($xml_parser, "characterData");
6427 $fp = fopen($xml_file,"r")
6428 or $status = false;
6429 if ($status) {
6430 while ($data = fread($fp, 4096) and !$moodle_parser->finished)
6431 xml_parse($xml_parser, $data, feof($fp))
6432 or die(sprintf("XML error: %s at line %d",
6433 xml_error_string(xml_get_error_code($xml_parser)),
6434 xml_get_current_line_number($xml_parser)));
6435 fclose($fp);
6437 //Get info from parser
6438 $info = $moodle_parser->info;
6440 //Clear parser mem
6441 xml_parser_free($xml_parser);
6443 if ($status && !empty($info)) {
6444 return $info;
6445 } else {
6446 return $status;
6451 * @param string $errorstr passed by reference, if silent is true,
6452 * errorstr will be populated and this function will return false rather than calling error() or notify()
6453 * @param boolean $noredirect (optional) if this is passed, this function will not print continue, or
6454 * redirect to the next step in the restore process, instead will return $backup_unique_code
6456 function restore_precheck($id,$file,&$errorstr,$noredirect=false) {
6458 global $CFG, $SESSION;
6460 //Prepend dataroot to variable to have the absolute path
6461 $file = $CFG->dataroot."/".$file;
6463 if (!defined('RESTORE_SILENTLY')) {
6464 //Start the main table
6465 echo "<table cellpadding=\"5\">";
6466 echo "<tr><td>";
6468 //Start the mail ul
6469 echo "<ul>";
6472 //Check the file exists
6473 if (!is_file($file)) {
6474 if (!defined('RESTORE_SILENTLY')) {
6475 error ("File not exists ($file)");
6476 } else {
6477 $errorstr = "File not exists ($file)";
6478 return false;
6482 //Check the file name ends with .zip
6483 if (!substr($file,-4) == ".zip") {
6484 if (!defined('RESTORE_SILENTLY')) {
6485 error ("File has an incorrect extension");
6486 } else {
6487 $errorstr = 'File has an incorrect extension';
6488 return false;
6492 //Now calculate the unique_code for this restore
6493 $backup_unique_code = time();
6495 //Now check and create the backup dir (if it doesn't exist)
6496 if (!defined('RESTORE_SILENTLY')) {
6497 echo "<li>".get_string("creatingtemporarystructures").'</li>';
6499 $status = check_and_create_backup_dir($backup_unique_code);
6500 //Empty dir
6501 if ($status) {
6502 $status = clear_backup_dir($backup_unique_code);
6505 //Now delete old data and directories under dataroot/temp/backup
6506 if ($status) {
6507 if (!defined('RESTORE_SILENTLY')) {
6508 echo "<li>".get_string("deletingolddata").'</li>';
6510 $status = backup_delete_old_data();
6513 //Now copy he zip file to dataroot/temp/backup/backup_unique_code
6514 if ($status) {
6515 if (!defined('RESTORE_SILENTLY')) {
6516 echo "<li>".get_string("copyingzipfile").'</li>';
6518 if (! $status = backup_copy_file($file,$CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
6519 if (!defined('RESTORE_SILENTLY')) {
6520 notify("Error copying backup file. Invalid name or bad perms.");
6521 } else {
6522 $errorstr = "Error copying backup file. Invalid name or bad perms";
6523 return false;
6528 //Now unzip the file
6529 if ($status) {
6530 if (!defined('RESTORE_SILENTLY')) {
6531 echo "<li>".get_string("unzippingbackup").'</li>';
6533 if (! $status = restore_unzip ($CFG->dataroot."/temp/backup/".$backup_unique_code."/".basename($file))) {
6534 if (!defined('RESTORE_SILENTLY')) {
6535 notify("Error unzipping backup file. Invalid zip file.");
6536 } else {
6537 $errorstr = "Error unzipping backup file. Invalid zip file.";
6538 return false;
6543 //Check for Blackboard backups and convert
6544 if ($status){
6545 require_once("$CFG->dirroot/backup/bb/restore_bb.php");
6546 if (!defined('RESTORE_SILENTLY')) {
6547 echo "<li>".get_string("checkingforbbexport").'</li>';
6549 $status = blackboard_convert($CFG->dataroot."/temp/backup/".$backup_unique_code);
6552 //Now check for the moodle.xml file
6553 if ($status) {
6554 $xml_file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
6555 if (!defined('RESTORE_SILENTLY')) {
6556 echo "<li>".get_string("checkingbackup").'</li>';
6558 if (! $status = restore_check_moodle_file ($xml_file)) {
6559 if (!is_file($xml_file)) {
6560 $errorstr = 'Error checking backup file. moodle.xml not found at root level of zip file.';
6561 } else {
6562 $errorstr = 'Error checking backup file. moodle.xml is incorrect or corrupted.';
6564 if (!defined('RESTORE_SILENTLY')) {
6565 notify($errorstr);
6566 } else {
6567 return false;
6572 $info = "";
6573 $course_header = "";
6575 //Now read the info tag (all)
6576 if ($status) {
6577 if (!defined('RESTORE_SILENTLY')) {
6578 echo "<li>".get_string("readinginfofrombackup").'</li>';
6580 //Reading info from file
6581 $info = restore_read_xml_info ($xml_file);
6582 //Reading course_header from file
6583 $course_header = restore_read_xml_course_header ($xml_file);
6586 if (!defined('RESTORE_SILENTLY')) {
6587 //End the main ul
6588 echo "</ul>\n";
6590 //End the main table
6591 echo "</td></tr>";
6592 echo "</table>";
6595 //We compare Moodle's versions
6596 if ($CFG->version < $info->backup_moodle_version && $status) {
6597 $message = new message();
6598 $message->serverversion = $CFG->version;
6599 $message->serverrelease = $CFG->release;
6600 $message->backupversion = $info->backup_moodle_version;
6601 $message->backuprelease = $info->backup_moodle_release;
6602 print_simple_box(get_string('noticenewerbackup','',$message), "center", "70%", '', "20", "noticebox");
6606 //Now we print in other table, the backup and the course it contains info
6607 if ($info and $course_header and $status) {
6608 //First, the course info
6609 if (!defined('RESTORE_SILENTLY')) {
6610 $status = restore_print_course_header($course_header);
6612 //Now, the backup info
6613 if ($status) {
6614 if (!defined('RESTORE_SILENTLY')) {
6615 $status = restore_print_info($info);
6620 //Save course header and info into php session
6621 if ($status) {
6622 $SESSION->info = $info;
6623 $SESSION->course_header = $course_header;
6626 //Finally, a little form to continue
6627 //with some hidden fields
6628 if ($status) {
6629 if (!defined('RESTORE_SILENTLY')) {
6630 echo "<br /><div style='text-align:center'>";
6631 $hidden["backup_unique_code"] = $backup_unique_code;
6632 $hidden["launch"] = "form";
6633 $hidden["file"] = $file;
6634 $hidden["id"] = $id;
6635 print_single_button("restore.php", $hidden, get_string("continue"),"post");
6636 echo "</div>";
6638 else {
6639 if (empty($noredirect)) {
6640 redirect($CFG->wwwroot.'/backup/restore.php?backup_unique_code='.$backup_unique_code.'&launch=form&file='.$file.'&id='.$id);
6641 } else {
6642 return $backup_unique_code;
6647 if (!$status) {
6648 if (!defined('RESTORE_SILENTLY')) {
6649 error ("An error has ocurred");
6650 } else {
6651 $errorstr = "An error has occured"; // helpful! :P
6652 return false;
6655 return true;
6658 function restore_setup_for_check(&$restore,$backup_unique_code) {
6659 global $SESSION;
6660 $restore->backup_unique_code=$backup_unique_code;
6661 $restore->users = 2; // yuk
6662 $restore->course_files = $SESSION->restore->restore_course_files;
6663 $restore->site_files = $SESSION->restore->restore_site_files;
6664 if ($allmods = get_records("modules")) {
6665 foreach ($allmods as $mod) {
6666 $modname = $mod->name;
6667 $var = "restore_".$modname;
6668 //Now check that we have that module info in the backup file
6669 if (isset($SESSION->info->mods[$modname]) && $SESSION->info->mods[$modname]->backup == "true") {
6670 $restore->$var = 1;
6674 return true;
6677 function backup_to_restore_array($backup,$k=0) {
6678 if (is_array($backup) ) {
6679 foreach ($backup as $key => $value) {
6680 $newkey = str_replace('backup','restore',$key);
6681 $restore[$newkey] = backup_to_restore_array($value,$key);
6684 else if (is_object($backup)) {
6685 $tmp = get_object_vars($backup);
6686 foreach ($tmp as $key => $value) {
6687 $newkey = str_replace('backup','restore',$key);
6688 $restore->$newkey = backup_to_restore_array($value,$key);
6691 else {
6692 $newkey = str_replace('backup','restore',$k);
6693 $restore = $backup;
6695 return $restore;
6699 * compatibility function
6700 * checks for per-instance backups AND
6701 * older per-module backups
6702 * and returns whether userdata has been selected.
6704 function restore_userdata_selected($restore,$modname,$modid) {
6705 // check first for per instance array
6706 if (!empty($restore->mods[$modname]->granular)) { // supports per instance
6707 return array_key_exists($modid,$restore->mods[$modname]->instances)
6708 && !empty($restore->mods[$modname]->instances[$modid]->userinfo);
6711 //print_object($restore->mods[$modname]);
6712 return !empty($restore->mods[$modname]->userinfo);
6715 function restore_execute(&$restore,$info,$course_header,&$errorstr) {
6717 global $CFG, $USER;
6718 $status = true;
6720 //Checks for the required files/functions to restore every module
6721 //and include them
6722 if ($allmods = get_records("modules") ) {
6723 foreach ($allmods as $mod) {
6724 $modname = $mod->name;
6725 $modfile = "$CFG->dirroot/mod/$modname/restorelib.php";
6726 //If file exists and we have selected to restore that type of module
6727 if ((file_exists($modfile)) and !empty($restore->mods[$modname]) and ($restore->mods[$modname]->restore)) {
6728 include_once($modfile);
6733 if (!defined('RESTORE_SILENTLY')) {
6734 //Start the main table
6735 echo "<table cellpadding=\"5\">";
6736 echo "<tr><td>";
6738 //Start the main ul
6739 echo "<ul>";
6742 //Localtion of the xml file
6743 $xml_file = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code."/moodle.xml";
6745 //If we've selected to restore into new course
6746 //create it (course)
6747 //Saving conversion id variables into backup_tables
6748 if ($restore->restoreto == 2) {
6749 if (!defined('RESTORE_SILENTLY')) {
6750 echo '<li>'.get_string('creatingnewcourse') . '</li>';
6752 $oldidnumber = $course_header->course_idnumber;
6753 if (!$status = restore_create_new_course($restore,$course_header)) {
6754 if (!defined('RESTORE_SILENTLY')) {
6755 notify("Error while creating the new empty course.");
6756 } else {
6757 $errorstr = "Error while creating the new empty course.";
6758 return false;
6762 //Print course fullname and shortname and category
6763 if ($status) {
6764 if (!defined('RESTORE_SILENTLY')) {
6765 echo "<ul>";
6766 echo "<li>".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
6767 echo "<li>".get_string("category").": ".$course_header->category->name.'</li>';
6768 if (!empty($oldidnumber)) {
6769 echo "<li>".get_string("nomoreidnumber","moodle",$oldidnumber)."</li>";
6771 echo "</ul>";
6772 //Put the destination course_id
6774 $restore->course_id = $course_header->course_id;
6777 if ($status = restore_open_html($restore,$course_header)){
6778 echo "<li>Creating the Restorelog.html in the course backup folder</li>";
6781 } else {
6782 $course = get_record("course","id",$restore->course_id);
6783 if ($course) {
6784 if (!defined('RESTORE_SILENTLY')) {
6785 echo "<li>".get_string("usingexistingcourse");
6786 echo "<ul>";
6787 echo "<li>".get_string("from").": ".$course_header->course_fullname." (".$course_header->course_shortname.")".'</li>';
6788 echo "<li>".get_string("to").": ". format_string($course->fullname) ." (".format_string($course->shortname).")".'</li>';
6789 if (($restore->deleting)) {
6790 echo "<li>".get_string("deletingexistingcoursedata").'</li>';
6791 } else {
6792 echo "<li>".get_string("addingdatatoexisting").'</li>';
6794 echo "</ul></li>";
6796 //If we have selected to restore deleting, we do it now.
6797 if ($restore->deleting) {
6798 if (!defined('RESTORE_SILENTLY')) {
6799 echo "<li>".get_string("deletingolddata").'</li>';
6801 $status = remove_course_contents($restore->course_id,false) and
6802 delete_dir_contents($CFG->dataroot."/".$restore->course_id,"backupdata");
6803 if ($status) {
6804 //Now , this situation is equivalent to the "restore to new course" one (we
6805 //have a course record and nothing more), so define it as "to new course"
6806 $restore->restoreto = 2;
6807 } else {
6808 if (!defined('RESTORE_SILENTLY')) {
6809 notify("An error occurred while deleting some of the course contents.");
6810 } else {
6811 $errrostr = "An error occurred while deleting some of the course contents.";
6812 return false;
6816 } else {
6817 if (!defined('RESTORE_SILENTLY')) {
6818 notify("Error opening existing course.");
6819 $status = false;
6820 } else {
6821 $errorstr = "Error opening existing course.";
6822 return false;
6827 //Now create users as needed
6828 if ($status and ($restore->users == 0 or $restore->users == 1)) {
6829 if (!defined('RESTORE_SILENTLY')) {
6830 echo "<li>".get_string("creatingusers")."<br />";
6832 if (!$status = restore_create_users($restore,$xml_file)) {
6833 if (!defined('RESTORE_SILENTLY')) {
6834 notify("Could not restore users.");
6835 } else {
6836 $errorstr = "Could not restore users.";
6837 return false;
6841 //Now print info about the work done
6842 if ($status) {
6843 $recs = get_records_sql("select old_id, new_id from {$CFG->prefix}backup_ids
6844 where backup_code = '$restore->backup_unique_code' and
6845 table_name = 'user'");
6846 //We've records
6847 if ($recs) {
6848 $new_count = 0;
6849 $exists_count = 0;
6850 $student_count = 0;
6851 $teacher_count = 0;
6852 $counter = 0;
6853 //Iterate, filling counters
6854 foreach ($recs as $rec) {
6855 //Get full record, using backup_getids
6856 $record = backup_getid($restore->backup_unique_code,"user",$rec->old_id);
6857 if (strpos($record->info,"new") !== false) {
6858 $new_count++;
6860 if (strpos($record->info,"exists") !== false) {
6861 $exists_count++;
6863 if (strpos($record->info,"student") !== false) {
6864 $student_count++;
6865 } else if (strpos($record->info,"teacher") !== false) {
6866 $teacher_count++;
6868 //Do some output
6869 $counter++;
6870 if ($counter % 10 == 0) {
6871 if (!defined('RESTORE_SILENTLY')) {
6872 echo ".";
6873 if ($counter % 200 == 0) {
6874 echo "<br />";
6877 backup_flush(300);
6880 if (!defined('RESTORE_SILENTLY')) {
6881 //Now print information gathered
6882 echo " (".get_string("new").": ".$new_count.", ".get_string("existing").": ".$exists_count.")";
6883 echo "<ul>";
6884 echo "<li>".get_string("students").": ".$student_count.'</li>';
6885 echo "<li>".get_string("teachers").": ".$teacher_count.'</li>';
6886 echo "</ul>";
6888 } else {
6889 if (!defined('RESTORE_SILENTLY')) {
6890 notify("No users were found!");
6891 } // no need to return false here, it's recoverable.
6895 if (!defined('RESTORE_SILENTLY')) {
6896 echo "</li>";
6901 //Now create groups as needed
6902 if ($status) {
6903 if (!defined('RESTORE_SILENTLY')) {
6904 echo "<li>".get_string("creatinggroups");
6906 if (!$status = restore_create_groups($restore,$xml_file)) {
6907 if (!defined('RESTORE_SILENTLY')) {
6908 notify("Could not restore groups!");
6909 } else {
6910 $errorstr = "Could not restore groups!";
6911 return false;
6914 if (!defined('RESTORE_SILENTLY')) {
6915 echo '</li>';
6919 //Now create groupings as needed
6920 if ($status) {
6921 if (!defined('RESTORE_SILENTLY')) {
6922 echo "<li>".get_string("creatinggroupings");
6924 if (!$status = restore_create_groupings($restore,$xml_file)) {
6925 if (!defined('RESTORE_SILENTLY')) {
6926 notify("Could not restore groupings!");
6927 } else {
6928 $errorstr = "Could not restore groupings!";
6929 return false;
6932 if (!defined('RESTORE_SILENTLY')) {
6933 echo '</li>';
6937 //Now create groupingsgroups as needed
6938 if ($status) {
6939 if (!defined('RESTORE_SILENTLY')) {
6940 echo "<li>".get_string("creatinggroupingsgroups");
6942 if (!$status = restore_create_groupings_groups($restore,$xml_file)) {
6943 if (!defined('RESTORE_SILENTLY')) {
6944 notify("Could not restore groups in groupings!");
6945 } else {
6946 $errorstr = "Could not restore groups in groupings!";
6947 return false;
6950 if (!defined('RESTORE_SILENTLY')) {
6951 echo '</li>';
6956 //Now create the course_sections and their associated course_modules
6957 //we have to do this after groups and groupings are restored, because we need the new groupings id
6958 if ($status) {
6959 //Into new course
6960 if ($restore->restoreto == 2) {
6961 if (!defined('RESTORE_SILENTLY')) {
6962 echo "<li>".get_string("creatingsections");
6964 if (!$status = restore_create_sections($restore,$xml_file)) {
6965 if (!defined('RESTORE_SILENTLY')) {
6966 notify("Error creating sections in the existing course.");
6967 } else {
6968 $errorstr = "Error creating sections in the existing course.";
6969 return false;
6972 if (!defined('RESTORE_SILENTLY')) {
6973 echo '</li>';
6975 //Into existing course
6976 } else if ($restore->restoreto == 0 or $restore->restoreto == 1) {
6977 if (!defined('RESTORE_SILENTLY')) {
6978 echo "<li>".get_string("checkingsections");
6980 if (!$status = restore_create_sections($restore,$xml_file)) {
6981 if (!defined('RESTORE_SILENTLY')) {
6982 notify("Error creating sections in the existing course.");
6983 } else {
6984 $errorstr = "Error creating sections in the existing course.";
6985 return false;
6988 if (!defined('RESTORE_SILENTLY')) {
6989 echo '</li>';
6991 //Error
6992 } else {
6993 if (!defined('RESTORE_SILENTLY')) {
6994 notify("Neither a new course or an existing one was specified.");
6995 $status = false;
6996 } else {
6997 $errorstr = "Neither a new course or an existing one was specified.";
6998 return false;
7003 //Now create metacourse info
7004 if ($status and $restore->metacourse) {
7005 //Only to new courses!
7006 if ($restore->restoreto == 2) {
7007 if (!defined('RESTORE_SILENTLY')) {
7008 echo "<li>".get_string("creatingmetacoursedata");
7010 if (!$status = restore_create_metacourse($restore,$xml_file)) {
7011 if (!defined('RESTORE_SILENTLY')) {
7012 notify("Error creating metacourse in the course.");
7013 } else {
7014 $errorstr = "Error creating metacourse in the course.";
7015 return false;
7018 if (!defined('RESTORE_SILENTLY')) {
7019 echo '</li>';
7025 //Now create categories and questions as needed
7026 if ($status) {
7027 include_once("$CFG->dirroot/question/restorelib.php");
7028 if (!defined('RESTORE_SILENTLY')) {
7029 echo "<li>".get_string("creatingcategoriesandquestions");
7030 echo "<ul>";
7032 if (!$status = restore_create_questions($restore,$xml_file)) {
7033 if (!defined('RESTORE_SILENTLY')) {
7034 notify("Could not restore categories and questions!");
7035 } else {
7036 $errorstr = "Could not restore categories and questions!";
7037 return false;
7040 if (!defined('RESTORE_SILENTLY')) {
7041 echo "</ul></li>";
7045 //Now create user_files as needed
7046 if ($status and ($restore->user_files)) {
7047 if (!defined('RESTORE_SILENTLY')) {
7048 echo "<li>".get_string("copyinguserfiles");
7050 if (!$status = restore_user_files($restore)) {
7051 if (!defined('RESTORE_SILENTLY')) {
7052 notify("Could not restore user files!");
7053 } else {
7054 $errorstr = "Could not restore user files!";
7055 return false;
7058 //If all is ok (and we have a counter)
7059 if ($status and ($status !== true)) {
7060 //Inform about user dirs created from backup
7061 if (!defined('RESTORE_SILENTLY')) {
7062 echo "<ul>";
7063 echo "<li>".get_string("userzones").": ".$status;
7064 echo "</li></ul>";
7067 if (!defined('RESTORE_SILENTLY')) {
7068 echo '</li>';
7072 //Now create course files as needed
7073 if ($status and ($restore->course_files)) {
7074 if (!defined('RESTORE_SILENTLY')) {
7075 echo "<li>".get_string("copyingcoursefiles");
7077 if (!$status = restore_course_files($restore)) {
7078 if (empty($status)) {
7079 notify("Could not restore course files!");
7080 } else {
7081 $errorstr = "Could not restore course files!";
7082 return false;
7085 //If all is ok (and we have a counter)
7086 if ($status and ($status !== true)) {
7087 //Inform about user dirs created from backup
7088 if (!defined('RESTORE_SILENTLY')) {
7089 echo "<ul>";
7090 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7091 echo "</ul>";
7094 if (!defined('RESTORE_SILENTLY')) {
7095 echo "</li>";
7100 //Now create site files as needed
7101 if ($status and ($restore->site_files)) {
7102 if (!defined('RESTORE_SILENTLY')) {
7103 echo "<li>".get_string('copyingsitefiles');
7105 if (!$status = restore_site_files($restore)) {
7106 if (empty($status)) {
7107 notify("Could not restore site files!");
7108 } else {
7109 $errorstr = "Could not restore site files!";
7110 return false;
7113 //If all is ok (and we have a counter)
7114 if ($status and ($status !== true)) {
7115 //Inform about user dirs created from backup
7116 if (!defined('RESTORE_SILENTLY')) {
7117 echo "<ul>";
7118 echo "<li>".get_string("filesfolders").": ".$status.'</li>';
7119 echo "</ul>";
7122 if (!defined('RESTORE_SILENTLY')) {
7123 echo "</li>";
7127 //Now create messages as needed
7128 if ($status and ($restore->messages)) {
7129 if (!defined('RESTORE_SILENTLY')) {
7130 echo "<li>".get_string("creatingmessagesinfo");
7132 if (!$status = restore_create_messages($restore,$xml_file)) {
7133 if (!defined('RESTORE_SILENTLY')) {
7134 notify("Could not restore messages!");
7135 } else {
7136 $errorstr = "Could not restore messages!";
7137 return false;
7140 if (!defined('RESTORE_SILENTLY')) {
7141 echo "</li>";
7145 //Now create scales as needed
7146 if ($status) {
7147 if (!defined('RESTORE_SILENTLY')) {
7148 echo "<li>".get_string("creatingscales");
7150 if (!$status = restore_create_scales($restore,$xml_file)) {
7151 if (!defined('RESTORE_SILENTLY')) {
7152 notify("Could not restore custom scales!");
7153 } else {
7154 $errorstr = "Could not restore custom scales!";
7155 return false;
7158 if (!defined('RESTORE_SILENTLY')) {
7159 echo '</li>';
7163 //Now create events as needed
7164 if ($status) {
7165 if (!defined('RESTORE_SILENTLY')) {
7166 echo "<li>".get_string("creatingevents");
7168 if (!$status = restore_create_events($restore,$xml_file)) {
7169 if (!defined('RESTORE_SILENTLY')) {
7170 notify("Could not restore course events!");
7171 } else {
7172 $errorstr = "Could not restore course events!";
7173 return false;
7176 if (!defined('RESTORE_SILENTLY')) {
7177 echo '</li>';
7181 //Now create course modules as needed
7182 if ($status) {
7183 if (!defined('RESTORE_SILENTLY')) {
7184 echo "<li>".get_string("creatingcoursemodules");
7186 if (!$status = restore_create_modules($restore,$xml_file)) {
7187 if (!defined('RESTORE_SILENTLY')) {
7188 notify("Could not restore modules!");
7189 } else {
7190 $errorstr = "Could not restore modules!";
7191 return false;
7194 if (!defined('RESTORE_SILENTLY')) {
7195 echo '</li>';
7199 //Now create gradebook as needed -- AFTER modules!!!
7200 if ($status) {
7201 if (!defined('RESTORE_SILENTLY')) {
7202 echo "<li>".get_string("creatinggradebook");
7204 if (!$status = restore_create_gradebook($restore,$xml_file)) {
7205 if (!defined('RESTORE_SILENTLY')) {
7206 notify("Could not restore gradebook!");
7207 } else {
7208 $errorstr = "Could not restore gradebook!";
7209 return false;
7212 if (!defined('RESTORE_SILENTLY')) {
7213 echo '</li>';
7217 //Bring back the course blocks -- do it AFTER the modules!!!
7218 if($status) {
7219 //If we are deleting and bringing into a course or making a new course, same situation
7220 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7221 if (!defined('RESTORE_SILENTLY')) {
7222 echo '<li>'.get_string('creatingblocks');
7224 $course_header->blockinfo = !empty($course_header->blockinfo) ? $course_header->blockinfo : NULL;
7225 if (!$status = restore_create_blocks($restore, $info->backup_block_format, $course_header->blockinfo, $xml_file)) {
7226 if (!defined('RESTORE_SILENTLY')) {
7227 notify('Error while creating the course blocks');
7228 } else {
7229 $errorstr = "Error while creating the course blocks";
7230 return false;
7233 if (!defined('RESTORE_SILENTLY')) {
7234 echo '</li>';
7239 if($status) {
7240 //If we are deleting and bringing into a course or making a new course, same situation
7241 if($restore->restoreto == 0 || $restore->restoreto == 2) {
7242 if (!defined('RESTORE_SILENTLY')) {
7243 echo '<li>'.get_string('courseformatdata');
7245 if (!$status = restore_set_format_data($restore, $xml_file)) {
7246 $error = "Error while setting the course format data";
7247 if (!defined('RESTORE_SILENTLY')) {
7248 notify($error);
7249 } else {
7250 $errorstr=$error;
7251 return false;
7254 if (!defined('RESTORE_SILENTLY')) {
7255 echo '</li>';
7260 //Now create log entries as needed
7261 if ($status and ($restore->logs)) {
7262 if (!defined('RESTORE_SILENTLY')) {
7263 echo "<li>".get_string("creatinglogentries");
7265 if (!$status = restore_create_logs($restore,$xml_file)) {
7266 if (!defined('RESTORE_SILENTLY')) {
7267 notify("Could not restore logs!");
7268 } else {
7269 $errorstr = "Could not restore logs!";
7270 return false;
7273 if (!defined('RESTORE_SILENTLY')) {
7274 echo '</li>';
7278 //Now, if all is OK, adjust the instance field in course_modules !!
7279 if ($status) {
7280 if (!defined('RESTORE_SILENTLY')) {
7281 echo "<li>".get_string("checkinginstances");
7283 if (!$status = restore_check_instances($restore)) {
7284 if (!defined('RESTORE_SILENTLY')) {
7285 notify("Could not adjust instances in course_modules!");
7286 } else {
7287 $errorstr = "Could not adjust instances in course_modules!";
7288 return false;
7291 if (!defined('RESTORE_SILENTLY')) {
7292 echo '</li>';
7296 //Now, if all is OK, adjust activity events
7297 if ($status) {
7298 if (!defined('RESTORE_SILENTLY')) {
7299 echo "<li>".get_string("refreshingevents");
7301 if (!$status = restore_refresh_events($restore)) {
7302 if (!defined('RESTORE_SILENTLY')) {
7303 notify("Could not refresh events for activities!");
7304 } else {
7305 $errorstr = "Could not refresh events for activities!";
7306 return false;
7309 if (!defined('RESTORE_SILENTLY')) {
7310 echo '</li>';
7314 //Now, if all is OK, adjust inter-activity links
7315 if ($status) {
7316 if (!defined('RESTORE_SILENTLY')) {
7317 echo "<li>".get_string("decodinginternallinks");
7319 if (!$status = restore_decode_content_links($restore)) {
7320 if (!defined('RESTORE_SILENTLY')) {
7321 notify("Could not decode content links!");
7322 } else {
7323 $errorstr = "Could not decode content links!";
7324 return false;
7327 if (!defined('RESTORE_SILENTLY')) {
7328 echo '</li>';
7332 //Now, with backup files prior to version 2005041100,
7333 //convert all the wiki texts in the course to markdown
7334 if ($status && $restore->backup_version < 2005041100) {
7335 if (!defined('RESTORE_SILENTLY')) {
7336 echo "<li>".get_string("convertingwikitomarkdown");
7338 if (!$status = restore_convert_wiki2markdown($restore)) {
7339 if (!defined('RESTORE_SILENTLY')) {
7340 notify("Could not convert wiki texts to markdown!");
7341 } else {
7342 $errorstr = "Could not convert wiki texts to markdown!";
7343 return false;
7346 if (!defined('RESTORE_SILENTLY')) {
7347 echo '</li>';
7351 /*******************************************************************************
7352 ************* Restore of Roles and Capabilities happens here ******************
7353 *******************************************************************************/
7354 // try to restore roles even when restore is going to fail - teachers might have
7355 // at least some role assigned - this is not correct though
7356 $status = restore_create_roles($restore, $xml_file) && $status;
7357 $status = restore_roles_settings($restore, $xml_file) && $status;
7359 //Now if all is OK, update:
7360 // - course modinfo field
7361 // - categories table
7362 // - add user as teacher
7363 if ($status) {
7364 if (!defined('RESTORE_SILENTLY')) {
7365 echo "<li>".get_string("checkingcourse");
7367 //modinfo field
7368 rebuild_course_cache($restore->course_id);
7369 //categories table
7370 $course = get_record("course","id",$restore->course_id);
7371 fix_course_sortorder();
7372 // Check if the user has course update capability in the newly restored course
7373 // there is no need to load his capabilities again, because restore_roles_settings
7374 // would have loaded it anyway, if there is any assignments.
7375 // fix for MDL-6831
7376 $newcontext = get_context_instance(CONTEXT_COURSE, $restore->course_id);
7377 if (!has_capability('moodle/course:manageactivities', $newcontext)) {
7378 // fix for MDL-9065, use the new config setting if exists
7379 if ($CFG->creatornewroleid) {
7380 role_assign($CFG->creatornewroleid, $USER->id, 0, $newcontext->id);
7381 } else {
7382 if ($legacyteachers = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW, get_context_instance(CONTEXT_SYSTEM, SITEID))) {
7383 if ($legacyteacher = array_shift($legacyteachers)) {
7384 role_assign($legacyteacher->id, $USER->id, 0, $newcontext->id);
7386 } else {
7387 notify('Could not find a legacy teacher role. You might need your moodle admin to assign a role with editing privilages to this course.');
7391 if (!defined('RESTORE_SILENTLY')) {
7392 echo '</li>';
7396 //Cleanup temps (files and db)
7397 if ($status) {
7398 if (!defined('RESTORE_SILENTLY')) {
7399 echo "<li>".get_string("cleaningtempdata");
7401 if (!$status = clean_temp_data ($restore)) {
7402 if (!defined('RESTORE_SILENTLY')) {
7403 notify("Could not clean up temporary data from files and database");
7404 } else {
7405 $errorstr = "Could not clean up temporary data from files and database";
7406 return false;
7409 if (!defined('RESTORE_SILENTLY')) {
7410 echo '</li>';
7414 // this is not a critical check - the result can be ignored
7415 if (restore_close_html($restore)){
7416 if (!defined('RESTORE_SILENTLY')) {
7417 echo '<li>Closing the Restorelog.html file.</li>';
7420 else {
7421 if (!defined('RESTORE_SILENTLY')) {
7422 notify("Could not close the restorelog.html file");
7426 if (!defined('RESTORE_SILENTLY')) {
7427 //End the main ul
7428 echo "</ul>";
7430 //End the main table
7431 echo "</td></tr>";
7432 echo "</table>";
7435 return $status;
7437 //Create, open and write header of the html log file
7438 function restore_open_html($restore,$course_header) {
7440 global $CFG;
7442 $status = true;
7444 //Open file for writing
7445 //First, we check the course_id backup data folder exists and create it as necessary in CFG->dataroot
7446 if (!$dest_dir = make_upload_directory("$restore->course_id/backupdata")) { // Backup folder
7447 error("Could not create backupdata folder. The site administrator needs to fix the file permissions");
7449 $status = check_dir_exists($dest_dir,true);
7450 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
7451 //Add the stylesheet
7452 $stylesheetshtml = '';
7453 foreach ($CFG->stylesheets as $stylesheet) {
7454 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
7456 ///Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
7457 $languagehtml = get_html_lang($dir=true);
7459 //Write the header in the new logging file
7460 fwrite ($restorelog_file,"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
7461 fwrite ($restorelog_file," \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ");
7462 fwrite ($restorelog_file,"<html dir=\"ltr\".$languagehtml.");
7463 fwrite ($restorelog_file,"<head>");
7464 fwrite ($restorelog_file,$stylesheetshtml);
7465 fwrite ($restorelog_file,"<title>".$course_header->course_shortname." Restored </title>");
7466 fwrite ($restorelog_file,"</head><body><br/><h1>The following changes were made during the Restoration of this Course.</h1><br/><br/>");
7467 fwrite ($restorelog_file,"The Course ShortName is now - ".$course_header->course_shortname." The FullName is now - ".$course_header->course_fullname."<br/><br/>");
7468 $startdate = addslashes($course_header->course_startdate);
7469 $date = usergetdate($startdate);
7470 fwrite ($restorelog_file,"The Originating Courses Start Date was " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."");
7471 $startdate += $restore->course_startdateoffset;
7472 $date = usergetdate($startdate);
7473 fwrite ($restorelog_file,"&nbsp;&nbsp;&nbsp;This Courses Start Date is now " .$date['weekday'].", ".$date['mday']." ".$date['month']." ".$date['year']."<br/><br/>");
7475 if ($status) {
7476 return $restorelog_file;
7477 } else {
7478 return false;
7481 //Create & close footer of the html log file
7482 function restore_close_html($restore) {
7484 global $CFG;
7486 $status = true;
7488 //Open file for writing
7489 //First, check that course_id/backupdata folder exists in CFG->dataroot
7490 $dest_dir = $CFG->dataroot."/".$restore->course_id."/backupdata";
7491 $status = check_dir_exists($dest_dir, true, true);
7492 $restorelog_file = fopen("$dest_dir/restorelog.html","a");
7493 //Write the footer to close the logging file
7494 fwrite ($restorelog_file,"<br/>This file was written to directly by each modules restore process.");
7495 fwrite ($restorelog_file,"<br/><br/>Log complete.</body></html>");
7497 if ($status) {
7498 return $restorelog_file;
7499 } else {
7500 return false;
7504 /********************** Roles and Capabilities Related Functions *******************************/
7506 /* Yu: Note recovering of role assignments/overrides need to take place after
7507 users have been recovered, i.e. after we get their new_id, and after all
7508 roles have been recreated or mapped. Contexts can be created on the fly.
7509 The current order of restore is Restore (old) -> restore roles -> restore assignment/overrides
7510 the order of restore among different contexts, i.e. course, mod, blocks, users should not matter
7511 once roles and users have been restored.
7515 * This function restores all the needed roles for this course
7516 * i.e. roles with an assignment in any of the mods or blocks,
7517 * roles assigned on any user (e.g. parent role) and roles
7518 * assigned at course levle
7519 * This function should check for duplicate roles first
7520 * It isn't now, just overwriting
7522 function restore_create_roles($restore, $xmlfile) {
7523 if (!defined('RESTORE_SILENTLY')) {
7524 echo "<li>".get_string("creatingrolesdefinitions").'</li>';
7526 $info = restore_read_xml_roles($xmlfile);
7528 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
7530 // the following code creates new roles
7531 // but we could use more intelligent detection, and role mapping
7532 // get role mapping info from $restore
7533 $rolemappings = array();
7535 if (!empty($restore->rolesmapping)) {
7536 $rolemappings = $restore->rolesmapping;
7538 // $info->roles will be empty for backups pre 1.7
7539 if (isset($info->roles) && $info->roles) {
7541 foreach ($info->roles as $oldroleid=>$roledata) {
7542 if (empty($restore->rolesmapping)) {
7543 // if this is empty altogether, we came from import or there's no roles used in course at all
7544 // in this case, write the same oldid as this is the same site
7545 // no need to do mapping
7546 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
7547 $oldroleid); // adding a new id
7548 continue; // do not create additonal roles;
7550 // first we check if the roles are in the mappings
7551 // if so, we just do a mapping i.e. update oldids table
7552 if (isset($rolemappings[$oldroleid]) && $rolemappings[$oldroleid]) {
7553 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
7554 $rolemappings[$oldroleid]); // adding a new id
7556 } else {
7558 // code to make new role name/short name if same role name or shortname exists
7559 $fullname = $roledata->name;
7560 $shortname = $roledata->shortname;
7561 $currentfullname = "";
7562 $currentshortname = "";
7563 $counter = 0;
7565 do {
7566 if ($counter) {
7567 $suffixfull = " ".get_string("copyasnoun")." ".$counter;
7568 $suffixshort = "_".$counter;
7569 } else {
7570 $suffixfull = "";
7571 $suffixshort = "";
7573 $currentfullname = $fullname.$suffixfull;
7574 // Limit the size of shortname - database column accepts <= 15 chars
7575 $currentshortname = substr($shortname, 0, 15 - strlen($suffixshort)).$suffixshort;
7576 $coursefull = get_record("role","name",addslashes($currentfullname));
7577 $courseshort = get_record("role","shortname",addslashes($currentshortname));
7578 $counter++;
7579 } while ($coursefull || $courseshort);
7581 $roledata->name = $currentfullname;
7582 $roledata->shortname= $currentshortname;
7584 // done finding a unique name
7586 $newroleid = create_role(addslashes($roledata->name),addslashes($roledata->shortname),'');
7587 $status = backup_putid($restore->backup_unique_code,"role",$oldroleid,
7588 $newroleid); // adding a new id
7589 foreach ($roledata->capabilities as $capability) {
7591 $roleinfo = new object();
7592 $roleinfo = (object)$capability;
7593 $roleinfo->contextid = $sitecontext->id;
7594 $roleinfo->capability = $capability->name;
7595 $roleinfo->roleid = $newroleid;
7597 insert_record('role_capabilities', $roleinfo);
7602 return true;
7606 * this function restores role assignments and role overrides
7607 * in course/user/block/mod level, it passed through
7608 * the xml file again
7610 function restore_roles_settings($restore, $xmlfile) {
7611 // data pulls from course, mod, user, and blocks
7613 /*******************************************************
7614 * Restoring from course level assignments *
7615 *******************************************************/
7616 if (!defined('RESTORE_SILENTLY')) {
7617 echo "<li>".get_string("creatingcourseroles").'</li>';
7619 $course = restore_read_xml_course_header($xmlfile);
7621 if (!isset($restore->rolesmapping)) {
7622 $isimport = true; // course import from another course, or course with no role assignments
7623 } else {
7624 $isimport = false; // course restore with role assignments
7627 if (!empty($course->roleassignments) && !$isimport) {
7628 $courseassignments = $course->roleassignments;
7630 foreach ($courseassignments as $oldroleid => $courseassignment) {
7631 restore_write_roleassignments($restore, $courseassignment->assignments, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
7634 /*****************************************************
7635 * Restoring from course level overrides *
7636 *****************************************************/
7638 if (!empty($course->roleoverrides) && !$isimport) {
7639 $courseoverrides = $course->roleoverrides;
7640 foreach ($courseoverrides as $oldroleid => $courseoverride) {
7641 // if not importing into exiting course, or creating new role, we are ok
7642 // local course overrides to be respected (i.e. restored course overrides ignored)
7643 if ($restore->restoreto != 1 || empty($restore->rolesmapping[$oldroleid])) {
7644 restore_write_roleoverrides($restore, $courseoverride->overrides, "course", CONTEXT_COURSE, $course->course_id, $oldroleid);
7649 /*******************************************************
7650 * Restoring role assignments/overrdies *
7651 * from module level assignments *
7652 *******************************************************/
7654 if (!defined('RESTORE_SILENTLY')) {
7655 echo "<li>".get_string("creatingmodroles").'</li>';
7657 $sections = restore_read_xml_sections($xmlfile);
7658 $secs = $sections->sections;
7660 foreach ($secs as $section) {
7661 if (isset($section->mods)) {
7662 foreach ($section->mods as $modid=>$mod) {
7663 if (isset($mod->roleassignments) && !$isimport) {
7664 foreach ($mod->roleassignments as $oldroleid=>$modassignment) {
7665 restore_write_roleassignments($restore, $modassignment->assignments, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
7668 // role overrides always applies, in import or backup/restore
7669 if (isset($mod->roleoverrides)) {
7670 foreach ($mod->roleoverrides as $oldroleid=>$modoverride) {
7671 restore_write_roleoverrides($restore, $modoverride->overrides, "course_modules", CONTEXT_MODULE, $modid, $oldroleid);
7678 /*************************************************
7679 * Restoring assignments from blocks level *
7680 * role assignments/overrides *
7681 *************************************************/
7683 if ($restore->restoreto != 1) { // skip altogether if restoring to exisitng course by adding
7684 if (!defined('RESTORE_SILENTLY')) {
7685 echo "<li>".get_string("creatingblocksroles").'</li>';
7687 $blocks = restore_read_xml_blocks($xmlfile);
7688 if (isset($blocks->instances)) {
7689 foreach ($blocks->instances as $instance) {
7690 if (isset($instance->roleassignments) && !$isimport) {
7691 foreach ($instance->roleassignments as $oldroleid=>$blockassignment) {
7692 restore_write_roleassignments($restore, $blockassignment->assignments, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
7696 // likewise block overrides should always be restored like mods
7697 if (isset($instance->roleoverrides)) {
7698 foreach ($instance->roleoverrides as $oldroleid=>$blockoverride) {
7699 restore_write_roleoverrides($restore, $blockoverride->overrides, "block_instance", CONTEXT_BLOCK, $instance->id, $oldroleid);
7705 /************************************************
7706 * Restoring assignments from userid level *
7707 * role assignments/overrides *
7708 ************************************************/
7709 if (!defined('RESTORE_SILENTLY')) {
7710 echo "<li>".get_string("creatinguserroles").'</li>';
7712 $info = restore_read_xml_users($restore, $xmlfile);
7713 if (!empty($info->users) && !$isimport) { // no need to restore user assignments for imports (same course)
7714 //For each user, take its info from backup_ids
7715 foreach ($info->users as $userid) {
7716 $rec = backup_getid($restore->backup_unique_code,"user",$userid);
7717 if (isset($rec->info->roleassignments)) {
7718 foreach ($rec->info->roleassignments as $oldroleid=>$userassignment) {
7719 restore_write_roleassignments($restore, $userassignment->assignments, "user", CONTEXT_USER, $userid, $oldroleid);
7722 if (isset($rec->info->roleoverrides)) {
7723 foreach ($rec->info->roleoverrides as $oldroleid=>$useroverride) {
7724 restore_write_roleoverrides($restore, $useroverride->overrides, "user", CONTEXT_USER, $userid, $oldroleid);
7730 return true;
7733 // auxillary function to write role assignments read from xml to db
7734 function restore_write_roleassignments($restore, $assignments, $table, $contextlevel, $oldid, $oldroleid) {
7736 $role = backup_getid($restore->backup_unique_code, "role", $oldroleid);
7738 foreach ($assignments as $assignment) {
7740 $olduser = backup_getid($restore->backup_unique_code,"user",$assignment->userid);
7741 //Oh dear, $olduser... can be an object, $obj->string or bool!
7742 if (!$olduser || (is_string($olduser->info) && $olduser->info == "notincourse")) { // it's possible that user is not in the course
7743 continue;
7745 $assignment->userid = $olduser->new_id; // new userid here
7746 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$assignment->modifierid);
7747 $assignment->modifierid = !empty($oldmodifier->new_id) ? $oldmodifier->new_id : 0; // new modifier id here
7748 $assignment->roleid = $role->new_id; // restored new role id
7750 // hack to make the correct contextid for course level imports
7751 if ($contextlevel == CONTEXT_COURSE) {
7752 $oldinstance->new_id = $restore->course_id;
7753 } else {
7754 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
7757 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
7758 $assignment->contextid = $newcontext->id; // new context id
7759 // might already have same assignment
7760 role_assign($assignment->roleid, $assignment->userid, 0, $assignment->contextid, $assignment->timestart, $assignment->timeend, $assignment->hidden, $assignment->enrol, $assignment->timemodified);
7765 // auxillary function to write role assignments read from xml to db
7766 function restore_write_roleoverrides($restore, $overrides, $table, $contextlevel, $oldid, $oldroleid) {
7768 // it is possible to have an override not relevant to this course context.
7769 // should be ignored(?)
7770 if (!$role = backup_getid($restore->backup_unique_code, "role", $oldroleid)) {
7771 return null;
7774 foreach ($overrides as $override) {
7775 $override->capability = $override->name;
7776 $oldmodifier = backup_getid($restore->backup_unique_code,"user",$override->modifierid);
7777 $override->modifierid = $oldmodifier->new_id?$oldmodifier->new_id:0; // new modifier id here
7778 $override->roleid = $role->new_id; // restored new role id
7780 // hack to make the correct contextid for course level imports
7781 if ($contextlevel == CONTEXT_COURSE) {
7782 $oldinstance->new_id = $restore->course_id;
7783 } else {
7784 $oldinstance = backup_getid($restore->backup_unique_code,$table,$oldid);
7787 $newcontext = get_context_instance($contextlevel, $oldinstance->new_id);
7788 $override->contextid = $newcontext->id; // new context id
7789 // use assign capability instead so we can add context to context_rel
7790 assign_capability($override->capability, $override->permission, $override->roleid, $override->contextid);
7793 //write activity date changes to the html log file, and update date values in the the xml array
7794 function restore_log_date_changes($recordtype, &$restore, &$xml, $TAGS, $NAMETAG='NAME') {
7796 global $CFG;
7797 $openlog = false;
7799 // loop through time fields in $TAGS
7800 foreach ($TAGS as $TAG) {
7802 // check $TAG has a sensible value
7803 if (!empty($xml[$TAG][0]['#']) && is_string($xml[$TAG][0]['#']) && is_numeric($xml[$TAG][0]['#'])) {
7805 if ($openlog==false) {
7806 $openlog = true; // only come through here once
7808 // open file for writing
7809 $course_dir = "$CFG->dataroot/$restore->course_id/backupdata";
7810 check_dir_exists($course_dir, true);
7811 $restorelog = fopen("$course_dir/restorelog.html", "a");
7813 // start output for this record
7814 $msg = new stdClass();
7815 $msg->recordtype = $recordtype;
7816 $msg->recordname = $xml[$NAMETAG][0]['#'];
7817 fwrite ($restorelog, get_string("backupdaterecordtype", "moodle", $msg));
7820 // write old date to $restorelog
7821 $value = $xml[$TAG][0]['#'];
7822 $date = usergetdate($value);
7824 $msg = new stdClass();
7825 $msg->TAG = $TAG;
7826 $msg->weekday = $date['weekday'];
7827 $msg->mday = $date['mday'];
7828 $msg->month = $date['month'];
7829 $msg->year = $date['year'];
7830 fwrite ($restorelog, get_string("backupdateold", "moodle", $msg));
7832 // write new date to $restorelog
7833 $value += $restore->course_startdateoffset;
7834 $date = usergetdate($value);
7836 $msg = new stdClass();
7837 $msg->TAG = $TAG;
7838 $msg->weekday = $date['weekday'];
7839 $msg->mday = $date['mday'];
7840 $msg->month = $date['month'];
7841 $msg->year = $date['year'];
7842 fwrite ($restorelog, get_string("backupdatenew", "moodle", $msg));
7844 // update $value in $xml tree for calling module
7845 $xml[$TAG][0]['#'] = "$value";
7848 // close the restore log, if it was opened
7849 if ($openlog) {
7850 fclose($restorelog);