MDL-9137 Applied parts of Petr's patch on the gradebook objects. Unit tests unaffected.
[moodle-pu.git] / backup / backuplib.php
blob2f50ca422f97f0a559681b3ea2b4137cff0c47b8
1 <?php //$Id$
2 //This file contains all the function needed in the backup utility
3 //except the mod-related funtions that are into every backuplib.php inside
4 //every mod directory
6 //Calculate the number of users to backup and put their ids in backup_ids
7 //Return an array of info (name,value)
8 function user_check_backup($course,$backup_unique_code,$backup_users,$backup_messages) {
9 //$backup_users=0-->all
10 // 1-->course (needed + enrolled)
11 // 2-->none
13 global $CFG;
14 global $db;
16 $context = get_context_instance(CONTEXT_COURSE, $course);
17 $count_users = 0;
19 //If we've selected none, simply return 0
20 if ($backup_users == 0 or $backup_users == 1) {
22 //Calculate needed users (calling every xxxx_get_participants function + scales users)
23 $needed_users = backup_get_needed_users($course, $backup_messages);
25 //Calculate enrolled users (students + teachers)
26 $enrolled_users = backup_get_enrolled_users($course);
28 //Calculate all users (every record in users table)
29 $all_users = backup_get_all_users();
31 //Calculate course users (needed + enrolled)
32 //First, needed
33 $course_users = $needed_users;
35 //Now, enrolled
36 if ($enrolled_users) {
37 foreach ($enrolled_users as $enrolled_user) {
38 $course_users[$enrolled_user->id]->id = $enrolled_user->id;
42 //Now, depending of parameters, create $backupable_users
43 if ($backup_users == 0) {
44 $backupable_users = $all_users;
45 } else {
46 $backupable_users = $course_users;
49 //If we have backupable users
50 if ($backupable_users) {
51 //Iterate over users putting their roles
52 foreach ($backupable_users as $backupable_user) {
53 $backupable_user->info = "";
55 //Is needed user (exists in needed_users)
56 if (isset($needed_users[$backupable_user->id])) {
57 $backupable_user->info .= "needed";
58 } else if (isset($course_users[$backupable_user->id])) {
59 $backupable_user->info .= "needed";
60 } // Yu: also needed because they can view course
61 // might need another variable
63 //Now create the backup_id record
64 $backupids_rec->backup_code = $backup_unique_code;
65 $backupids_rec->table_name = "user";
66 $backupids_rec->old_id = $backupable_user->id;
67 $backupids_rec->info = $backupable_user->info;
69 //Insert the record id. backup_users decide it.
70 //When all users
71 $status = insert_record('backup_ids', $backupids_rec, false);
72 $count_users++;
74 //Do some output
75 backup_flush(30);
79 //Prepare Info
80 //Gets the user data
81 $info[0][0] = get_string("users");
82 $info[0][1] = $count_users;
84 return $info;
87 //Returns every needed user (participant) in a course
88 //It uses the xxxx_get_participants() function
89 //plus users needed to backup scales.
90 //WARNING: It returns only NEEDED users, not every
91 // every student and teacher in the course, so it
92 //must be merged with backup_get_enrrolled_users !!
94 function backup_get_needed_users ($courseid, $includemessages=false) {
96 global $CFG;
98 $result = false;
100 $course_modules = get_records_sql ("SELECT cm.id, m.name, cm.instance
101 FROM {$CFG->prefix}modules m,
102 {$CFG->prefix}course_modules cm
103 WHERE m.id = cm.module and
104 cm.course = '$courseid'");
106 if ($course_modules) {
107 //Iterate over each module
108 foreach ($course_modules as $course_module) {
109 $modlib = "$CFG->dirroot/mod/$course_module->name/lib.php";
110 $modgetparticipants = $course_module->name."_get_participants";
111 if (file_exists($modlib)) {
112 include_once($modlib);
113 if (function_exists($modgetparticipants)) {
114 $module_participants = $modgetparticipants($course_module->instance);
115 //Add them to result
116 if ($module_participants) {
117 foreach ($module_participants as $module_participant) {
118 $result[$module_participant->id]->id = $module_participant->id;
126 //Now, add scale users (from site and course scales)
127 //Get users
128 $scaleusers = get_records_sql("SELECT DISTINCT userid,userid
129 FROM {$CFG->prefix}scale
130 WHERE courseid = '0' or courseid = '$courseid'");
131 //Add scale users to results
132 if ($scaleusers) {
133 foreach ($scaleusers as $scaleuser) {
134 //If userid != 0
135 if ($scaleuser->userid != 0) {
136 $result[$scaleuser->userid]->id = $scaleuser->userid;
141 //Now, add message users if necessary
142 if ($includemessages) {
143 include_once("$CFG->dirroot/message/lib.php");
144 //Get users
145 $messageusers = message_get_participants();
146 //Add message users to results
147 if ($messageusers) {
148 foreach ($messageusers as $messageuser) {
149 //If id != 0
150 if ($messageuser->id !=0) {
151 $result[$messageuser->id]->id = $messageuser->id;
157 return $result;
161 //Returns every enrolled user (student and teacher) in a course
163 function backup_get_enrolled_users ($courseid) {
165 global $CFG;
167 // get all users with moodle/course:view capability, this will include people
168 // assigned at cat level, or site level
169 // but it should be ok if they have no direct assignment at course, mod, block level
170 return get_users_by_capability(get_context_instance(CONTEXT_COURSE, $courseid), 'moodle/course:view');
173 //Returns all users ids (every record in users table)
174 function backup_get_all_users() {
176 return get_records('user', '', '', '', 'id, id');
179 //Calculate the number of log entries to backup
180 //Return an array of info (name,value)
181 function log_check_backup($course) {
183 global $CFG;
185 //Now execute the count
186 $ids = count_records("log","course",$course);
188 //Gets the user data
189 $info[0][0] = get_string("logs");
190 if ($ids) {
191 $info[0][1] = $ids;
192 } else {
193 $info[0][1] = 0;
196 return $info;
199 //Calculate the number of user files to backup
200 //Under $CFG->dataroot/users
201 //and put them (their path) in backup_ids
202 //Return an array of info (name,value)
203 function user_files_check_backup($course,$backup_unique_code) {
205 global $CFG;
207 $rootdir = $CFG->dataroot."/users";
208 //Check if directory exists
209 if (is_dir($rootdir)) {
210 //Get directories without descend
211 $userdirs = get_directory_list($rootdir,"",false,true,false);
212 foreach ($userdirs as $dir) {
213 //Extracts user id from file path
214 $tok = strtok($dir,"/");
215 if ($tok) {
216 $userid = $tok;
217 } else {
218 //We were getting $dir='0', so continue (WAS: $tok = "";)
219 continue;
221 //Look it is a backupable user
222 $data = get_record ("backup_ids","backup_code","$backup_unique_code",
223 "table_name","user",
224 "old_id",$userid);
225 if ($data) {
226 //Insert them into backup_files
227 $status = execute_sql("INSERT INTO {$CFG->prefix}backup_files
228 (backup_code, file_type, path, old_id)
229 VALUES
230 ('$backup_unique_code','user','".addslashes($dir)."','$userid')",false);
232 //Do some output
233 backup_flush(30);
237 //Now execute the select
238 $ids = get_records_sql("SELECT DISTINCT b.path, b.old_id
239 FROM {$CFG->prefix}backup_files b
240 WHERE backup_code = '$backup_unique_code' AND
241 file_type = 'user'");
242 //Gets the user data
243 $info[0][0] = get_string("files");
244 if ($ids) {
245 $info[0][1] = count($ids);
246 } else {
247 $info[0][1] = 0;
250 return $info;
253 //Calculate the number of course files to backup
254 //under $CFG->dataroot/$course, except $CFG->moddata, and backupdata
255 //and put them (their path) in backup_ids
256 //Return an array of info (name,value)
257 function course_files_check_backup($course,$backup_unique_code) {
259 global $CFG;
261 $rootdir = $CFG->dataroot."/$course";
262 //Check if directory exists
263 if (is_dir($rootdir)) {
264 //Get files and directories without descend
265 $coursedirs = get_directory_list($rootdir,$CFG->moddata,false,true,true);
266 $backupdata_dir = "backupdata";
267 foreach ($coursedirs as $dir) {
268 //Check it isn't backupdata_dir
269 if (strpos($dir,$backupdata_dir)!==0) {
270 //Insert them into backup_files
271 $status = execute_sql("INSERT INTO {$CFG->prefix}backup_files
272 (backup_code, file_type, path)
273 VALUES
274 ('$backup_unique_code','course','".addslashes($dir)."')",false);
276 //Do some output
277 backup_flush(30);
281 //Now execute the select
282 $ids = get_records_sql("SELECT DISTINCT b.path, b.old_id
283 FROM {$CFG->prefix}backup_files b
284 WHERE backup_code = '$backup_unique_code' AND
285 file_type = 'course'");
286 //Gets the user data
287 $info[0][0] = get_string("files");
288 if ($ids) {
289 $info[0][1] = count($ids);
290 } else {
291 $info[0][1] = 0;
294 return $info;
297 //Function to check and create the needed moddata dir to
298 //save all the mod backup files. We always name it moddata
299 //to be able to restore it, but in restore we check for
300 //$CFG->moddata !!
301 function check_and_create_moddata_dir($backup_unique_code) {
303 global $CFG;
305 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/moddata",true);
307 return $status;
310 //Function to check and create the "user_files" dir to
311 //save all the user files we need from "users" dir
312 function check_and_create_user_files_dir($backup_unique_code) {
314 global $CFG;
316 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/user_files",true);
318 return $status;
321 //Function to check and create the "group_files" dir to
322 //save all the user files we need from "groups" dir
323 function check_and_create_group_files_dir($backup_unique_code) {
325 global $CFG;
327 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/group_files",true);
329 return $status;
332 //Function to check and create the "course_files" dir to
333 //save all the course files we need from "CFG->datadir/course" dir
334 function check_and_create_course_files_dir($backup_unique_code) {
336 global $CFG;
338 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/course_files",true);
340 return $status;
343 //Function to create, open and write header of the xml file
344 function backup_open_xml($backup_unique_code) {
346 global $CFG;
348 $status = true;
350 //Open for writing
352 $file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
353 $backup_file = fopen($file,"w");
354 //Writes the header
355 $status = fwrite ($backup_file,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
356 if ($status) {
357 $status = fwrite ($backup_file,start_tag("MOODLE_BACKUP",0,true));
359 if ($status) {
360 return $backup_file;
361 } else {
362 return false;
366 //Close the file
367 function backup_close_xml($backup_file) {
368 $status = fwrite ($backup_file,end_tag("MOODLE_BACKUP",0,true));
369 return fclose($backup_file);
372 //Return the xml start tag
373 function start_tag($tag,$level=0,$endline=false,$attributes=null) {
374 if ($endline) {
375 $endchar = "\n";
376 } else {
377 $endchar = "";
379 $attrstring = '';
380 if (!empty($attributes) && is_array($attributes)) {
381 foreach ($attributes as $key => $value) {
382 $attrstring .= " ".xml_tag_safe_content($key)."=\"".
383 xml_tag_safe_content($value)."\"";
386 return str_repeat(" ",$level*2)."<".strtoupper($tag).$attrstring.">".$endchar;
389 //Return the xml end tag
390 function end_tag($tag,$level=0,$endline=true) {
391 if ($endline) {
392 $endchar = "\n";
393 } else {
394 $endchar = "";
396 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
399 //Return the start tag, the contents and the end tag
400 function full_tag($tag,$level=0,$endline=true,$content,$attributes=null) {
402 global $CFG;
404 //Here we encode absolute links
405 $content = backup_encode_absolute_links($content);
407 $st = start_tag($tag,$level,$endline,$attributes);
409 $co = xml_tag_safe_content($content);
411 $et = end_tag($tag,0,true);
413 return $st.$co.$et;
417 function xml_tag_safe_content($content) {
418 global $CFG;
419 //If enabled, we strip all the control chars (\x0-\x1f) from the text but tabs (\x9),
420 //newlines (\xa) and returns (\xd). The delete control char (\x7f) is also included.
421 //because they are forbiden in XML 1.0 specs. The expression below seems to be
422 //UTF-8 safe too because it simply ignores the rest of characters.
423 $content = preg_replace("/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is","",$content);
424 $content = preg_replace("/\r\n|\r/", "\n", htmlspecialchars($content));
425 return $content;
428 //Prints General info about the course
429 //name, moodle_version (internal and release), backup_version, date, info in file...
430 function backup_general_info ($bf,$preferences) {
432 global $CFG;
434 fwrite ($bf,start_tag("INFO",1,true));
436 //The name of the backup
437 fwrite ($bf,full_tag("NAME",2,false,$preferences->backup_name));
438 //The moodle_version
439 fwrite ($bf,full_tag("MOODLE_VERSION",2,false,$preferences->moodle_version));
440 fwrite ($bf,full_tag("MOODLE_RELEASE",2,false,$preferences->moodle_release));
441 //The backup_version
442 fwrite ($bf,full_tag("BACKUP_VERSION",2,false,$preferences->backup_version));
443 fwrite ($bf,full_tag("BACKUP_RELEASE",2,false,$preferences->backup_release));
444 //The date
445 fwrite ($bf,full_tag("DATE",2,false,$preferences->backup_unique_code));
446 //The original site wwwroot
447 fwrite ($bf,full_tag("ORIGINAL_WWWROOT",2,false,$CFG->wwwroot));
448 //The zip method used
449 if (!empty($CFG->zip)) {
450 $zipmethod = 'external';
451 } else {
452 $zipmethod = 'internal';
454 //Indicate if it includes external MNET users
455 $sql = "SELECT b.old_id
456 FROM {$CFG->prefix}backup_ids b
457 JOIN {$CFG->prefix}user u ON b.old_id=u.id
458 WHERE b.backup_code = '$preferences->backup_unique_code'
459 AND b.table_name = 'user' AND u.mnethostid != '{$CFG->mnet_localhost_id}'";
460 if (record_exists_sql($sql)) {
461 fwrite ($bf,full_tag("MNET_REMOTEUSERS",2,false,'true'));
463 fwrite ($bf,full_tag("ZIP_METHOD",2,false,$zipmethod));
464 //Te includes tag
465 fwrite ($bf,start_tag("DETAILS",2,true));
466 //Now, go to mod element of preferences to print its status
467 foreach ($preferences->mods as $element) {
468 //Calculate info
469 $included = "false";
470 $userinfo = "false";
471 if ($element->backup) {
472 $included = "true";
473 if ($element->userinfo) {
474 $userinfo = "true";
477 //Prints the mod start
478 fwrite ($bf,start_tag("MOD",3,true));
479 fwrite ($bf,full_tag("NAME",4,false,$element->name));
480 fwrite ($bf,full_tag("INCLUDED",4,false,$included));
481 fwrite ($bf,full_tag("USERINFO",4,false,$userinfo));
483 if (isset($preferences->mods[$element->name]->instances)
484 && is_array($preferences->mods[$element->name]->instances)
485 && count($preferences->mods[$element->name]->instances)) {
486 fwrite ($bf, start_tag("INSTANCES",4,true));
487 foreach ($preferences->mods[$element->name]->instances as $id => $object) {
488 if (!empty($object->backup)) {
489 //Calculate info
490 $included = "false";
491 $userinfo = "false";
492 if ($object->backup) {
493 $included = "true";
494 if ($object->userinfo) {
495 $userinfo = "true";
498 fwrite ($bf, start_tag("INSTANCE",5,true));
499 fwrite ($bf, full_tag("ID",5,false,$id));
500 fwrite ($bf, full_tag("NAME",5,false,$object->name));
501 fwrite ($bf, full_tag("INCLUDED",5,false,$included)) ;
502 fwrite ($bf, full_tag("USERINFO",5,false,$userinfo));
503 fwrite ($bf, end_tag("INSTANCE",5,true));
506 fwrite ($bf, end_tag("INSTANCES",4,true));
510 //Print the end
511 fwrite ($bf,end_tag("MOD",3,true));
513 //The metacourse in backup
514 if ($preferences->backup_metacourse == 1) {
515 fwrite ($bf,full_tag("METACOURSE",3,false,"true"));
516 } else {
517 fwrite ($bf,full_tag("METACOURSE",3,false,"false"));
519 //The user in backup
520 if ($preferences->backup_users == 1) {
521 fwrite ($bf,full_tag("USERS",3,false,"course"));
522 } else if ($preferences->backup_users == 0) {
523 fwrite ($bf,full_tag("USERS",3,false,"all"));
524 } else {
525 fwrite ($bf,full_tag("USERS",3,false,"none"));
527 //The logs in backup
528 if ($preferences->backup_logs == 1) {
529 fwrite ($bf,full_tag("LOGS",3,false,"true"));
530 } else {
531 fwrite ($bf,full_tag("LOGS",3,false,"false"));
533 //The user files
534 if ($preferences->backup_user_files == 1) {
535 fwrite ($bf,full_tag("USERFILES",3,false,"true"));
536 } else {
537 fwrite ($bf,full_tag("USERFILES",3,false,"false"));
539 //The course files
540 if ($preferences->backup_course_files == 1) {
541 fwrite ($bf,full_tag("COURSEFILES",3,false,"true"));
542 } else {
543 fwrite ($bf,full_tag("COURSEFILES",3,false,"false"));
545 //The messages in backup
546 if ($preferences->backup_messages == 1 && $preferences->backup_course == SITEID) {
547 fwrite ($bf,full_tag("MESSAGES",3,false,"true"));
548 } else {
549 fwrite ($bf,full_tag("MESSAGES",3,false,"false"));
551 //The mode of writing the block data
552 fwrite ($bf,full_tag('BLOCKFORMAT',3,false,'instances'));
553 fwrite ($bf,end_tag("DETAILS",2,true));
555 $status = fwrite ($bf,end_tag("INFO",1,true));
557 ///Roles stuff goes in here
559 fwrite ($bf, start_tag('ROLES', 1, true));
560 $roles = backup_fetch_roles($preferences);
562 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
564 foreach ($roles as $role) {
565 fwrite ($bf,start_tag('ROLE',2,true));
566 fwrite ($bf,full_tag('ID', 3, false, $role->id));
567 fwrite ($bf,full_tag('NAME',3,false,$role->name));
568 fwrite ($bf,full_tag('SHORTNAME',3,false,$role->shortname));
569 // find and write all default capabilities
570 fwrite ($bf,start_tag('CAPABILITIES',3,true));
571 // pull out all default (site context) capabilities
572 if ($capabilities = role_context_capabilities($role->id, $sitecontext)) {
573 foreach ($capabilities as $capability=>$value) {
574 fwrite ($bf,start_tag('CAPABILITY',4,true));
575 fwrite ($bf,full_tag('NAME', 5, false, $capability));
576 fwrite ($bf,full_tag('PERMISSION', 5, false, $value));
577 // use this to pull out the other info (timemodified and modifierid)
578 $cap = get_record_sql("SELECT *
579 FROM {$CFG->prefix}role_capabilities
580 WHERE capability = '$capability'
581 AND contextid = $sitecontext->id
582 AND roleid = $role->id");
583 fwrite ($bf, full_tag("TIMEMODIFIED", 5, false, $cap->timemodified));
584 fwrite ($bf, full_tag("MODIFIERID", 5, false, $cap->modifierid));
585 fwrite ($bf,end_tag('CAPABILITY',4,true));
588 fwrite ($bf,end_tag('CAPABILITIES',3,true));
589 fwrite ($bf,end_tag('ROLE',2,true));
591 fwrite ($bf,end_tag('ROLES', 1, true));
592 return $status;
595 //Prints course's general info (table course)
596 function backup_course_start ($bf,$preferences) {
598 global $CFG;
600 $status = true;
602 //Course open tag
603 fwrite ($bf,start_tag("COURSE",1,true));
604 //Header open tag
605 fwrite ($bf,start_tag("HEADER",2,true));
607 //Get info from course
608 $course = get_record("course","id",$preferences->backup_course);
609 $context = get_context_instance(CONTEXT_COURSE, $course->id);
610 if ($course) {
611 //Prints course info
612 fwrite ($bf,full_tag("ID",3,false,$course->id));
613 //Obtain the category
614 $category = get_record("course_categories","id","$course->category");
615 if ($category) {
616 //Prints category info
617 fwrite ($bf,start_tag("CATEGORY",3,true));
618 fwrite ($bf,full_tag("ID",4,false,$course->category));
619 fwrite ($bf,full_tag("NAME",4,false,$category->name));
620 fwrite ($bf,end_tag("CATEGORY",3,true));
622 //Continues with the course
623 fwrite ($bf,full_tag("PASSWORD",3,false,$course->password));
624 fwrite ($bf,full_tag("FULLNAME",3,false,$course->fullname));
625 fwrite ($bf,full_tag("SHORTNAME",3,false,$course->shortname));
626 fwrite ($bf,full_tag("IDNUMBER",3,false,$course->idnumber));
627 fwrite ($bf,full_tag("SUMMARY",3,false,$course->summary));
628 fwrite ($bf,full_tag("FORMAT",3,false,$course->format));
629 fwrite ($bf,full_tag("SHOWGRADES",3,false,$course->showgrades));
630 fwrite ($bf,full_tag("NEWSITEMS",3,false,$course->newsitems));
631 fwrite ($bf,full_tag("TEACHER",3,false,$course->teacher));
632 fwrite ($bf,full_tag("TEACHERS",3,false,$course->teachers));
633 fwrite ($bf,full_tag("STUDENT",3,false,$course->student));
634 fwrite ($bf,full_tag("STUDENTS",3,false,$course->students));
635 fwrite ($bf,full_tag("GUEST",3,false,$course->guest));
636 fwrite ($bf,full_tag("STARTDATE",3,false,$course->startdate));
637 fwrite ($bf,full_tag("ENROLPERIOD",3,false,$course->enrolperiod));
638 fwrite ($bf,full_tag("NUMSECTIONS",3,false,$course->numsections));
639 //fwrite ($bf,full_tag("SHOWRECENT",3,false,$course->showrecent)); INFO: This is out in 1.3
640 fwrite ($bf,full_tag("MAXBYTES",3,false,$course->maxbytes));
641 fwrite ($bf,full_tag("SHOWREPORTS",3,false,$course->showreports));
642 fwrite ($bf,full_tag("GROUPMODE",3,false,$course->groupmode));
643 fwrite ($bf,full_tag("GROUPMODEFORCE",3,false,$course->groupmodeforce));
644 fwrite ($bf,full_tag("LANG",3,false,$course->lang));
645 fwrite ($bf,full_tag("THEME",3,false,$course->theme));
646 fwrite ($bf,full_tag("COST",3,false,$course->cost));
647 fwrite ($bf,full_tag("CURRENCY",3,false,$course->currency));
648 fwrite ($bf,full_tag("MARKER",3,false,$course->marker));
649 fwrite ($bf,full_tag("VISIBLE",3,false,$course->visible));
650 fwrite ($bf,full_tag("HIDDENSECTIONS",3,false,$course->hiddensections));
651 fwrite ($bf,full_tag("TIMECREATED",3,false,$course->timecreated));
652 fwrite ($bf,full_tag("TIMEMODIFIED",3,false,$course->timemodified));
653 //If not selected, force metacourse to 0
654 if (!$preferences->backup_metacourse) {
655 $status = fwrite ($bf,full_tag("METACOURSE",3,false,'0'));
656 //else, export the field as is in DB
657 } else {
658 $status = fwrite ($bf,full_tag("METACOURSE",3,false,$course->metacourse));
661 /// write local course overrides here?
662 write_role_overrides_xml($bf, $context, 3);
663 /// write role_assign code here
664 write_role_assignments_xml($bf, $context, 3);
665 //Print header end
666 fwrite ($bf,end_tag("HEADER",2,true));
667 } else {
668 $status = false;
671 return $status;
674 //Prints course's end tag
675 function backup_course_end ($bf,$preferences) {
677 //Course end tag
678 $status = fwrite ($bf,end_tag("COURSE",1,true));
680 return $status;
684 //Prints course's metacourse info (table course_meta)
685 function backup_course_metacourse ($bf,$preferences) {
687 global $CFG;
689 $status = true;
691 //Get info from meta
692 $parents = get_records_sql ("SELECT m.*, c.idnumber, c.shortname
693 FROM {$CFG->prefix}course_meta m,
694 {$CFG->prefix}course c
695 WHERE m.child_course = '$preferences->backup_course' AND
696 m.parent_course = c.id");
697 $childs = get_records_sql ("SELECT m.*, c.idnumber, c.shortname
698 FROM {$CFG->prefix}course_meta m,
699 {$CFG->prefix}course c
700 WHERE m.parent_course = '$preferences->backup_course' AND
701 m.child_course = c.id");
703 if ($parents || $childs) {
704 //metacourse open tag
705 fwrite ($bf,start_tag("METACOURSE",2,true));
706 if ($parents) {
707 fwrite($bf, start_tag("PARENTS",3,true));
708 //Iterate over every parent
709 foreach ($parents as $parent) {
710 //Begin parent
711 fwrite ($bf,start_tag("PARENT",4,true));
712 fwrite ($bf,full_tag("ID",5,false,$parent->parent_course));
713 fwrite ($bf,full_tag("IDNUMBER",5,false,$parent->idnumber));
714 fwrite ($bf,full_tag("SHORTNAME",5,false,$parent->shortname));
715 //End parent
716 fwrite ($bf,end_tag("PARENT",4,true));
718 fwrite ($bf,end_tag("PARENTS",3,true));
720 if ($childs) {
721 fwrite($bf, start_tag("CHILDS",3,true));
722 //Iterate over every child
723 foreach ($childs as $child) {
724 //Begin parent
725 fwrite ($bf,start_tag("CHILD",4,true));
726 fwrite ($bf,full_tag("ID",5,false,$child->child_course));
727 fwrite ($bf,full_tag("IDNUMBER",5,false,$child->idnumber));
728 fwrite ($bf,full_tag("SHORTNAME",5,false,$child->shortname));
729 //End parent
730 fwrite ($bf,end_tag("CHILD",4,true));
732 fwrite ($bf,end_tag("CHILDS",3,true));
734 //metacourse close tag
735 $status = fwrite ($bf,end_tag("METACOURSE",3,true));
738 return $status;
742 //Prints course's messages info (tables message, message_read and message_contacts)
743 function backup_messages ($bf,$preferences) {
745 global $CFG;
747 $status = true;
749 //Get info from messages
750 $unreads = get_records ('message');
751 $reads = get_records ('message_read');
752 $contacts= get_records ('message_contacts');
754 if ($unreads || $reads || $contacts) {
755 $counter = 0;
756 //message open tag
757 fwrite ($bf,start_tag("MESSAGES",2,true));
758 if ($unreads) {
759 //Iterate over every unread
760 foreach ($unreads as $unread) {
761 //start message
762 fwrite($bf, start_tag("MESSAGE",3,true));
763 fwrite ($bf,full_tag("ID",4,false,$unread->id));
764 fwrite ($bf,full_tag("STATUS",4,false,"UNREAD"));
765 fwrite ($bf,full_tag("USERIDFROM",4,false,$unread->useridfrom));
766 fwrite ($bf,full_tag("USERIDTO",4,false,$unread->useridto));
767 fwrite ($bf,full_tag("MESSAGE",4,false,$unread->message));
768 fwrite ($bf,full_tag("FORMAT",4,false,$unread->format));
769 fwrite ($bf,full_tag("TIMECREATED",4,false,$unread->timecreated));
770 fwrite ($bf,full_tag("MESSAGETYPE",4,false,$unread->messagetype));
771 //end message
772 fwrite ($bf,end_tag("MESSAGE",3,true));
774 //Do some output
775 $counter++;
776 if ($counter % 20 == 0) {
777 echo ".";
778 if ($counter % 400 == 0) {
779 echo "<br />";
781 backup_flush(300);
786 if ($reads) {
787 //Iterate over every read
788 foreach ($reads as $read) {
789 //start message
790 fwrite($bf, start_tag("MESSAGE",3,true));
791 fwrite ($bf,full_tag("ID",4,false,$read->id));
792 fwrite ($bf,full_tag("STATUS",4,false,"READ"));
793 fwrite ($bf,full_tag("USERIDFROM",4,false,$read->useridfrom));
794 fwrite ($bf,full_tag("USERIDTO",4,false,$read->useridto));
795 fwrite ($bf,full_tag("MESSAGE",4,false,$read->message));
796 fwrite ($bf,full_tag("FORMAT",4,false,$read->format));
797 fwrite ($bf,full_tag("TIMECREATED",4,false,$read->timecreated));
798 fwrite ($bf,full_tag("MESSAGETYPE",4,false,$read->messagetype));
799 fwrite ($bf,full_tag("TIMEREAD",4,false,$read->timeread));
800 fwrite ($bf,full_tag("MAILED",4,false,$read->mailed));
801 //end message
802 fwrite ($bf,end_tag("MESSAGE",3,true));
804 //Do some output
805 $counter++;
806 if ($counter % 20 == 0) {
807 echo ".";
808 if ($counter % 400 == 0) {
809 echo "<br />";
811 backup_flush(300);
816 if ($contacts) {
817 fwrite($bf, start_tag("CONTACTS",3,true));
818 //Iterate over every contact
819 foreach ($contacts as $contact) {
820 //start contact
821 fwrite($bf, start_tag("CONTACT",4,true));
822 fwrite ($bf,full_tag("ID",5,false,$contact->id));
823 fwrite ($bf,full_tag("USERID",5,false,$contact->userid));
824 fwrite ($bf,full_tag("CONTACTID",5,false,$contact->contactid));
825 fwrite ($bf,full_tag("BLOCKED",5,false,$contact->blocked));
826 //end contact
827 fwrite ($bf,end_tag("CONTACT",4,true));
829 //Do some output
830 $counter++;
831 if ($counter % 20 == 0) {
832 echo ".";
833 if ($counter % 400 == 0) {
834 echo "<br />";
836 backup_flush(300);
839 fwrite($bf, end_tag("CONTACTS",3,true));
841 //messages close tag
842 $status = fwrite ($bf,end_tag("MESSAGES",2,true));
845 return $status;
849 //Prints course's blocks info (table block_instance)
850 function backup_course_blocks ($bf,$preferences) {
852 global $CFG;
854 $status = true;
856 // Read all of the block table
857 $blocks = blocks_get_record();
859 $pages = array();
860 $pages[] = page_create_object(PAGE_COURSE_VIEW, $preferences->backup_course);
862 // Let's see if we have to backup blocks from modules
863 $modulerecords = get_records_sql('SELECT name, id FROM '.$CFG->prefix.'modules');
865 foreach($preferences->mods as $module) {
866 if(!$module->backup) {
867 continue;
870 $cmods = get_records_select('course_modules', 'course = '.$preferences->backup_course.' AND module = '.$modulerecords[$module->name]->id);
871 if(empty($cmods)) {
872 continue;
875 $pagetypes = page_import_types('mod/'.$module->name.'/');
876 if(empty($pagetypes)) {
877 continue;
880 foreach($pagetypes as $pagetype) {
881 foreach($cmods as $cmod) {
882 $pages[] = page_create_object($pagetype, $cmod->instance);
887 //Blocks open tag
888 fwrite ($bf,start_tag('BLOCKS',2,true));
890 while($page = array_pop($pages)) {
891 if ($instances = blocks_get_by_page($page)) {
892 //Iterate over every block
893 foreach ($instances as $position) {
894 foreach ($position as $instance) {
896 //If we somehow have a block with an invalid id, skip it
897 if(empty($blocks[$instance->blockid]->name)) {
898 continue;
900 //Begin Block
902 fwrite ($bf,start_tag('BLOCK',3,true));
903 fwrite ($bf,full_tag('ID', 4, false,$instance->id));
904 fwrite ($bf,full_tag('NAME',4,false,$blocks[$instance->blockid]->name));
905 fwrite ($bf,full_tag('PAGEID',4,false,$instance->pageid));
906 fwrite ($bf,full_tag('PAGETYPE',4,false,$instance->pagetype));
907 fwrite ($bf,full_tag('POSITION',4,false,$instance->position));
908 fwrite ($bf,full_tag('WEIGHT',4,false,$instance->weight));
909 fwrite ($bf,full_tag('VISIBLE',4,false,$instance->visible));
910 fwrite ($bf,full_tag('CONFIGDATA',4,false,$instance->configdata));
912 $context = get_context_instance(CONTEXT_BLOCK, $instance->id);
913 write_role_overrides_xml($bf, $context, 4);
914 /// write role_assign code here
915 write_role_assignments_xml($bf, $context, 4);
916 //End Block
917 fwrite ($bf,end_tag('BLOCK',3,true));
923 //Blocks close tag
924 $status = fwrite ($bf,end_tag('BLOCKS',2,true));
926 return $status;
930 //Prints course's sections info (table course_sections)
931 function backup_course_sections ($bf,$preferences) {
933 global $CFG;
935 $status = true;
938 //Get info from sections
939 $section=false;
940 if ($sections = get_records("course_sections","course",$preferences->backup_course,"section")) {
941 //Section open tag
942 fwrite ($bf,start_tag("SECTIONS",2,true));
943 //Iterate over every section (ordered by section)
944 foreach ($sections as $section) {
945 //Begin Section
946 fwrite ($bf,start_tag("SECTION",3,true));
947 fwrite ($bf,full_tag("ID",4,false,$section->id));
948 fwrite ($bf,full_tag("NUMBER",4,false,$section->section));
949 fwrite ($bf,full_tag("SUMMARY",4,false,$section->summary));
950 fwrite ($bf,full_tag("VISIBLE",4,false,$section->visible));
951 //Now print the mods in section
952 backup_course_modules ($bf,$preferences,$section);
953 //End section
954 fwrite ($bf,end_tag("SECTION",3,true));
956 //Section close tag
957 $status = fwrite ($bf,end_tag("SECTIONS",2,true));
960 return $status;
964 //Prints course's format data (any data the format might want to save).
965 function backup_format_data ($bf,$preferences) {
966 global $CFG;
968 // Check course format
969 if(!($format=get_field('course','format','id',$preferences->backup_course))) {
970 return false;
972 // Write appropriate tag. Note that we always put this tag there even if
973 // blank, it makes parsing easier
974 fwrite ($bf,start_tag("FORMATDATA",2,true));
976 $file=$CFG->dirroot."/course/format/$format/backuplib.php";
977 if(file_exists($file)) {
978 // If the file is there, the function must be or it's an error.
979 require_once($file);
980 $function=$format.'_backup_format_data';
981 if(!function_exists($function)) {
982 return false;
984 if(!$function($bf,$preferences)) {
985 return false;
989 // This last return just checks the file writing has been ok (ish)
990 return fwrite ($bf,end_tag("FORMATDATA",2,true));
993 //Prints course's modules info (table course_modules)
994 //Only for selected mods in preferences
995 function backup_course_modules ($bf,$preferences,$section) {
997 global $CFG;
999 $status = true;
1001 $first_record = true;
1003 //Now print the mods in section
1004 //Extracts mod id from sequence
1005 $tok = strtok($section->sequence,",");
1006 while ($tok) {
1007 //Get module's type
1008 $moduletype = get_module_type ($preferences->backup_course,$tok);
1009 //Check if we've selected to backup that type
1010 if ($moduletype and $preferences->mods[$moduletype]->backup) {
1011 $selected = true;
1012 } else {
1013 $selected = false;
1016 if ($selected) {
1017 $context = get_context_instance(CONTEXT_MODULE, $tok);
1018 //Gets course_module data from db
1019 $course_module = get_records ("course_modules","id",$tok);
1020 //If it's the first, pring MODS tag
1021 if ($first_record) {
1022 fwrite ($bf,start_tag("MODS",4,true));
1023 $first_record = false;
1025 // if we're doing selected instances, check that too.
1026 if (is_array($preferences->mods[$moduletype]->instances)
1027 && count($preferences->mods[$moduletype]->instances)
1028 && (!array_key_exists($course_module[$tok]->instance,$preferences->mods[$moduletype]->instances)
1029 || empty($preferences->mods[$moduletype]->instances[$course_module[$tok]->instance]->backup))) {
1030 $tok = strtok(",");
1031 continue;
1034 // find all role values that has an override in this context
1035 $roles = get_records('role_capabilities', 'contextid', $context->id);
1037 //Print mod info from course_modules
1038 fwrite ($bf,start_tag("MOD",5,true));
1039 //Save neccesary info to backup_ids
1040 fwrite ($bf,full_tag("ID",6,false,$tok));
1041 fwrite ($bf,full_tag("TYPE",6,false,$moduletype));
1042 fwrite ($bf,full_tag("INSTANCE",6,false,$course_module[$tok]->instance));
1043 fwrite ($bf,full_tag("ADDED",6,false,$course_module[$tok]->added));
1044 fwrite ($bf,full_tag("SCORE",6,false,$course_module[$tok]->score));
1045 fwrite ($bf,full_tag("INDENT",6,false,$course_module[$tok]->indent));
1046 fwrite ($bf,full_tag("VISIBLE",6,false,$course_module[$tok]->visible));
1047 fwrite ($bf,full_tag("GROUPMODE",6,false,$course_module[$tok]->groupmode));
1048 // get all the role_capabilities overrides in this mod
1049 write_role_overrides_xml($bf, $context, 6);
1050 /// write role_assign code here
1051 write_role_assignments_xml($bf, $context, 6);
1052 /// write role_assign code here
1054 fwrite ($bf,end_tag("MOD",5,true));
1056 //check for next
1057 $tok = strtok(",");
1060 //Si ha habido modulos, final de MODS
1061 if (!$first_record) {
1062 $status =fwrite ($bf,end_tag("MODS",4,true));
1065 return $status;
1068 //Print users to xml
1069 //Only users previously calculated in backup_ids will output
1071 function backup_user_info ($bf,$preferences) {
1073 global $CFG;
1075 $status = true;
1077 // Use a recordset to for the memory handling on to
1078 // the DB and run faster
1079 $users = get_recordset_sql("SELECT b.old_id, b.table_name, b.info,
1080 u.*, m.wwwroot
1081 FROM {$CFG->prefix}backup_ids b
1082 JOIN {$CFG->prefix}user u ON b.old_id=u.id
1083 JOIN {$CFG->prefix}mnet_host m ON u.mnethostid=m.id
1084 WHERE b.backup_code = '$preferences->backup_unique_code' AND
1085 b.table_name = 'user'");
1087 //If we have users to backup
1088 if ($users && $users->RecordCount()) {
1089 //Begin Users tag
1090 fwrite ($bf,start_tag("USERS",2,true));
1091 $counter = 0;
1092 //With every user
1093 while ($user = $users->FetchNextObj()) {
1094 //Begin User tag
1095 fwrite ($bf,start_tag("USER",3,true));
1096 //Output all user data
1097 fwrite ($bf,full_tag("ID",4,false,$user->id));
1098 fwrite ($bf,full_tag("AUTH",4,false,$user->auth));
1099 fwrite ($bf,full_tag("CONFIRMED",4,false,$user->confirmed));
1100 fwrite ($bf,full_tag("POLICYAGREED",4,false,$user->policyagreed));
1101 fwrite ($bf,full_tag("DELETED",4,false,$user->deleted));
1102 fwrite ($bf,full_tag("USERNAME",4,false,$user->username));
1103 fwrite ($bf,full_tag("PASSWORD",4,false,$user->password));
1104 fwrite ($bf,full_tag("IDNUMBER",4,false,$user->idnumber));
1105 fwrite ($bf,full_tag("FIRSTNAME",4,false,$user->firstname));
1106 fwrite ($bf,full_tag("LASTNAME",4,false,$user->lastname));
1107 fwrite ($bf,full_tag("EMAIL",4,false,$user->email));
1108 fwrite ($bf,full_tag("EMAILSTOP",4,false,$user->emailstop));
1109 fwrite ($bf,full_tag("ICQ",4,false,$user->icq));
1110 fwrite ($bf,full_tag("SKYPE",4,false,$user->skype));
1111 fwrite ($bf,full_tag("YAHOO",4,false,$user->yahoo));
1112 fwrite ($bf,full_tag("AIM",4,false,$user->aim));
1113 fwrite ($bf,full_tag("MSN",4,false,$user->msn));
1114 fwrite ($bf,full_tag("PHONE1",4,false,$user->phone1));
1115 fwrite ($bf,full_tag("PHONE2",4,false,$user->phone2));
1116 fwrite ($bf,full_tag("INSTITUTION",4,false,$user->institution));
1117 fwrite ($bf,full_tag("DEPARTMENT",4,false,$user->department));
1118 fwrite ($bf,full_tag("ADDRESS",4,false,$user->address));
1119 fwrite ($bf,full_tag("CITY",4,false,$user->city));
1120 fwrite ($bf,full_tag("COUNTRY",4,false,$user->country));
1121 fwrite ($bf,full_tag("LANG",4,false,$user->lang));
1122 fwrite ($bf,full_tag("THEME",4,false,$user->theme));
1123 fwrite ($bf,full_tag("TIMEZONE",4,false,$user->timezone));
1124 fwrite ($bf,full_tag("FIRSTACCESS",4,false,$user->firstaccess));
1125 fwrite ($bf,full_tag("LASTACCESS",4,false,$user->lastaccess));
1126 fwrite ($bf,full_tag("LASTLOGIN",4,false,$user->lastlogin));
1127 fwrite ($bf,full_tag("CURRENTLOGIN",4,false,$user->currentlogin));
1128 fwrite ($bf,full_tag("LASTIP",4,false,$user->lastip));
1129 fwrite ($bf,full_tag("SECRET",4,false,$user->secret));
1130 fwrite ($bf,full_tag("PICTURE",4,false,$user->picture));
1131 fwrite ($bf,full_tag("URL",4,false,$user->url));
1132 fwrite ($bf,full_tag("DESCRIPTION",4,false,$user->description));
1133 fwrite ($bf,full_tag("MAILFORMAT",4,false,$user->mailformat));
1134 fwrite ($bf,full_tag("MAILDIGEST",4,false,$user->maildigest));
1135 fwrite ($bf,full_tag("MAILDISPLAY",4,false,$user->maildisplay));
1136 fwrite ($bf,full_tag("HTMLEDITOR",4,false,$user->htmleditor));
1137 fwrite ($bf,full_tag("AJAX",4,false,$user->ajax));
1138 fwrite ($bf,full_tag("AUTOSUBSCRIBE",4,false,$user->autosubscribe));
1139 fwrite ($bf,full_tag("TRACKFORUMS",4,false,$user->trackforums));
1140 if ($user->mnethostid != $CFG->mnet_localhost_id) {
1141 fwrite ($bf,full_tag("MNETHOSTURL",4,false,$user->wwwroot));
1143 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$user->timemodified));
1145 /// write assign/override code for context_userid
1147 $user->isneeded = strpos($user->info,"needed");
1148 //Output every user role (with its associated info)
1150 $user->isadmin = strpos($user->info,"admin");
1151 $user->iscoursecreator = strpos($user->info,"coursecreator");
1152 $user->isteacher = strpos($user->info,"teacher");
1153 $user->isstudent = strpos($user->info,"student");
1156 if ($user->isadmin!==false or
1157 $user->iscoursecreator!==false or
1158 $user->isteacher!==false or
1159 $user->isstudent!==false or
1160 $user->isneeded!==false) {
1162 fwrite ($bf,start_tag("ROLES",4,true));
1163 if ($user->info != "needed" && $user->info!="") {
1164 //Begin ROLES tag
1166 //PRINT ROLE INFO
1167 //Admins
1168 $roles = explode(",", $user->info);
1169 foreach ($roles as $role) {
1170 if ($role!="" && $role!="needed") {
1171 fwrite ($bf,start_tag("ROLE",5,true));
1172 //Print Role info
1173 fwrite ($bf,full_tag("TYPE",6,false,$role));
1174 //Print ROLE end
1175 fwrite ($bf,end_tag("ROLE",5,true));
1180 if ($user->isadmin!==false) {
1181 //Print ROLE start
1182 fwrite ($bf,start_tag("ROLE",5,true));
1183 //Print Role info
1184 fwrite ($bf,full_tag("TYPE",6,false,"admin"));
1185 //Print ROLE end
1186 fwrite ($bf,end_tag("ROLE",5,true));
1188 //CourseCreator
1189 if ($user->iscoursecreator!==false) {
1190 //Print ROLE start
1191 fwrite ($bf,start_tag("ROLE",5,true));
1192 //Print Role info
1193 fwrite ($bf,full_tag("TYPE",6,false,"coursecreator"));
1194 //Print ROLE end
1195 fwrite ($bf,end_tag("ROLE",5,true));
1197 //Teacher
1198 if ($user->isteacher!==false) {
1199 //Print ROLE start
1200 fwrite ($bf,start_tag("ROLE",5,true));
1201 //Print Role info
1202 fwrite ($bf,full_tag("TYPE",6,false,"teacher"));
1203 //Get specific info for teachers
1204 $tea = get_record("user_teachers","userid",$user->old_id,"course",$preferences->backup_course);
1205 fwrite ($bf,full_tag("AUTHORITY",6,false,$tea->authority));
1206 fwrite ($bf,full_tag("TEA_ROLE",6,false,$tea->role));
1207 fwrite ($bf,full_tag("EDITALL",6,false,$tea->editall));
1208 fwrite ($bf,full_tag("TIMESTART",6,false,$tea->timestart));
1209 fwrite ($bf,full_tag("TIMEEND",6,false,$tea->timeend));
1210 fwrite ($bf,full_tag("TIMEMODIFIED",6,false,$tea->timemodified));
1211 fwrite ($bf,full_tag("TIMEACCESS",6,false,$tea->timeaccess));
1212 fwrite ($bf,full_tag("ENROL",6,false,$tea->enrol));
1213 //Print ROLE end
1214 fwrite ($bf,end_tag("ROLE",5,true));
1216 //Student
1217 if ($user->isstudent!==false) {
1218 //Print ROLE start
1219 fwrite ($bf,start_tag("ROLE",5,true));
1220 //Print Role info
1221 fwrite ($bf,full_tag("TYPE",6,false,"student"));
1222 //Get specific info for students
1223 $stu = get_record("user_students","userid",$user->old_id,"course",$preferences->backup_course);
1224 fwrite ($bf,full_tag("TIMESTART",6,false,$stu->timestart));
1225 fwrite ($bf,full_tag("TIMEEND",6,false,$stu->timeend));
1226 fwrite ($bf,full_tag("TIME",6,false,$stu->time));
1227 fwrite ($bf,full_tag("TIMEACCESS",6,false,$stu->timeaccess));
1228 fwrite ($bf,full_tag("ENROL",6,false,$stu->enrol));
1229 //Print ROLE end
1230 fwrite ($bf,end_tag("ROLE",5,true));
1235 //Needed
1236 if ($user->isneeded!==false) {
1237 //Print ROLE start
1238 fwrite ($bf,start_tag("ROLE",5,true));
1239 //Print Role info
1240 fwrite ($bf,full_tag("TYPE",6,false,"needed"));
1241 //Print ROLE end
1242 fwrite ($bf,end_tag("ROLE",5,true));
1245 //End ROLES tag
1246 fwrite ($bf,end_tag("ROLES",4,true));
1248 //Check if we have user_preferences to backup
1249 if ($preferences_data = get_records("user_preferences","userid",$user->old_id)) {
1250 //Start USER_PREFERENCES tag
1251 fwrite ($bf,start_tag("USER_PREFERENCES",4,true));
1252 //Write each user_preference
1253 foreach ($preferences_data as $user_preference) {
1254 fwrite ($bf,start_tag("USER_PREFERENCE",5,true));
1255 fwrite ($bf,full_tag("NAME",6,false,$user_preference->name));
1256 fwrite ($bf,full_tag("VALUE",6,false,$user_preference->value));
1257 fwrite ($bf,end_tag("USER_PREFERENCE",5,true));
1259 //End USER_PREFERENCES tag
1260 fwrite ($bf,end_tag("USER_PREFERENCES",4,true));
1263 $context = get_context_instance(CONTEXT_USER, $user->old_id);
1265 write_role_overrides_xml($bf, $context, 4);
1266 /// write role_assign code here
1267 write_role_assignments_xml($bf, $context, 4);
1268 //End User tag
1269 fwrite ($bf,end_tag("USER",3,true));
1270 //Do some output
1271 $counter++;
1272 if ($counter % 10 == 0) {
1273 echo ".";
1274 if ($counter % 200 == 0) {
1275 echo "<br />";
1277 backup_flush(300);
1280 //End Users tag
1281 fwrite ($bf,end_tag("USERS",2,true));
1282 } else {
1283 // There aren't any users.
1284 $status = true;
1287 return $status;
1290 //Backup log info (time ordered)
1291 function backup_log_info($bf,$preferences) {
1293 global $CFG;
1295 //Number of records to get in every chunk
1296 $recordset_size = 1000;
1298 $status = true;
1300 //Counter, points to current record
1301 $counter = 0;
1303 //Count records
1304 $count_logs = count_records("log","course",$preferences->backup_course);
1306 //Pring logs header
1307 if ($count_logs > 0 ) {
1308 fwrite ($bf,start_tag("LOGS",2,true));
1310 while ($counter < $count_logs) {
1311 //Get a chunk of records
1312 $logs = get_records ("log","course",$preferences->backup_course,"time","*",$counter,$recordset_size);
1314 //We have logs
1315 if ($logs) {
1316 //Iterate
1317 foreach ($logs as $log) {
1318 //See if it is a valid module to backup
1319 if ($log->module == "course" or
1320 $log->module == "user" or
1321 (array_key_exists($log->module, $preferences->mods) and $preferences->mods[$log->module]->backup == 1)) {
1322 // logs with 'upload' in module field are ignored, there is no restore code anyway
1323 //Begin log tag
1324 fwrite ($bf,start_tag("LOG",3,true));
1326 //Output log tag
1327 fwrite ($bf,full_tag("ID",4,false,$log->id));
1328 fwrite ($bf,full_tag("TIME",4,false,$log->time));
1329 fwrite ($bf,full_tag("USERID",4,false,$log->userid));
1330 fwrite ($bf,full_tag("IP",4,false,$log->ip));
1331 fwrite ($bf,full_tag("MODULE",4,false,$log->module));
1332 fwrite ($bf,full_tag("CMID",4,false,$log->cmid));
1333 fwrite ($bf,full_tag("ACTION",4,false,$log->action));
1334 fwrite ($bf,full_tag("URL",4,false,$log->url));
1335 fwrite ($bf,full_tag("INFO",4,false,$log->info));
1337 //End log tag
1338 fwrite ($bf,end_tag("LOG",3,true));
1340 //Do some output
1341 $counter++;
1342 if ($counter % 20 == 0) {
1343 echo ".";
1344 if ($counter % 400 == 0) {
1345 echo "<br />";
1347 backup_flush(300);
1352 //End logs tag
1353 if ($count_logs > 0 ) {
1354 $status = fwrite ($bf,end_tag("LOGS",2,true));
1356 return $status;
1359 //Backup gradebook info
1360 function backup_gradebook_info($bf,$preferences) {
1362 global $CFG;
1364 $status = true;
1366 //Gradebook header
1367 fwrite ($bf,start_tag("GRADEBOOK",2,true));
1369 //Output grade_category
1371 // getting grade categories, but make sure parents come before children
1372 $grade_categories = get_records("grade_categories", "courseid", $preferences->backup_course);
1373 if ($grade_categories) {
1374 //Begin grade_categories tag
1375 fwrite ($bf,start_tag("GRADE_CATEGORIES",3,true));
1376 //Iterate for each category
1377 foreach ($grade_categories as $grade_category) {
1378 //Begin grade_category
1379 fwrite ($bf,start_tag("GRADE_CATEGORY",4,true));
1380 //Output individual fields
1381 fwrite ($bf,full_tag("ID",5,false,$grade_category->id));
1383 // not keeping path and depth because they can be derived
1384 fwrite ($bf,full_tag("PARENT",5,false,$grade_category->parent));
1385 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_category->fullname));
1386 fwrite ($bf,full_tag("AGGREGATION",5,false,$grade_category->aggregation));
1387 fwrite ($bf,full_tag("KEEPHIGH",5,false,$grade_category->keephigh));
1388 fwrite ($bf,full_tag("DROPLOW",5,false,$grade_category->droplow));
1389 fwrite ($bf,full_tag("HIDDEN",5,false,$grade_category->hidden));
1391 //End grade_category
1392 fwrite ($bf,end_tag("GRADE_CATEGORY",4,true));
1394 //End grade_categories tag
1395 $status = fwrite ($bf,end_tag("GRADE_CATEGORIES",3,true));
1398 // Now backup grade_item (inside grade_category)
1399 $status = backup_gradebook_item_info($bf,$preferences);
1400 $status = backup_gradebook_outcomes_info($bf, $preferences);
1401 // back up grade outcomes
1403 //Gradebook footer
1404 $status = fwrite ($bf,end_tag("GRADEBOOK",2,true));
1405 return $status;
1408 //Backup gradebook_item (called from backup_gradebook_info
1409 function backup_gradebook_item_info($bf,$preferences) {
1411 global $CFG;
1413 $status = true;
1415 // get all the grade_items
1416 // might need to do it using sortorder
1417 if ($grade_items = get_records('grade_items', 'courseid', $preferences->backup_course)) {
1419 //Begin grade_items tag
1420 fwrite ($bf,start_tag("GRADE_ITEMS",3,true));
1421 //Iterate for each item
1422 foreach ($grade_items as $grade_item) {
1423 //Begin grade_item
1424 fwrite ($bf,start_tag("GRADE_ITEM",4,true));
1425 //Output individual fields
1427 fwrite ($bf,full_tag("ID",5,false,$grade_item->id));
1428 fwrite ($bf,full_tag("ITEMNAME",5,false,$grade_item->itemname));
1429 fwrite ($bf,full_tag("ITEMMODULE",5,false,$grade_item->itemmodule));
1430 fwrite ($bf,full_tag("ITEMINSTANCE",5,false,$grade_item->iteminstance));
1431 fwrite ($bf,full_tag("ITEMNUMBER",5,false,$grade_item->itemnumber));
1432 fwrite ($bf,full_tag("ITEMINFO",5,false,$grade_item->iteminfo));
1433 fwrite ($bf,full_tag("IDNUMBER",5,false,$grade_item->idnumber));
1434 fwrite ($bf,full_tag("GRADEMAX",5,false,$grade_item->grademax));
1435 fwrite ($bf,full_tag("GRADEMIN",5,false,$grade_item->grademin));
1436 fwrite ($bf,full_tag("SCALEID",5,false,$grade_item->scaleid));
1437 fwrite ($bf,full_tag("OUTCOMEID",5,false,$grade_item->outcomeid));
1438 fwrite ($bf,full_tag("GRADEPASS",5,false,$grade_item->gradepass));
1439 fwrite ($bf,full_tag("MULTFACTOR",5,false,$grade_item->multfactor));
1440 fwrite ($bf,full_tag("PLUSFACTOR",5,false,$grade_item->plusfactor));
1441 fwrite ($bf,full_tag("HIDDEN",5,false,$grade_item->hidden));
1443 // back up the other stuff here
1444 $status = backup_gradebook_calculations_info($bf,$preferences,$grade_item->id);
1445 $status = backup_gradebook_grades_raw_info($bf,$preferences,$grade_item->id);
1446 $status = backup_gradebook_grades_final_info($bf,$preferences,$grade_item->id);
1447 $status = backup_gradebook_grades_history_info($bf,$preferences,$grade_item->id);
1448 $status = backup_gradebook_grades_text_info($bf,$preferences,$grade_item->id);
1450 //End grade_item
1451 fwrite ($bf,end_tag("GRADE_ITEM",4,true));
1453 //End grade_items tag
1454 $status = fwrite ($bf,end_tag("GRADE_ITEMS",3,true));
1457 return $status;
1459 //Backup gradebook_item (called from backup_gradebook_info
1461 function backup_gradebook_outcomes_info($bf,$preferences) {
1463 global $CFG;
1465 $status = true;
1467 // get all the grade_items
1468 // might need to do it using sortorder
1469 if ($grade_outcomes = get_records('grade_outcomes', 'courseid', $preferences->backup_course)) {
1471 //Begin grade_items tag
1472 fwrite ($bf,start_tag("GRADE_OUTCOMES",3,true));
1473 //Iterate for each item
1474 foreach ($grade_outcomes as $grade_outcome) {
1475 //Begin grade_item
1476 fwrite ($bf,start_tag("GRADE_OUTCOME",4,true));
1477 //Output individual fields
1479 fwrite ($bf,full_tag("ID",5,false,$grade_outcome->id));
1480 fwrite ($bf,full_tag("SHORTNAME",5,false,$grade_outcome->shortname));
1481 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_outcome->fullname));
1482 fwrite ($bf,full_tag("SCALEID",5,false,$grade_outcome->scaleid));
1483 fwrite ($bf,full_tag("USERMODIFIED",5,false,$grade_outcome->usermodified));
1485 //End grade_item
1486 fwrite ($bf,end_tag("GRADE_OUTCOME",4,true));
1488 //End grade_items tag
1489 $status = fwrite ($bf,end_tag("GRADE_OUTCOMES",3,true));
1492 return $status;
1494 //Backup gradebook_calculations(called from backup_gradebook_item_info
1495 function backup_gradebook_calculations_info($bf,$preferences, $itemid) {
1497 global $CFG;
1499 $status = true;
1501 // find all calculations belonging to this item
1502 if ($calculations = get_records('grade_calculations', 'itemid', $itemid)) {
1503 fwrite ($bf,start_tag("GRADE_CALCULATIONS",5,true));
1504 foreach ($calculations as $calculation) {
1505 fwrite ($bf,start_tag("GRADE_CALCULATION",6,true));
1506 fwrite ($bf,full_tag("ID",7,false,$calculation->id));
1507 fwrite ($bf,full_tag("CALCULATION",7,false,$calculation->calculation));
1508 fwrite ($bf,full_tag("USERMODIFIED",7,false,$calculation->usermodified));
1509 fwrite ($bf,end_tag("GRADE_CALCULATION",6,true));
1511 $status = fwrite ($bf,end_tag("GRADE_CALCULATIONS",5,true));
1513 return $status;
1516 function backup_gradebook_grades_raw_info($bf,$preferences, $itemid) {
1518 global $CFG;
1520 $status = true;
1522 // find all calculations belonging to this item
1523 if ($raws = get_records('grade_grades_raw', 'itemid', $itemid)) {
1524 fwrite ($bf,start_tag("GRADE_GRADES_RAW",5,true));
1525 foreach ($raws as $raw) {
1526 fwrite ($bf,start_tag("GRADE_RAW",6,true));
1527 fwrite ($bf,full_tag("ID",7,false,$raw->id));
1528 fwrite ($bf,full_tag("USERID",7,false,$raw->userid));
1529 fwrite ($bf,full_tag("GRADEVALUE",7,false,$raw->gradevalue));
1530 fwrite ($bf,full_tag("GRADEMAX",7,false,$raw->grademax));
1531 fwrite ($bf,full_tag("GRADEMIN",7,false,$raw->grademin));
1532 fwrite ($bf,full_tag("SCALEID",7,false,$raw->scaleid));
1533 fwrite ($bf,full_tag("USERMODIFIED",7,false,$raw->usermodified));
1534 fwrite ($bf,end_tag("GRADE_RAW",6,true));
1536 $stauts = fwrite ($bf,end_tag("GRADE_GRADES_RAW",5,true));
1538 return $status;
1541 function backup_gradebook_grades_final_info($bf, $preferences, $itemid) {
1543 global $CFG;
1545 $status = true;
1547 // find all calculations belonging to this item
1548 if ($finals = get_records('grade_grades_final', 'itemid', $itemid)) {
1549 fwrite ($bf,start_tag("GRADE_GRADES_FINAL",5,true));
1550 foreach ($finals as $final) {
1551 fwrite ($bf,start_tag("GRADE_FINAL",6,true));
1552 fwrite ($bf,full_tag("ID",7,false,$final->id));
1553 fwrite ($bf,full_tag("USERID",7,false,$final->userid));
1554 fwrite ($bf,full_tag("GRADEVALUE",7,false,$final->gradevalue));
1555 fwrite ($bf,full_tag("HIDDEN",7,false,$final->hidden));
1556 fwrite ($bf,full_tag("LOCKED",7,false,$final->locked));
1557 fwrite ($bf,full_tag("EXPORTED",7,false,$final->exported));
1558 fwrite ($bf,full_tag("USERMODIFIED",7,false,$final->usermodified));
1559 fwrite ($bf,end_tag("GRADE_FINAL",6,true));
1561 $stauts = fwrite ($bf,end_tag("GRADE_GRADES_FINAL",5,true));
1563 return $status;
1566 function backup_gradebook_grades_text_info($bf, $preferences, $itemid) {
1568 global $CFG;
1570 $status = true;
1572 // find all calculations belonging to this item
1573 if ($texts = get_records('grade_grades_text', 'itemid', $itemid)) {
1574 fwrite ($bf,start_tag("GRADE_GRADES_TEXT",5,true));
1575 foreach ($texts as $text) {
1576 fwrite ($bf,start_tag("GRADE_TEXT",6,true));
1577 fwrite ($bf,full_tag("ID",7,false,$text->id));
1578 fwrite ($bf,full_tag("USERID",7,false,$text->userid));
1579 fwrite ($bf,full_tag("INFORMATION",7,false,$text->information));
1580 fwrite ($bf,full_tag("INFORMATIONFORMAT",7,false,$text->informationformat));
1581 fwrite ($bf,full_tag("FEEDBACK",7,false,$text->feedback));
1582 fwrite ($bf,full_tag("FEEDBACKFORMAT",7,false,$text->feedbackformat));
1583 fwrite ($bf,end_tag("GRADE_TEXT",6,true));
1585 $stauts = fwrite ($bf,end_tag("GRADE_GRADES_TEXT",5,true));
1587 return $status;
1590 function backup_gradebook_grades_history_info($bf, $preferences, $itemid) {
1592 global $CFG;
1594 $status = true;
1596 // find all calculations belonging to this item
1597 if ($histories = get_records('grades_history', 'itemid', $itemid)) {
1598 fwrite ($bf,start_tag("GRADE_GRADES_HISTORY",5,true));
1599 foreach ($histories as $history) {
1600 fwrite ($bf,start_tag("GRADE_HISTORY",6,true));
1601 fwrite ($bf,full_tag("ID",7,false,$history->id));
1602 fwrite ($bf,full_tag("USERID",7,false,$hisotry->userid));
1603 fwrite ($bf,full_tag("OLDGRADE",7,false,$hisotry->oldgrade));
1604 fwrite ($bf,full_tag("NEWGRADE",7,false,$history->newgrade));
1605 fwrite ($bf,full_tag("NOTE",7,false,$history->note));
1606 fwrite ($bf,full_tag("HOWMODIFIED",7,false,$hisotry->howmodified));
1607 fwrite ($bf,full_tag("USERMODIFIED",7,false,$hisotry->usermodified));
1608 fwrite ($bf,end_tag("GRADE_HISTORY",6,true));
1610 $stauts = fwrite ($bf,end_tag("GRADE_GRADES_HISOTRY",5,true));
1612 return $status;
1615 //Backup scales info (common and course scales)
1616 function backup_scales_info($bf,$preferences) {
1618 global $CFG;
1620 $status = true;
1622 //Counter, points to current record
1623 $counter = 0;
1625 //Get scales (common and course scales)
1626 $scales = get_records_sql("SELECT id, courseid, userid, name, scale, description, timemodified
1627 FROM {$CFG->prefix}scale
1628 WHERE courseid = '0' or courseid = $preferences->backup_course");
1630 //Copy only used scales to $backupscales. They will be in backup (unused no). See Bug 1223.
1631 $backupscales = array();
1632 if ($scales) {
1633 foreach ($scales as $scale) {
1634 if (course_scale_used($preferences->backup_course, $scale->id)) {
1635 $backupscales[] = $scale;
1640 //Pring scales header
1641 if ($backupscales) {
1642 //Pring scales header
1643 fwrite ($bf,start_tag("SCALES",2,true));
1644 //Iterate
1645 foreach ($backupscales as $scale) {
1646 //Begin scale tag
1647 fwrite ($bf,start_tag("SCALE",3,true));
1648 //Output scale tag
1649 fwrite ($bf,full_tag("ID",4,false,$scale->id));
1650 fwrite ($bf,full_tag("COURSEID",4,false,$scale->courseid));
1651 fwrite ($bf,full_tag("USERID",4,false,$scale->userid));
1652 fwrite ($bf,full_tag("NAME",4,false,$scale->name));
1653 fwrite ($bf,full_tag("SCALETEXT",4,false,$scale->scale));
1654 fwrite ($bf,full_tag("DESCRIPTION",4,false,$scale->description));
1655 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$scale->timemodified));
1656 //End scale tag
1657 fwrite ($bf,end_tag("SCALE",3,true));
1659 //End scales tag
1660 $status = fwrite ($bf,end_tag("SCALES",2,true));
1662 return $status;
1665 //Backup events info (course events)
1666 function backup_events_info($bf,$preferences) {
1668 global $CFG;
1670 $status = true;
1672 //Counter, points to current record
1673 $counter = 0;
1675 //Get events (course events)
1676 $events = get_records_select("event","courseid='$preferences->backup_course' AND instance='0'","id");
1678 //Pring events header
1679 if ($events) {
1680 //Pring events header
1681 fwrite ($bf,start_tag("EVENTS",2,true));
1682 //Iterate
1683 foreach ($events as $event) {
1684 //Begin event tag
1685 fwrite ($bf,start_tag("EVENT",3,true));
1686 //Output event tag
1687 fwrite ($bf,full_tag("ID",4,false,$event->id));
1688 fwrite ($bf,full_tag("NAME",4,false,$event->name));
1689 fwrite ($bf,full_tag("DESCRIPTION",4,false,$event->description));
1690 fwrite ($bf,full_tag("FORMAT",4,false,$event->format));
1691 fwrite ($bf,full_tag("GROUPID",4,false,$event->groupid));
1692 fwrite ($bf,full_tag("USERID",4,false,$event->userid));
1693 fwrite ($bf,full_tag("REPEATID",4,false,$event->repeatid));
1694 fwrite ($bf,full_tag("EVENTTYPE",4,false,$event->eventtype));
1695 fwrite ($bf,full_tag("TIMESTART",4,false,$event->timestart));
1696 fwrite ($bf,full_tag("TIMEDURATION",4,false,$event->timeduration));
1697 fwrite ($bf,full_tag("VISIBLE",4,false,$event->visible));
1698 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$event->timemodified));
1699 //End event tag
1700 fwrite ($bf,end_tag("EVENT",3,true));
1702 //End events tag
1703 $status = fwrite ($bf,end_tag("EVENTS",2,true));
1705 return $status;
1708 //Backup groups info
1709 function backup_groups_info($bf,$preferences) {
1711 global $CFG;
1713 $status = true;
1714 $status2 = true;
1716 //Get groups
1717 $groups = get_groups($preferences->backup_course); //TODO:check.
1719 //Pring groups header
1720 if ($groups) {
1721 //Pring groups header
1722 fwrite ($bf,start_tag("GROUPS",2,true));
1723 //Iterate
1724 foreach ($groups as $group) {
1725 //Begin group tag
1726 fwrite ($bf,start_tag("GROUP",3,true));
1727 //Output group contents
1728 fwrite ($bf,full_tag("ID",4,false,$group->id));
1729 ///fwrite ($bf,full_tag("COURSEID",4,false,$group->courseid));
1730 fwrite ($bf,full_tag("NAME",4,false,$group->name));
1731 fwrite ($bf,full_tag("DESCRIPTION",4,false,$group->description));
1732 fwrite ($bf,full_tag("ENROLMENTKEY",4,false,$group->enrolmentkey)); //TODO:
1733 fwrite ($bf,full_tag("LANG",4,false,$group->lang));
1734 fwrite ($bf,full_tag("THEME",4,false,$group->theme));
1735 fwrite ($bf,full_tag("PICTURE",4,false,$group->picture));
1736 fwrite ($bf,full_tag("HIDEPICTURE",4,false,$group->hidepicture));
1737 fwrite ($bf,full_tag("TIMECREATED",4,false,$group->timecreated));
1738 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$group->timemodified));
1740 //Now, backup groups_members, only if users are included
1741 if ($preferences->backup_users != 2) {
1742 $status2 = backup_groups_members_info($bf,$preferences,$group->id);
1745 //End group tag
1746 fwrite ($bf,end_tag("GROUP",3,true));
1748 //End groups tag
1749 $status = fwrite ($bf,end_tag("GROUPS",2,true));
1751 //Now save group_files
1752 if ($status && $status2) {
1753 $status2 = backup_copy_group_files($preferences);
1756 return ($status && $status2);
1759 //Backup groups_members info
1760 function backup_groups_members_info($bf,$preferences,$groupid) {
1762 global $CFG;
1764 $status = true;
1766 //Get groups_members
1767 $groups_members = groups_get_member_records($groupid);
1769 //Pring groups_members header
1770 if ($groups_members) {
1771 //Pring groups_members header
1772 fwrite ($bf,start_tag("MEMBERS",4,true));
1773 //Iterate
1774 foreach ($groups_members as $group_member) {
1775 //Begin group_member tag
1776 fwrite ($bf,start_tag("MEMBER",5,true));
1777 //Output group_member contents
1778 fwrite ($bf,full_tag("USERID",6,false,$group_member->userid));
1779 fwrite ($bf,full_tag("TIMEADDED",6,false,$group_member->timeadded));
1780 //End group_member tag
1781 fwrite ($bf,end_tag("MEMBER",5,true));
1783 //End groups_members tag
1784 $status = fwrite ($bf,end_tag("MEMBERS",4,true));
1786 return $status;
1789 //Backup groupings info
1790 function backup_groupings_info($bf,$preferences) {
1792 global $CFG;
1794 $status = true;
1795 $status2 = true;
1797 //Get groups
1798 $groupings = groups_get_grouping_records($preferences->backup_course);
1800 //Pring groups header
1801 if ($groupings) {
1802 //Pring groups header
1803 fwrite ($bf,start_tag("GROUPINGS",2,true));
1804 //Iterate
1805 foreach ($groupings as $grouping) {
1806 //Begin group tag
1807 fwrite ($bf,start_tag("GROUPING",3,true));
1808 //Output group contents
1809 fwrite ($bf,full_tag("ID",4,false,$grouping->id));
1810 fwrite ($bf,full_tag("NAME",4,false,$grouping->name));
1811 fwrite ($bf,full_tag("DESCRIPTION",4,false,$grouping->description));
1812 fwrite ($bf,full_tag("TIMECREATED",4,false,$grouping->timecreated));
1814 $status2 = backup_groupids_info($bf,$preferences,$grouping->id);
1816 //End group tag
1817 fwrite ($bf,end_tag("GROUPING",3,true));
1819 //End groups tag
1820 $status = fwrite ($bf,end_tag("GROUPINGS",2,true));
1822 //(Now save grouping_files)
1824 return ($status && $status2);
1827 //Backup groupings-groups info
1828 function backup_groupids_info($bf,$preferences,$groupingid) {
1830 global $CFG;
1832 $status = true;
1834 //Get groups_members
1835 $grouping_groups = groups_get_groups_in_grouping_records($groupingid) ;
1837 //Pring groups_members header
1838 if ($grouping_groups) {
1839 //Pring groups_members header
1840 fwrite ($bf,start_tag("GROUPS",4,true));
1841 //Iterate
1842 foreach ($grouping_groups as $group2) {
1843 //Begin group tag
1844 fwrite ($bf,start_tag("GROUP",5,true));
1845 //Output group_member contents
1846 fwrite ($bf,full_tag("GROUPID",6,false,$group2->groupid));
1847 fwrite ($bf,full_tag("TIMEADDED",6,false,$group2->timeadded)); //TODO:
1848 //End group tag
1849 fwrite ($bf,end_tag("GROUP",5,true));
1851 //End groups_members tag
1852 $status = fwrite ($bf,end_tag("GROUPS",4,true));
1854 return $status;
1857 //Start the modules tag
1858 function backup_modules_start ($bf,$preferences) {
1860 return fwrite ($bf,start_tag("MODULES",2,true));
1863 //End the modules tag
1864 function backup_modules_end ($bf,$preferences) {
1866 return fwrite ($bf,end_tag("MODULES",2,true));
1869 //This function makes all the necesary calls to every mod
1870 //to export itself and its files !!!
1871 function backup_module($bf,$preferences,$module) {
1873 global $CFG;
1875 $status = true;
1877 require_once($CFG->dirroot.'/mod/'.$module.'/backuplib.php');
1879 if (isset($preferences->mods[$module]->instances)
1880 && is_array($preferences->mods[$module]->instances)) {
1881 $onemodbackup = $module.'_backup_one_mod';
1882 if (function_exists($onemodbackup)) {
1883 foreach ($preferences->mods[$module]->instances as $instance => $object) {
1884 if (!empty($object->backup)) {
1885 $status = $onemodbackup($bf,$preferences,$instance);
1888 } else {
1889 $status = false;
1891 } else { // whole module.
1892 //First, re-check if necessary functions exists
1893 $modbackup = $module."_backup_mods";
1894 if (function_exists($modbackup)) {
1895 //Call the function
1896 $status = $modbackup($bf,$preferences);
1897 } else {
1898 //Something was wrong. Function should exist.
1899 $status = false;
1903 return $status;
1907 //This function encode things to make backup multi-site fully functional
1908 //It does this conversions:
1909 // - $CFG->wwwroot/file.php/courseid ------------------> $@FILEPHP@$ (slasharguments links)
1910 // - $CFG->wwwroot/file.php?file=/courseid ------------> $@FILEPHP@$ (non-slasharguments links)
1911 // - Every module xxxx_encode_content_links() is executed too
1913 function backup_encode_absolute_links($content) {
1915 global $CFG,$preferences;
1917 //Use one static variable to cache all the require_once calls that,
1918 //under PHP5 seems to increase load too much, and we are requiring
1919 //them here thousands of times (one per content). MDL-8700.
1920 //Once fixed by PHP, we'll delete this hack
1922 static $includedfiles;
1923 if (!isset($includedfiles)) {
1924 $includedfiles = array();
1927 //Check if preferences is ok. If it isn't set, we are
1928 //in a scheduled_backup to we are able to get a copy
1929 //from CFG->backup_preferences
1930 if (!isset($preferences)) {
1931 $mypreferences = $CFG->backup_preferences;
1932 } else {
1933 //We are in manual backups so global preferences must exist!!
1934 $mypreferences = $preferences;
1937 //First, we check for every call to file.php inside the course
1938 $search = array($CFG->wwwroot.'/file.php/'.$mypreferences->backup_course,
1939 $CFG->wwwroot.'/file.php?file=/'.$mypreferences->backup_course);
1941 $replace = array('$@FILEPHP@$','$@FILEPHP@$');
1943 $result = str_replace($search,$replace,$content);
1945 foreach ($mypreferences->mods as $name => $info) {
1946 /// We only include the corresponding backuplib.php if it hasn't been included before
1947 /// This will save some load under PHP5. MDL-8700.
1948 /// Once fixed by PHP, we'll delete this hack
1949 if (!in_array($name, $includedfiles)) {
1950 include_once("$CFG->dirroot/mod/$name/backuplib.php");
1951 $includedfiles[] = $name;
1953 //Check if the xxxx_encode_content_links exists
1954 $function_name = $name."_encode_content_links";
1955 if (function_exists($function_name)) {
1956 $result = $function_name($result,$mypreferences);
1960 if ($result != $content) {
1961 debugging('<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />');
1964 return $result;
1967 //This function copies all the needed files under the "users" directory to the "user_files"
1968 //directory under temp/backup
1969 function backup_copy_user_files ($preferences) {
1971 global $CFG;
1973 $status = true;
1975 //First we check to "user_files" exists and create it as necessary
1976 //in temp/backup/$backup_code dir
1977 $status = check_and_create_user_files_dir($preferences->backup_unique_code);
1979 //Now iterate over directories under "users" to check if that user must be
1980 //copied to backup
1982 $rootdir = $CFG->dataroot."/users";
1983 //Check if directory exists
1984 if (is_dir($rootdir)) {
1985 $list = list_directories ($rootdir);
1986 if ($list) {
1987 //Iterate
1988 foreach ($list as $dir) {
1989 //Look for dir like username in backup_ids
1990 $data = get_record ("backup_ids","backup_code",$preferences->backup_unique_code,
1991 "table_name","user",
1992 "old_id",$dir);
1993 //If exists, copy it
1994 if ($data) {
1995 $status = backup_copy_file($rootdir."/".$dir,
1996 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/user_files/".$dir);
2002 return $status;
2005 //This function copies all the needed files under the "groups" directory to the "group_files"
2006 //directory under temp/backup
2007 function backup_copy_group_files ($preferences) {
2009 global $CFG;
2011 $status = true;
2013 //First we check if "group_files" exists and create it as necessary
2014 //in temp/backup/$backup_code dir
2015 $status = check_and_create_group_files_dir($preferences->backup_unique_code);
2017 //Now iterate over directories under "groups" to check if that user must be
2018 //copied to backup
2020 $rootdir = $CFG->dataroot.'/groups';
2021 //Check if directory exists
2022 if (is_dir($rootdir)) {
2023 $list = list_directories ($rootdir);
2024 if ($list) {
2025 //Iterate
2026 foreach ($list as $dir) {
2027 //Look for dir like group in groups table
2028 $data = groups_group_belongs_to_course($dir, $preferences->backup_course);
2029 //TODO:check. get_record ('groups', 'courseid', $preferences->backup_course,'id',$dir);
2030 //If exists, copy it
2031 if ($data) {
2032 $status = backup_copy_file($rootdir."/".$dir,
2033 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/group_files/".$dir);
2038 return $status;
2041 //This function copies all the course files under the course directory (except the moddata
2042 //directory to the "course_files" directory under temp/backup
2043 function backup_copy_course_files ($preferences) {
2045 global $CFG;
2047 $status = true;
2049 //First we check to "course_files" exists and create it as necessary
2050 //in temp/backup/$backup_code dir
2051 $status = check_and_create_course_files_dir($preferences->backup_unique_code);
2053 //Now iterate over files and directories except $CFG->moddata and backupdata to be
2054 //copied to backup
2056 $rootdir = $CFG->dataroot."/".$preferences->backup_course;
2058 $name_moddata = $CFG->moddata;
2059 $name_backupdata = "backupdata";
2060 //Check if directory exists
2061 if (is_dir($rootdir)) {
2062 $list = list_directories_and_files ($rootdir);
2063 if ($list) {
2064 //Iterate
2065 foreach ($list as $dir) {
2066 if ($dir !== $name_moddata and $dir !== $name_backupdata) {
2067 $status = backup_copy_file($rootdir."/".$dir,
2068 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/course_files/".$dir);
2073 return $status;
2076 //This function creates the zip file containing all the backup info
2077 //moodle.xml, moddata, user_files, course_files.
2078 //The zipped file is created in the backup directory and named with
2079 //the "oficial" name of the backup
2080 //It uses "pclzip" if available or system "zip" (unix only)
2081 function backup_zip ($preferences) {
2083 global $CFG;
2085 $status = true;
2087 //Base dir where everything happens
2088 $basedir = cleardoubleslashes($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code);
2089 //Backup zip file name
2090 $name = $preferences->backup_name;
2091 //List of files and directories
2092 $filelist = list_directories_and_files ($basedir);
2094 //Convert them to full paths
2095 $files = array();
2096 foreach ($filelist as $file) {
2097 $files[] = "$basedir/$file";
2100 $status = zip_files($files, "$basedir/$name");
2102 //echo "<br/>Status: ".$status; //Debug
2103 return $status;
2107 //This function copies the final zip to the course dir
2108 function copy_zip_to_course_dir ($preferences) {
2110 global $CFG;
2112 $status = true;
2114 //Define zip location (from)
2115 $from_zip_file = $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/".$preferences->backup_name;
2117 //Initialise $to_zip_file
2118 $to_zip_file="";
2120 //If $preferences->backup_destination isn't empty, then copy to custom directory
2121 if (!empty($preferences->backup_destination)) {
2122 $to_zip_file = $preferences->backup_destination."/".$preferences->backup_name;
2123 } else {
2124 //Define zip destination (course dir)
2125 $to_zip_file = $CFG->dataroot."/".$preferences->backup_course;
2127 //echo "<p>From: ".$from_zip_file."<br />"; //Debug
2129 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2131 //Checks course dir exists
2132 $status = check_dir_exists($to_zip_file,true);
2134 //Define zip destination (backup dir)
2135 $to_zip_file = $to_zip_file."/backupdata";
2137 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2139 //Checks backup dir exists
2140 $status = check_dir_exists($to_zip_file,true);
2142 //Define zip destination (zip file)
2143 $to_zip_file = $to_zip_file."/".$preferences->backup_name;
2146 //echo "<p>To: ".$to_zip_file."<br />"; //Debug
2148 //Copy zip file
2149 if ($status) {
2150 $status = backup_copy_file ($from_zip_file,$to_zip_file);
2153 return $status;
2156 /**
2157 * compatibility function
2158 * with new granular backup
2159 * we need to know
2161 function backup_userdata_selected($preferences,$modname,$modid) {
2162 return ((empty($preferences->mods[$modname]->instances)
2163 && !empty($preferences->mods[$modname]->userinfo))
2164 || (is_array($preferences->mods[$modname]->instances)
2165 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2166 && !empty($preferences->mods[$modname]->instances[$modid]->userinfo)));
2170 function backup_mod_selected($preferences,$modname,$modid) {
2171 return ((empty($preferences->mods[$modname]->instances)
2172 && !empty($preferences->mods[$modname]->backup))
2173 || (is_array($preferences->mods[$modname]->instances)
2174 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2175 && !empty($preferences->mods[$modname]->instances[$modid]->backup)));
2179 * Checks for the required files/functions to backup every mod
2180 * And check if there is data about it
2182 function backup_fetch_prefs_from_request(&$preferences,&$count,$course) {
2183 global $CFG,$SESSION;
2185 // check to see if it's in the session already
2186 if (!empty($SESSION->backupprefs) && array_key_exists($course->id,$SESSION->backupprefs) && !empty($SESSION->backupprefs[$course->id])) {
2187 $sprefs = $SESSION->backupprefs[$course->id];
2188 $preferences = $sprefs;
2189 // refetch backup_name just in case.
2190 $bn = optional_param('backup_name','',PARAM_FILE);
2191 if (!empty($bn)) {
2192 $preferences->backup_name = $bn;
2194 $count = 1;
2195 return true;
2198 if ($allmods = get_records("modules") ) {
2199 foreach ($allmods as $mod) {
2200 $modname = $mod->name;
2201 $modfile = "$CFG->dirroot/mod/$modname/backuplib.php";
2202 $modbackup = $modname."_backup_mods";
2203 $modbackupone = $modname."_backup_one_mod";
2204 $modcheckbackup = $modname."_check_backup_mods";
2205 if (!file_exists($modfile)) {
2206 continue;
2208 include_once($modfile);
2209 if (!function_exists($modbackup) || !function_exists($modcheckbackup)) {
2210 continue;
2212 $var = "exists_".$modname;
2213 $preferences->$var = true;
2214 $count++;
2215 // check that there are instances and we can back them up individually
2216 if (!count_records('course_modules','course',$course->id,'module',$mod->id) || !function_exists($modbackupone)) {
2217 continue;
2219 $var = 'exists_one_'.$modname;
2220 $preferences->$var = true;
2221 $varname = $modname.'_instances';
2222 $preferences->$varname = get_all_instances_in_course($modname,$course);
2223 foreach ($preferences->$varname as $instance) {
2224 $preferences->mods[$modname]->instances[$instance->id]->name = $instance->name;
2225 $var = 'backup_'.$modname.'_instance_'.$instance->id;
2226 $$var = optional_param($var,0);
2227 $preferences->$var = $$var;
2228 $preferences->mods[$modname]->instances[$instance->id]->backup = $$var;
2229 $var = 'backup_user_info_'.$modname.'_instance_'.$instance->id;
2230 $$var = optional_param($var,0);
2231 $preferences->$var = $$var;
2232 $preferences->mods[$modname]->instances[$instance->id]->userinfo = $$var;
2233 $var = 'backup_'.$modname.'_instances';
2234 $preferences->$var = 1; // we need this later to determine what to display in modcheckbackup.
2237 //Check data
2238 //Check module info
2239 $preferences->mods[$modname]->name = $modname;
2241 $var = "backup_".$modname;
2242 $$var = optional_param( $var,0);
2243 $preferences->$var = $$var;
2244 $preferences->mods[$modname]->backup = $$var;
2246 //Check include user info
2247 $var = "backup_user_info_".$modname;
2248 $$var = optional_param( $var,0);
2249 $preferences->$var = $$var;
2250 $preferences->mods[$modname]->userinfo = $$var;
2255 //Check other parameters
2256 $preferences->backup_metacourse = optional_param('backup_metacourse',1,PARAM_INT);
2257 $preferences->backup_users = optional_param('backup_users',1,PARAM_INT);
2258 $preferences->backup_logs = optional_param('backup_logs',0,PARAM_INT);
2259 $preferences->backup_user_files = optional_param('backup_user_files',1,PARAM_INT);
2260 $preferences->backup_course_files = optional_param('backup_course_files',1,PARAM_INT);
2261 $preferences->backup_messages = optional_param('backup_messages',1,PARAM_INT);
2262 $preferences->backup_course = $course->id;
2263 $preferences->backup_name = required_param('backup_name',PARAM_FILE);
2264 $preferences->backup_unique_code = required_param('backup_unique_code');
2266 // put it (back) in the session
2267 $SESSION->backupprefs[$course->id] = $preferences;
2270 /* Finds all related roles used in course, mod and blocks context
2271 * @param object $preferences
2272 * @param object $course
2273 * @return array of role objects
2275 function backup_fetch_roles($preferences) {
2277 global $CFG;
2278 $contexts = array();
2279 $roles = array();
2281 /// adding course context
2282 $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
2283 $contexts[$coursecontext->id] = $coursecontext;
2285 /// adding mod contexts
2286 $mods = $preferences->mods;
2287 foreach ($mods as $modname => $mod) {
2288 $instances = $mod->instances;
2289 foreach ($instances as $id => $instance) {
2290 // if this type of mod is to be backed up
2291 if ($instance->backup) {
2292 $cm = get_coursemodule_from_instance($modname, $id);
2293 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2294 // put context in array keys
2295 $contexts[$context->id] = $context;
2300 // add all roles assigned at user context
2301 if ($preferences->backup_users) {
2302 if ($users = get_records_sql("SELECT u.old_id, u.table_name,u.info
2303 FROM {$CFG->prefix}backup_ids u
2304 WHERE u.backup_code = '$preferences->backup_unique_code' AND
2305 u.table_name = 'user'")) {
2306 foreach ($users as $user) {
2307 $context = get_context_instance(CONTEXT_USER, $user->old_id);
2308 $contexts[$context->id] = $context;
2314 // add all roles assigned at block context
2315 if ($courseblocks = get_records_sql("SELECT *
2316 FROM {$CFG->prefix}block_instance
2317 WHERE pagetype = '".PAGE_COURSE_VIEW."'
2318 AND pageid = {$preferences->backup_course}")) {
2320 foreach ($courseblocks as $courseblock) {
2322 $context = get_context_instance(CONTEXT_BLOCK, $courseblock->id);
2323 $contexts[$context->id] = $context;
2327 // foreach context, call get_roles_on_exact_context insert into array
2328 foreach ($contexts as $context) {
2329 if ($proles = get_roles_on_exact_context($context)) {
2330 foreach ($proles as $prole) {
2331 $roles[$prole->id] = $prole;
2336 return $roles;
2339 /* function to print xml for overrides */
2340 function write_role_overrides_xml($bf, $context, $startlevel) {
2341 fwrite ($bf, start_tag("ROLES_OVERRIDES", $startlevel, true));
2342 if ($roles = get_roles_with_override_on_context($context)) {
2343 foreach ($roles as $role) {
2344 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2345 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2346 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2347 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2348 fwrite ($bf, start_tag("CAPABILITIES", $startlevel+2, true));
2349 if ($capabilities = get_capabilities_from_role_on_context($role, $context)) {
2350 foreach ($capabilities as $capability) {
2351 fwrite ($bf, start_tag("CAPABILITY", $startlevel+3, true));
2352 fwrite ($bf, full_tag("NAME", $startlevel+4, false, $capability->capability));
2353 fwrite ($bf, full_tag("PERMISSION", $startlevel+4, false, $capability->permission));
2354 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $capability->timemodified));
2355 if (!isset($capability->modifierid)) {
2356 $capability->modifierid = 0;
2358 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $capability->modifierid));
2359 fwrite ($bf, end_tag("CAPABILITY", $startlevel+3, true));
2362 fwrite ($bf, end_tag("CAPABILITIES", $startlevel+2, true));
2363 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2366 fwrite ($bf, end_tag("ROLES_OVERRIDES", $startlevel, true));
2369 /* function to print xml for assignment */
2370 function write_role_assignments_xml($bf, $context, $startlevel) {
2371 /// write role_assign code here
2372 fwrite ($bf, start_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2374 if ($roles = get_roles_with_assignment_on_context($context)) {
2375 foreach ($roles as $role) {
2376 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2377 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2378 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2379 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2380 fwrite ($bf, start_tag("ASSIGNMENTS", $startlevel+2, true));
2381 if ($assignments = get_users_from_role_on_context($role, $context)) {
2382 foreach ($assignments as $assignment) {
2383 fwrite ($bf, start_tag("ASSIGNMENT", $startlevel+3, true));
2384 fwrite ($bf, full_tag("USERID", $startlevel+4, false, $assignment->userid));
2385 fwrite ($bf, full_tag("HIDDEN", $startlevel+4, false, $assignment->hidden));
2386 fwrite ($bf, full_tag("TIMESTART", $startlevel+4, false, $assignment->timestart));
2387 fwrite ($bf, full_tag("TIMEEND", $startlevel+4, false, $assignment->timeend));
2388 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $assignment->timemodified));
2389 if (!isset($assignment->modifierid)) {
2390 $assignment->modifierid = 0;
2392 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $assignment->modifierid));
2393 fwrite ($bf, full_tag("ENROL", $startlevel+4, false, $assignment->enrol));
2394 fwrite ($bf, full_tag("SORTORDER", $startlevel+4, false, $assignment->sortorder));
2395 fwrite ($bf, end_tag("ASSIGNMENT", $startlevel+3, true));
2398 fwrite ($bf, end_tag("ASSIGNMENTS", $startlevel+2, true));
2399 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2402 fwrite ($bf, end_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2406 function backup_execute(&$preferences, &$errorstr) {
2407 global $CFG;
2408 $status = true;
2410 //Check for temp and backup and backup_unique_code directory
2411 //Create them as needed
2412 if (!defined('BACKUP_SILENTLY')) {
2413 echo "<li>".get_string("creatingtemporarystructures").'</li>';
2416 $status = check_and_create_backup_dir($preferences->backup_unique_code);
2417 //Empty dir
2418 if ($status) {
2419 $status = clear_backup_dir($preferences->backup_unique_code);
2422 //Delete old_entries from backup tables
2423 if (!defined('BACKUP_SILENTLY')) {
2424 echo "<li>".get_string("deletingolddata").'</li>';
2426 $status = backup_delete_old_data();
2427 if (!$status) {
2428 if (!defined('BACKUP_SILENTLY')) {
2429 error ("An error occurred deleting old backup data");
2431 else {
2432 $errorstr = "An error occurred deleting old backup data";
2433 return false;
2437 //Create the moodle.xml file
2438 if ($status) {
2439 if (!defined('BACKUP_SILENTLY')) {
2440 echo "<li>".get_string("creatingxmlfile");
2441 //Begin a new list to xml contents
2442 echo "<ul>";
2443 echo "<li>".get_string("writingheader").'</li>';
2445 //Obtain the xml file (create and open) and print prolog information
2446 $backup_file = backup_open_xml($preferences->backup_unique_code);
2447 if (!defined('BACKUP_SILENTLY')) {
2448 echo "<li>".get_string("writinggeneralinfo").'</li>';
2450 //Prints general info about backup to file
2451 if ($backup_file) {
2452 if (!$status = backup_general_info($backup_file,$preferences)) {
2453 if (!defined('BACKUP_SILENTLY')) {
2454 notify("An error occurred while backing up general info");
2456 else {
2457 $errorstr = "An error occurred while backing up general info";
2458 return false;
2462 if (!defined('BACKUP_SILENTLY')) {
2463 echo "<li>".get_string("writingcoursedata");
2464 //Start new ul (for course)
2465 echo "<ul>";
2466 echo "<li>".get_string("courseinfo").'</li>';
2468 //Prints course start (tag and general info)
2469 if ($status) {
2470 if (!$status = backup_course_start($backup_file,$preferences)) {
2471 if (!defined('BACKUP_SILENTLY')) {
2472 notify("An error occurred while backing up course start");
2474 else {
2475 $errorstr = "An error occurred while backing up course start";
2476 return false;
2480 //Metacourse information
2481 if ($status && $preferences->backup_metacourse) {
2482 if (!defined('BACKUP_SILENTLY')) {
2483 echo "<li>".get_string("metacourse").'</li>';
2485 if (!$status = backup_course_metacourse($backup_file,$preferences)) {
2486 if (!defined('BACKUP_SILENTLY')) {
2487 notify("An error occurred while backing up metacourse info");
2489 else {
2490 $errorstr = "An error occurred while backing up metacourse info";
2491 return false;
2495 if (!defined('BACKUP_SILENTLY')) {
2496 echo "<li>".get_string("blocks").'</li>';
2498 //Blocks information
2499 if ($status) {
2500 if (!$status = backup_course_blocks($backup_file,$preferences)) {
2501 if (!defined('BACKUP_SILENTLY')) {
2502 notify("An error occurred while backing up course blocks");
2504 else {
2505 $errorstr = "An error occurred while backing up course blocks";
2506 return false;
2510 if (!defined('BACKUP_SILENTLY')) {
2511 echo "<li>".get_string("sections").'</li>';
2513 //Section info
2514 if ($status) {
2515 if (!$status = backup_course_sections($backup_file,$preferences)) {
2516 if (!defined('BACKUP_SILENTLY')) {
2517 notify("An error occurred while backing up course sections");
2519 else {
2520 $errorstr = "An error occurred while backing up course sections";
2521 return false;
2526 //End course contents (close ul)
2527 if (!defined('BACKUP_SILENTLY')) {
2528 echo "</ul></li>";
2531 //User info
2532 if ($status) {
2533 if (!defined('BACKUP_SILENTLY')) {
2534 echo "<li>".get_string("writinguserinfo").'</li>';
2536 if (!$status = backup_user_info($backup_file,$preferences)) {
2537 if (!defined('BACKUP_SILENTLY')) {
2538 notify("An error occurred while backing up user info");
2540 else {
2541 $errorstr = "An error occurred while backing up user info";
2542 return false;
2547 //If we have selected to backup messages and we are
2548 //doing a SITE backup, let's do it
2549 if ($status && $preferences->backup_messages && $preferences->backup_course == SITEID) {
2550 if (!defined('BACKUP_SILENTLY')) {
2551 echo "<li>".get_string("writingmessagesinfo").'</li>';
2553 if (!$status = backup_messages($backup_file,$preferences)) {
2554 if (!defined('BACKUP_SILENTLY')) {
2555 notify("An error occurred while backing up messages");
2557 else {
2558 $errorstr = "An error occurred while backing up messages";
2559 return false;
2564 //If we have selected to backup quizzes, backup categories and
2565 //questions structure (step 1). See notes on mod/quiz/backuplib.php
2566 if ($status and !empty($preferences->mods['quiz']->backup)) {
2567 if (!defined('BACKUP_SILENTLY')) {
2568 echo "<li>".get_string("writingcategoriesandquestions").'</li>';
2570 require_once($CFG->dirroot.'/mod/quiz/backuplib.php');
2571 if (!$status = backup_question_categories($backup_file,$preferences)) {
2572 if (!defined('BACKUP_SILENTLY')) {
2573 notify("An error occurred while backing up quiz categories");
2575 else {
2576 $errorstr = "An error occurred while backing up quiz categories";
2577 return false;
2582 //Print logs if selected
2583 if ($status) {
2584 if ($preferences->backup_logs) {
2585 if (!defined('BACKUP_SILENTLY')) {
2586 echo "<li>".get_string("writingloginfo").'</li>';
2588 if (!$status = backup_log_info($backup_file,$preferences)) {
2589 if (!defined('BACKUP_SILENTLY')) {
2590 notify("An error occurred while backing up log info");
2592 else {
2593 $errorstr = "An error occurred while backing up log info";
2594 return false;
2600 //Print scales info
2601 if ($status) {
2602 if (!defined('BACKUP_SILENTLY')) {
2603 echo "<li>".get_string("writingscalesinfo").'</li>';
2605 if (!$status = backup_scales_info($backup_file,$preferences)) {
2606 if (!defined('BACKUP_SILENTLY')) {
2607 notify("An error occurred while backing up scales");
2609 else {
2610 $errorstr = "An error occurred while backing up scales";
2611 return false;
2616 //Print groupings info
2617 if ($status) {
2618 if (!defined('BACKUP_SILENTLY')) {
2619 echo "<li>".get_string("writinggroupingsinfo").'</li>';
2621 if (!$status = backup_groupings_info($backup_file,$preferences)) {
2622 if (!defined('BACKUP_SILENTLY')) {
2623 notify("An error occurred while backing up groupings");
2625 else {
2626 $errorstr = "An error occurred while backing up groupings";
2627 return false;
2632 //Print groups info
2633 if ($status) {
2634 if (!defined('BACKUP_SILENTLY')) {
2635 echo "<li>".get_string("writinggroupsinfo").'</li>';
2637 if (!$status = backup_groups_info($backup_file,$preferences)) {
2638 if (!defined('BACKUP_SILENTLY')) {
2639 notify("An error occurred while backing up groups");
2641 else {
2642 $errostr = "An error occurred while backing up groups";
2643 return false;
2648 //Print events info
2649 if ($status) {
2650 if (!defined('BACKUP_SILENTLY')) {
2651 echo "<li>".get_string("writingeventsinfo").'</li>';
2653 if (!$status = backup_events_info($backup_file,$preferences)) {
2654 if (!defined('BACKUP_SILENTLY')) {
2655 notify("An error occurred while backing up events");
2657 else {
2658 $errorstr = "An error occurred while backing up events";
2659 return false;
2664 //Print gradebook info
2665 if ($status) {
2666 if (!defined('BACKUP_SILENTLY')) {
2667 echo "<li>".get_string("writinggradebookinfo").'</li>';
2669 if (!$status = backup_gradebook_info($backup_file,$preferences)) {
2670 if (!defined('BACKUP_SILENTLY')) {
2671 notify("An error occurred while backing up gradebook");
2673 else {
2674 $errorstr = "An error occurred while backing up gradebook";
2675 return false;
2680 //Module info, this unique function makes all the work!!
2681 //db export and module fileis copy
2682 if ($status) {
2683 $mods_to_backup = false;
2684 //Check if we have any mod to backup
2685 foreach ($preferences->mods as $module) {
2686 if ($module->backup) {
2687 $mods_to_backup = true;
2690 //If we have to backup some module
2691 if ($mods_to_backup) {
2692 if (!defined('BACKUP_SILENTLY')) {
2693 echo "<li>".get_string("writingmoduleinfo");
2695 //Start modules tag
2696 if (!$status = backup_modules_start ($backup_file,$preferences)) {
2697 if (!defined('BACKUP_SILENTLY')) {
2698 notify("An error occurred while backing up module info");
2700 else {
2701 $errorstr = "An error occurred while backing up module info";
2702 return false;
2705 //Open ul for module list
2706 if (!defined('BACKUP_SILENTLY')) {
2707 echo "<ul>";
2709 //Iterate over modules and call backup
2710 foreach ($preferences->mods as $module) {
2711 if ($module->backup and $status) {
2712 if (!defined('BACKUP_SILENTLY')) {
2713 echo "<li>".get_string("modulenameplural",$module->name).'</li>';
2715 if (!$status = backup_module($backup_file,$preferences,$module->name)) {
2716 if (!defined('BACKUP_SILENTLY')) {
2717 notify("An error occurred while backing up '$module->name'");
2719 else {
2720 $errorstr = "An error occurred while backing up '$module->name'";
2721 return false;
2726 //Close ul for module list
2727 if (!defined('BACKUP_SILENTLY')) {
2728 echo "</ul></li>";
2730 //Close modules tag
2731 if (!$status = backup_modules_end ($backup_file,$preferences)) {
2732 if (!defined('BACKUP_SILENTLY')) {
2733 notify("An error occurred while finishing the module backups");
2735 else {
2736 $errorstr = "An error occurred while finishing the module backups";
2737 return false;
2743 //Backup course format data, if any.
2744 if (!defined('BACKUP_SILENTLY')) {
2745 echo '<li>'.get_string("courseformatdata").'</li>';
2747 if($status) {
2748 if (!$status = backup_format_data($backup_file,$preferences)) {
2749 if (!defined('BACKUP_SILENTLY')) {
2750 notify("An error occurred while backing up the course format data");
2752 else {
2753 $errorstr = "An error occurred while backing up the course format data";
2754 return false;
2759 //Prints course end
2760 if ($status) {
2761 if (!$status = backup_course_end($backup_file,$preferences)) {
2762 if (!defined('BACKUP_SILENTLY')) {
2763 notify("An error occurred while closing the course backup");
2765 else {
2766 $errorstr = "An error occurred while closing the course backup";
2767 return false;
2771 //Close the xml file and xml data
2772 if ($backup_file) {
2773 backup_close_xml($backup_file);
2776 //End xml contents (close ul)
2777 if (!defined('BACKUP_SILENTLY')) {
2778 echo "</ul></li>";
2782 //Now, if selected, copy user files
2783 if ($status) {
2784 if ($preferences->backup_user_files) {
2785 if (!defined('BACKUP_SILENTLY')) {
2786 echo "<li>".get_string("copyinguserfiles").'</li>';
2788 if (!$status = backup_copy_user_files ($preferences)) {
2789 if (!defined('BACKUP_SILENTLY')) {
2790 notify("An error occurred while copying user files");
2792 else {
2793 $errorstr = "An error occurred while copying user files";
2794 return false;
2800 //Now, if selected, copy course files
2801 if ($status) {
2802 if ($preferences->backup_course_files) {
2803 if (!defined('BACKUP_SILENTLY')) {
2804 echo "<li>".get_string("copyingcoursefiles").'</li>';
2806 if (!$status = backup_copy_course_files ($preferences)) {
2807 if (!defined('BACKUP_SILENTLY')) {
2808 notify("An error occurred while copying course files");
2810 else {
2811 $errorstr = "An error occurred while copying course files";
2812 return false;
2818 //Now, zip all the backup directory contents
2819 if ($status) {
2820 if (!defined('BACKUP_SILENTLY')) {
2821 echo "<li>".get_string("zippingbackup").'</li>';
2823 if (!$status = backup_zip ($preferences)) {
2824 if (!defined('BACKUP_SILENTLY')) {
2825 notify("An error occurred while zipping the backup");
2827 else {
2828 $errorstr = "An error occurred while zipping the backup";
2829 return false;
2834 //Now, copy the zip file to course directory
2835 if ($status) {
2836 if (!defined('BACKUP_SILENTLY')) {
2837 echo "<li>".get_string("copyingzipfile").'</li>';
2839 if (!$status = copy_zip_to_course_dir ($preferences)) {
2840 if (!defined('BACKUP_SILENTLY')) {
2841 notify("An error occurred while copying the zip file to the course directory");
2843 else {
2844 $errorstr = "An error occurred while copying the zip file to the course directory";
2845 return false;
2850 //Now, clean temporary data (db and filesystem)
2851 if ($status) {
2852 if (!defined('BACKUP_SILENTLY')) {
2853 echo "<li>".get_string("cleaningtempdata").'</li>';
2855 if (!$status = clean_temp_data ($preferences)) {
2856 if (!defined('BACKUP_SILENTLY')) {
2857 notify("An error occurred while cleaning up temporary data");
2859 else {
2860 $errorstr = "An error occurred while cleaning up temporary data";
2861 return false;
2866 return $status;
2870 * This function generates the default zipfile name for a backup
2871 * based on the course id and the unique code.
2873 * @param object $course course object
2874 * @param string $backup_unique_code (optional, if left out current timestamp used)
2877 * @return string filename (excluding path information)
2879 function backup_get_zipfile_name($course, $backup_unique_code='') {
2881 if (empty($backup_unique_code)) {
2882 $backup_unique_code = time();
2885 //Calculate the backup word
2886 //Take off some characters in the filename !!
2887 $takeoff = array(" ", ":", "/", "\\", "|");
2888 $backup_word = str_replace($takeoff,"_",moodle_strtolower(get_string("backupfilename")));
2889 //If non-translated, use "backup"
2890 if (substr($backup_word,0,1) == "[") {
2891 $backup_word= "backup";
2894 //Calculate the date format string
2895 $backup_date_format = str_replace(" ","_",get_string("backupnameformat"));
2896 //If non-translated, use "%Y%m%d-%H%M"
2897 if (substr($backup_date_format,0,1) == "[") {
2898 $backup_date_format = "%%Y%%m%%d-%%H%%M";
2901 //Calculate the shortname
2902 $backup_shortname = clean_filename($course->shortname);
2903 if (empty($backup_shortname) or $backup_shortname == '_' ) {
2904 $backup_shortname = $course->id;
2907 //Calculate the final backup filename
2908 //The backup word
2909 $backup_name = $backup_word."-";
2910 //The shortname
2911 $backup_name .= moodle_strtolower($backup_shortname)."-";
2912 //The date format
2913 $backup_name .= userdate(time(),$backup_date_format,99,false);
2914 //The extension
2915 $backup_name .= ".zip";
2916 //And finally, clean everything
2917 $backup_name = clean_filename($backup_name);
2919 return $backup_name;
2924 * This function adds on the standard items to the preferences
2925 * Like moodle version and backup version
2927 * @param object $preferences existing preferences object.
2928 * (passed by reference)
2930 function backup_add_static_preferences(&$preferences) {
2931 global $CFG;
2932 $preferences->moodle_version = $CFG->version;
2933 $preferences->moodle_release = $CFG->release;
2934 $preferences->backup_version = $CFG->backup_version;
2935 $preferences->backup_release = $CFG->backup_release;