MDL-10234
[moodle-linuxchix.git] / backup / backuplib.php
blob5e825f105a1f0c57bd133177708dba11c1b2a747
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 // see if ALL grade items of type mod of this course are being backed up
1367 // if not, we do not need to backup grade category and associated grade items/grades
1368 $backupall = true;
1370 if ($grade_items = get_records_sql("SELECT * FROM {$CFG->prefix}grade_items
1371 WHERE courseid = $preferences->backup_course
1372 ORDER BY sortorder ASC")) {
1373 foreach ($grade_items as $grade_item) {
1375 // do not restore if this grade_item is a mod, and
1376 if ($grade_item->itemtype == 'mod') {
1378 // get module information
1379 // if no user data selected, we skip this grade_item
1380 if (!backup_userdata_selected($preferences,$grade_item->itemmodule,$grade_item->iteminstance)) {
1381 //print_object($grade_item);
1382 $backupall = false;
1383 break;
1389 //Gradebook header
1390 fwrite ($bf,start_tag("GRADEBOOK",2,true));
1392 // Now backup grade_item (inside grade_category)
1393 if ($backupall) {
1394 $status = backup_gradebook_category_info($bf,$preferences);
1396 $status = backup_gradebook_item_info($bf,$preferences, $backupall);
1397 $status = backup_gradebook_outcomes_info($bf, $preferences);
1398 // back up grade outcomes
1400 //Gradebook footer
1401 $status = fwrite ($bf,end_tag("GRADEBOOK",2,true));
1402 return $status;
1406 function backup_gradebook_category_info($bf,$preferences) {
1407 global $CFG;
1409 $status = true;
1411 //Output grade_category
1413 // getting grade categories, but make sure parents come before children
1414 // because when we do restore, we need to recover the parents first
1415 // we do this by getting the lowest depth first
1416 $grade_categories = get_records_sql("SELECT * FROM {$CFG->prefix}grade_categories
1417 WHERE courseid = $preferences->backup_course
1418 ORDER BY depth ASC");
1419 if ($grade_categories) {
1420 //Begin grade_categories tag
1421 fwrite ($bf,start_tag("GRADE_CATEGORIES",3,true));
1422 //Iterate for each category
1423 foreach ($grade_categories as $grade_category) {
1424 //Begin grade_category
1425 fwrite ($bf,start_tag("GRADE_CATEGORY",4,true));
1426 //Output individual fields
1427 fwrite ($bf,full_tag("ID",5,false,$grade_category->id));
1429 // not keeping path and depth because they can be derived
1430 fwrite ($bf,full_tag("PARENT",5,false,$grade_category->parent));
1431 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_category->fullname));
1432 fwrite ($bf,full_tag("AGGREGATION",5,false,$grade_category->aggregation));
1433 fwrite ($bf,full_tag("KEEPHIGH",5,false,$grade_category->keephigh));
1434 fwrite ($bf,full_tag("DROPLOW",5,false,$grade_category->droplow));
1435 fwrite ($bf,full_tag("HIDDEN",5,false,$grade_category->hidden));
1437 //End grade_category
1438 fwrite ($bf,end_tag("GRADE_CATEGORY",4,true));
1440 //End grade_categories tag
1441 $status = fwrite ($bf,end_tag("GRADE_CATEGORIES",3,true));
1444 return $status;
1449 //Backup gradebook_item (called from backup_gradebook_info
1450 function backup_gradebook_item_info($bf,$preferences, $backupall) {
1452 global $CFG;
1454 $status = true;
1456 // get all the grade_items, ordered by sort order since upon restoring, it is not always
1457 // possible to use the same sort order. We could at least preserve the sortorder by restoring
1458 // grade_items in the original sortorder
1459 if ($grade_items = get_records_sql("SELECT * FROM {$CFG->prefix}grade_items
1460 WHERE courseid = $preferences->backup_course
1461 ORDER BY sortorder ASC")) {
1463 //Begin grade_items tag
1464 fwrite ($bf,start_tag("GRADE_ITEMS",3,true));
1465 //Iterate for each item
1466 foreach ($grade_items as $grade_item) {
1468 // do not restore if this grade_item is a mod, and
1469 if ($grade_item->itemtype == 'mod') {
1471 // if no user data selected, we skip this grade_item
1472 if (!backup_userdata_selected($preferences,$grade_item->itemmodule,$grade_item->iteminstance)) {
1473 continue;
1475 } else if ($grade_item->itemtype == 'category') {
1476 // if not all grade items are being backed up
1477 // we ignore this type of grade_item and grades associated
1478 if (!$backupall) {
1479 continue;
1483 //Begin grade_item
1484 fwrite ($bf,start_tag("GRADE_ITEM",4,true));
1485 //Output individual fields
1487 fwrite ($bf,full_tag("ID",5,false,$grade_item->id));
1488 fwrite ($bf,full_tag("ITEMNAME",5,false,$grade_item->itemname));
1489 fwrite ($bf,full_tag("ITEMTYPE",5,false,$grade_item->itemtype));
1490 fwrite ($bf,full_tag("ITEMMODULE",5,false,$grade_item->itemmodule));
1491 fwrite ($bf,full_tag("ITEMINSTANCE",5,false,$grade_item->iteminstance));
1492 fwrite ($bf,full_tag("ITEMNUMBER",5,false,$grade_item->itemnumber));
1493 fwrite ($bf,full_tag("ITEMINFO",5,false,$grade_item->iteminfo));
1494 fwrite ($bf,full_tag("IDNUMBER",5,false,$grade_item->idnumber));
1495 // use [idnumber] in calculation instead of [#giXXX#]
1496 fwrite ($bf,full_tag("CALCULATION",5,false,$grade_item->get_caclulation()));
1497 fwrite ($bf,full_tag("GRADEMAX",5,false,$grade_item->grademax));
1498 fwrite ($bf,full_tag("GRADEMIN",5,false,$grade_item->grademin));
1499 fwrite ($bf,full_tag("SCALEID",5,false,$grade_item->scaleid));
1500 fwrite ($bf,full_tag("OUTCOMEID",5,false,$grade_item->outcomeid));
1501 fwrite ($bf,full_tag("GRADEPASS",5,false,$grade_item->gradepass));
1502 fwrite ($bf,full_tag("MULTFACTOR",5,false,$grade_item->multfactor));
1503 fwrite ($bf,full_tag("PLUSFACTOR",5,false,$grade_item->plusfactor));
1504 fwrite ($bf,full_tag("HIDDEN",5,false,$grade_item->hidden));
1505 fwrite ($bf,full_tag("LOCKED",5,false,$grade_item->locked));
1506 fwrite ($bf,full_tag("LOCKTIME",5,false,$grade_item->locktime));
1508 // back up the other stuff here
1509 $status = backup_gradebook_grades_info($bf,$preferences,$grade_item->id);
1510 $status = backup_gradebook_grades_history_info($bf,$preferences,$grade_item->id);
1511 $status = backup_gradebook_grades_text_info($bf,$preferences,$grade_item->id);
1513 //End grade_item
1514 fwrite ($bf,end_tag("GRADE_ITEM",4,true));
1516 //End grade_items tag
1517 $status = fwrite ($bf,end_tag("GRADE_ITEMS",3,true));
1520 return $status;
1522 //Backup gradebook_item (called from backup_gradebook_info
1524 function backup_gradebook_outcomes_info($bf,$preferences) {
1526 global $CFG;
1528 $status = true;
1530 // get all the grade_items
1531 // might need to do it using sortorder
1532 if ($grade_outcomes = get_records('grade_outcomes', 'courseid', $preferences->backup_course)) {
1534 //Begin grade_items tag
1535 fwrite ($bf,start_tag("GRADE_OUTCOMES",3,true));
1536 //Iterate for each item
1537 foreach ($grade_outcomes as $grade_outcome) {
1538 //Begin grade_item
1539 fwrite ($bf,start_tag("GRADE_OUTCOME",4,true));
1540 //Output individual fields
1542 fwrite ($bf,full_tag("ID",5,false,$grade_outcome->id));
1543 fwrite ($bf,full_tag("SHORTNAME",5,false,$grade_outcome->shortname));
1544 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_outcome->fullname));
1545 fwrite ($bf,full_tag("SCALEID",5,false,$grade_outcome->scaleid));
1546 fwrite ($bf,full_tag("USERMODIFIED",5,false,$grade_outcome->usermodified));
1548 //End grade_item
1549 fwrite ($bf,end_tag("GRADE_OUTCOME",4,true));
1551 //End grade_items tag
1552 $status = fwrite ($bf,end_tag("GRADE_OUTCOMES",3,true));
1555 return $status;
1558 function backup_gradebook_grades_info($bf,$preferences, $itemid) {
1560 global $CFG;
1562 $status = true;
1564 // find all grades belonging to this item
1565 if ($grades = get_records('grade_grades', 'itemid', $itemid)) {
1566 fwrite ($bf,start_tag("GRADE_GRADES",5,true));
1567 foreach ($grades as $grade) {
1568 fwrite ($bf,start_tag("GRADE",6,true));
1569 fwrite ($bf,full_tag("ID",7,false,$grade->id));
1570 fwrite ($bf,full_tag("USERID",7,false,$grade->userid));
1571 fwrite ($bf,full_tag("RAWGRADE",7,false,$grade->rawgrade));
1572 fwrite ($bf,full_tag("RAWGRADEMAX",7,false,$grade->rawgrademax));
1573 fwrite ($bf,full_tag("RAWGRADEMIN",7,false,$grade->rawgrademin));
1574 fwrite ($bf,full_tag("RAWSCALEID",7,false,$grade->rawscaleid));
1575 fwrite ($bf,full_tag("USERMODIFIED",7,false,$grade->usermodified));
1576 fwrite ($bf,full_tag("FINALGRADE",7,false,$grade->finalgrade));
1577 fwrite ($bf,full_tag("HIDDEN",7,false,$final->hidden));
1578 fwrite ($bf,full_tag("LOCKED",7,false,$final->locked));
1579 fwrite ($bf,full_tag("LOCKTIME",7,false,$final->locktime));
1580 fwrite ($bf,full_tag("EXPORTED",7,false,$final->exported));
1581 fwrite ($bf,end_tag("GRADE_RAW",6,true));
1583 $stauts = fwrite ($bf,end_tag("GRADE_GRADES",5,true));
1585 return $status;
1588 function backup_gradebook_grades_text_info($bf, $preferences, $itemid) {
1590 global $CFG;
1592 $status = true;
1594 // find all grade texts belonging to this item
1595 if ($texts = get_records('grade_grades_text', 'itemid', $itemid)) {
1596 fwrite ($bf,start_tag("GRADE_GRADES_TEXT",5,true));
1597 foreach ($texts as $text) {
1598 fwrite ($bf,start_tag("GRADE_TEXT",6,true));
1599 fwrite ($bf,full_tag("ID",7,false,$text->id));
1600 fwrite ($bf,full_tag("GRADEID",7,false,$text->gradeid));
1601 fwrite ($bf,full_tag("INFORMATION",7,false,$text->information));
1602 fwrite ($bf,full_tag("INFORMATIONFORMAT",7,false,$text->informationformat));
1603 fwrite ($bf,full_tag("FEEDBACK",7,false,$text->feedback));
1604 fwrite ($bf,full_tag("FEEDBACKFORMAT",7,false,$text->feedbackformat));
1605 fwrite ($bf,end_tag("GRADE_TEXT",6,true));
1607 $stauts = fwrite ($bf,end_tag("GRADE_GRADES_TEXT",5,true));
1609 return $status;
1612 function backup_gradebook_grades_history_info($bf, $preferences, $itemid) {
1614 global $CFG;
1616 $status = true;
1618 // find all grade history belonging to this item
1619 if ($histories = get_records('grade_history', 'itemid', $itemid)) {
1620 fwrite ($bf,start_tag("GRADE_GRADES_HISTORY",5,true));
1621 foreach ($histories as $history) {
1622 fwrite ($bf,start_tag("GRADE_HISTORY",6,true));
1623 fwrite ($bf,full_tag("ID",7,false,$history->id));
1624 fwrite ($bf,full_tag("USERID",7,false,$history->userid));
1625 fwrite ($bf,full_tag("OLDGRADE",7,false,$history->oldgrade));
1626 fwrite ($bf,full_tag("NEWGRADE",7,false,$history->newgrade));
1627 fwrite ($bf,full_tag("NOTE",7,false,$history->note));
1628 fwrite ($bf,full_tag("HOWMODIFIED",7,false,$history->howmodified));
1629 fwrite ($bf,full_tag("USERMODIFIED",7,false,$history->usermodified));
1630 fwrite ($bf,end_tag("GRADE_HISTORY",6,true));
1632 $stauts = fwrite ($bf,end_tag("GRADE_GRADES_HISTORY",5,true));
1634 return $status;
1637 //Backup scales info (common and course scales)
1638 function backup_scales_info($bf,$preferences) {
1640 global $CFG;
1642 $status = true;
1644 //Counter, points to current record
1645 $counter = 0;
1647 //Get scales (common and course scales)
1648 $scales = get_records_sql("SELECT id, courseid, userid, name, scale, description, timemodified
1649 FROM {$CFG->prefix}scale
1650 WHERE courseid = '0' or courseid = $preferences->backup_course");
1652 //Copy only used scales to $backupscales. They will be in backup (unused no). See Bug 1223.
1653 $backupscales = array();
1654 if ($scales) {
1655 foreach ($scales as $scale) {
1656 if (course_scale_used($preferences->backup_course, $scale->id)) {
1657 $backupscales[] = $scale;
1662 //Pring scales header
1663 if ($backupscales) {
1664 //Pring scales header
1665 fwrite ($bf,start_tag("SCALES",2,true));
1666 //Iterate
1667 foreach ($backupscales as $scale) {
1668 //Begin scale tag
1669 fwrite ($bf,start_tag("SCALE",3,true));
1670 //Output scale tag
1671 fwrite ($bf,full_tag("ID",4,false,$scale->id));
1672 fwrite ($bf,full_tag("COURSEID",4,false,$scale->courseid));
1673 fwrite ($bf,full_tag("USERID",4,false,$scale->userid));
1674 fwrite ($bf,full_tag("NAME",4,false,$scale->name));
1675 fwrite ($bf,full_tag("SCALETEXT",4,false,$scale->scale));
1676 fwrite ($bf,full_tag("DESCRIPTION",4,false,$scale->description));
1677 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$scale->timemodified));
1678 //End scale tag
1679 fwrite ($bf,end_tag("SCALE",3,true));
1681 //End scales tag
1682 $status = fwrite ($bf,end_tag("SCALES",2,true));
1684 return $status;
1687 //Backup events info (course events)
1688 function backup_events_info($bf,$preferences) {
1690 global $CFG;
1692 $status = true;
1694 //Counter, points to current record
1695 $counter = 0;
1697 //Get events (course events)
1698 $events = get_records_select("event","courseid='$preferences->backup_course' AND instance='0'","id");
1700 //Pring events header
1701 if ($events) {
1702 //Pring events header
1703 fwrite ($bf,start_tag("EVENTS",2,true));
1704 //Iterate
1705 foreach ($events as $event) {
1706 //Begin event tag
1707 fwrite ($bf,start_tag("EVENT",3,true));
1708 //Output event tag
1709 fwrite ($bf,full_tag("ID",4,false,$event->id));
1710 fwrite ($bf,full_tag("NAME",4,false,$event->name));
1711 fwrite ($bf,full_tag("DESCRIPTION",4,false,$event->description));
1712 fwrite ($bf,full_tag("FORMAT",4,false,$event->format));
1713 fwrite ($bf,full_tag("GROUPID",4,false,$event->groupid));
1714 fwrite ($bf,full_tag("USERID",4,false,$event->userid));
1715 fwrite ($bf,full_tag("REPEATID",4,false,$event->repeatid));
1716 fwrite ($bf,full_tag("EVENTTYPE",4,false,$event->eventtype));
1717 fwrite ($bf,full_tag("TIMESTART",4,false,$event->timestart));
1718 fwrite ($bf,full_tag("TIMEDURATION",4,false,$event->timeduration));
1719 fwrite ($bf,full_tag("VISIBLE",4,false,$event->visible));
1720 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$event->timemodified));
1721 //End event tag
1722 fwrite ($bf,end_tag("EVENT",3,true));
1724 //End events tag
1725 $status = fwrite ($bf,end_tag("EVENTS",2,true));
1727 return $status;
1730 //Backup groups info
1731 function backup_groups_info($bf,$preferences) {
1733 global $CFG;
1735 $status = true;
1736 $status2 = true;
1738 //Get groups
1739 $groups = get_groups($preferences->backup_course); //TODO:check.
1741 //Pring groups header
1742 if ($groups) {
1743 //Pring groups header
1744 fwrite ($bf,start_tag("GROUPS",2,true));
1745 //Iterate
1746 foreach ($groups as $group) {
1747 //Begin group tag
1748 fwrite ($bf,start_tag("GROUP",3,true));
1749 //Output group contents
1750 fwrite ($bf,full_tag("ID",4,false,$group->id));
1751 ///fwrite ($bf,full_tag("COURSEID",4,false,$group->courseid));
1752 fwrite ($bf,full_tag("NAME",4,false,$group->name));
1753 fwrite ($bf,full_tag("DESCRIPTION",4,false,$group->description));
1754 fwrite ($bf,full_tag("ENROLMENTKEY",4,false,$group->enrolmentkey)); //TODO:
1755 fwrite ($bf,full_tag("LANG",4,false,$group->lang));
1756 fwrite ($bf,full_tag("THEME",4,false,$group->theme));
1757 fwrite ($bf,full_tag("PICTURE",4,false,$group->picture));
1758 fwrite ($bf,full_tag("HIDEPICTURE",4,false,$group->hidepicture));
1759 fwrite ($bf,full_tag("TIMECREATED",4,false,$group->timecreated));
1760 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$group->timemodified));
1762 //Now, backup groups_members, only if users are included
1763 if ($preferences->backup_users != 2) {
1764 $status2 = backup_groups_members_info($bf,$preferences,$group->id);
1767 //End group tag
1768 fwrite ($bf,end_tag("GROUP",3,true));
1770 //End groups tag
1771 $status = fwrite ($bf,end_tag("GROUPS",2,true));
1773 //Now save group_files
1774 if ($status && $status2) {
1775 $status2 = backup_copy_group_files($preferences);
1778 return ($status && $status2);
1781 //Backup groups_members info
1782 function backup_groups_members_info($bf,$preferences,$groupid) {
1784 global $CFG;
1786 $status = true;
1788 //Get groups_members
1789 $groups_members = groups_get_member_records($groupid);
1791 //Pring groups_members header
1792 if ($groups_members) {
1793 //Pring groups_members header
1794 fwrite ($bf,start_tag("MEMBERS",4,true));
1795 //Iterate
1796 foreach ($groups_members as $group_member) {
1797 //Begin group_member tag
1798 fwrite ($bf,start_tag("MEMBER",5,true));
1799 //Output group_member contents
1800 fwrite ($bf,full_tag("USERID",6,false,$group_member->userid));
1801 fwrite ($bf,full_tag("TIMEADDED",6,false,$group_member->timeadded));
1802 //End group_member tag
1803 fwrite ($bf,end_tag("MEMBER",5,true));
1805 //End groups_members tag
1806 $status = fwrite ($bf,end_tag("MEMBERS",4,true));
1808 return $status;
1811 //Backup groupings info
1812 function backup_groupings_info($bf,$preferences) {
1814 global $CFG;
1816 $status = true;
1817 $status2 = true;
1819 //Get groups
1820 $groupings = groups_get_grouping_records($preferences->backup_course);
1822 //Pring groups header
1823 if ($groupings) {
1824 //Pring groups header
1825 fwrite ($bf,start_tag("GROUPINGS",2,true));
1826 //Iterate
1827 foreach ($groupings as $grouping) {
1828 //Begin group tag
1829 fwrite ($bf,start_tag("GROUPING",3,true));
1830 //Output group contents
1831 fwrite ($bf,full_tag("ID",4,false,$grouping->id));
1832 fwrite ($bf,full_tag("NAME",4,false,$grouping->name));
1833 fwrite ($bf,full_tag("DESCRIPTION",4,false,$grouping->description));
1834 fwrite ($bf,full_tag("TIMECREATED",4,false,$grouping->timecreated));
1836 $status2 = backup_groupids_info($bf,$preferences,$grouping->id);
1838 //End group tag
1839 fwrite ($bf,end_tag("GROUPING",3,true));
1841 //End groups tag
1842 $status = fwrite ($bf,end_tag("GROUPINGS",2,true));
1844 //(Now save grouping_files)
1846 return ($status && $status2);
1849 //Backup groupings-groups info
1850 function backup_groupids_info($bf,$preferences,$groupingid) {
1852 global $CFG;
1854 $status = true;
1856 //Get groups_members
1857 $grouping_groups = groups_get_groups_in_grouping_records($groupingid) ;
1859 //Pring groups_members header
1860 if ($grouping_groups) {
1861 //Pring groups_members header
1862 fwrite ($bf,start_tag("GROUPS",4,true));
1863 //Iterate
1864 foreach ($grouping_groups as $group2) {
1865 //Begin group tag
1866 fwrite ($bf,start_tag("GROUP",5,true));
1867 //Output group_member contents
1868 fwrite ($bf,full_tag("GROUPID",6,false,$group2->groupid));
1869 fwrite ($bf,full_tag("TIMEADDED",6,false,$group2->timeadded)); //TODO:
1870 //End group tag
1871 fwrite ($bf,end_tag("GROUP",5,true));
1873 //End groups_members tag
1874 $status = fwrite ($bf,end_tag("GROUPS",4,true));
1876 return $status;
1879 //Start the modules tag
1880 function backup_modules_start ($bf,$preferences) {
1882 return fwrite ($bf,start_tag("MODULES",2,true));
1885 //End the modules tag
1886 function backup_modules_end ($bf,$preferences) {
1888 return fwrite ($bf,end_tag("MODULES",2,true));
1891 //This function makes all the necesary calls to every mod
1892 //to export itself and its files !!!
1893 function backup_module($bf,$preferences,$module) {
1895 global $CFG;
1897 $status = true;
1899 require_once($CFG->dirroot.'/mod/'.$module.'/backuplib.php');
1901 if (isset($preferences->mods[$module]->instances)
1902 && is_array($preferences->mods[$module]->instances)) {
1903 $onemodbackup = $module.'_backup_one_mod';
1904 if (function_exists($onemodbackup)) {
1905 foreach ($preferences->mods[$module]->instances as $instance => $object) {
1906 if (!empty($object->backup)) {
1907 $status = $onemodbackup($bf,$preferences,$instance);
1910 } else {
1911 $status = false;
1913 } else { // whole module.
1914 //First, re-check if necessary functions exists
1915 $modbackup = $module."_backup_mods";
1916 if (function_exists($modbackup)) {
1917 //Call the function
1918 $status = $modbackup($bf,$preferences);
1919 } else {
1920 //Something was wrong. Function should exist.
1921 $status = false;
1925 return $status;
1929 //This function encode things to make backup multi-site fully functional
1930 //It does this conversions:
1931 // - $CFG->wwwroot/file.php/courseid ------------------> $@FILEPHP@$ (slasharguments links)
1932 // - $CFG->wwwroot/file.php?file=/courseid ------------> $@FILEPHP@$ (non-slasharguments links)
1933 // - Every module xxxx_encode_content_links() is executed too
1935 function backup_encode_absolute_links($content) {
1937 global $CFG,$preferences;
1939 //Use one static variable to cache all the require_once calls that,
1940 //under PHP5 seems to increase load too much, and we are requiring
1941 //them here thousands of times (one per content). MDL-8700.
1942 //Once fixed by PHP, we'll delete this hack
1944 static $includedfiles;
1945 if (!isset($includedfiles)) {
1946 $includedfiles = array();
1949 //Check if preferences is ok. If it isn't set, we are
1950 //in a scheduled_backup to we are able to get a copy
1951 //from CFG->backup_preferences
1952 if (!isset($preferences)) {
1953 $mypreferences = $CFG->backup_preferences;
1954 } else {
1955 //We are in manual backups so global preferences must exist!!
1956 $mypreferences = $preferences;
1959 //First, we check for every call to file.php inside the course
1960 $search = array($CFG->wwwroot.'/file.php/'.$mypreferences->backup_course,
1961 $CFG->wwwroot.'/file.php?file=/'.$mypreferences->backup_course);
1963 $replace = array('$@FILEPHP@$','$@FILEPHP@$');
1965 $result = str_replace($search,$replace,$content);
1967 foreach ($mypreferences->mods as $name => $info) {
1968 /// We only include the corresponding backuplib.php if it hasn't been included before
1969 /// This will save some load under PHP5. MDL-8700.
1970 /// Once fixed by PHP, we'll delete this hack
1971 if (!in_array($name, $includedfiles)) {
1972 include_once("$CFG->dirroot/mod/$name/backuplib.php");
1973 $includedfiles[] = $name;
1975 //Check if the xxxx_encode_content_links exists
1976 $function_name = $name."_encode_content_links";
1977 if (function_exists($function_name)) {
1978 $result = $function_name($result,$mypreferences);
1982 if ($result != $content) {
1983 debugging('<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />');
1986 return $result;
1989 //This function copies all the needed files under the "users" directory to the "user_files"
1990 //directory under temp/backup
1991 function backup_copy_user_files ($preferences) {
1993 global $CFG;
1995 $status = true;
1997 //First we check to "user_files" exists and create it as necessary
1998 //in temp/backup/$backup_code dir
1999 $status = check_and_create_user_files_dir($preferences->backup_unique_code);
2001 //Now iterate over directories under "users" to check if that user must be
2002 //copied to backup
2004 $rootdir = $CFG->dataroot."/users";
2005 //Check if directory exists
2006 if (is_dir($rootdir)) {
2007 $list = list_directories ($rootdir);
2008 if ($list) {
2009 //Iterate
2010 foreach ($list as $dir) {
2011 //Look for dir like username in backup_ids
2012 $data = get_record ("backup_ids","backup_code",$preferences->backup_unique_code,
2013 "table_name","user",
2014 "old_id",$dir);
2015 //If exists, copy it
2016 if ($data) {
2017 $status = backup_copy_file($rootdir."/".$dir,
2018 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/user_files/".$dir);
2024 return $status;
2027 //This function copies all the needed files under the "groups" directory to the "group_files"
2028 //directory under temp/backup
2029 function backup_copy_group_files ($preferences) {
2031 global $CFG;
2033 $status = true;
2035 //First we check if "group_files" exists and create it as necessary
2036 //in temp/backup/$backup_code dir
2037 $status = check_and_create_group_files_dir($preferences->backup_unique_code);
2039 //Now iterate over directories under "groups" to check if that user must be
2040 //copied to backup
2042 $rootdir = $CFG->dataroot.'/groups';
2043 //Check if directory exists
2044 if (is_dir($rootdir)) {
2045 $list = list_directories ($rootdir);
2046 if ($list) {
2047 //Iterate
2048 foreach ($list as $dir) {
2049 //Look for dir like group in groups table
2050 $data = groups_group_belongs_to_course($dir, $preferences->backup_course);
2051 //TODO:check. get_record ('groups', 'courseid', $preferences->backup_course,'id',$dir);
2052 //If exists, copy it
2053 if ($data) {
2054 $status = backup_copy_file($rootdir."/".$dir,
2055 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/group_files/".$dir);
2060 return $status;
2063 //This function copies all the course files under the course directory (except the moddata
2064 //directory to the "course_files" directory under temp/backup
2065 function backup_copy_course_files ($preferences) {
2067 global $CFG;
2069 $status = true;
2071 //First we check to "course_files" exists and create it as necessary
2072 //in temp/backup/$backup_code dir
2073 $status = check_and_create_course_files_dir($preferences->backup_unique_code);
2075 //Now iterate over files and directories except $CFG->moddata and backupdata to be
2076 //copied to backup
2078 $rootdir = $CFG->dataroot."/".$preferences->backup_course;
2080 $name_moddata = $CFG->moddata;
2081 $name_backupdata = "backupdata";
2082 //Check if directory exists
2083 if (is_dir($rootdir)) {
2084 $list = list_directories_and_files ($rootdir);
2085 if ($list) {
2086 //Iterate
2087 foreach ($list as $dir) {
2088 if ($dir !== $name_moddata and $dir !== $name_backupdata) {
2089 $status = backup_copy_file($rootdir."/".$dir,
2090 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/course_files/".$dir);
2095 return $status;
2098 //This function creates the zip file containing all the backup info
2099 //moodle.xml, moddata, user_files, course_files.
2100 //The zipped file is created in the backup directory and named with
2101 //the "oficial" name of the backup
2102 //It uses "pclzip" if available or system "zip" (unix only)
2103 function backup_zip ($preferences) {
2105 global $CFG;
2107 $status = true;
2109 //Base dir where everything happens
2110 $basedir = cleardoubleslashes($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code);
2111 //Backup zip file name
2112 $name = $preferences->backup_name;
2113 //List of files and directories
2114 $filelist = list_directories_and_files ($basedir);
2116 //Convert them to full paths
2117 $files = array();
2118 foreach ($filelist as $file) {
2119 $files[] = "$basedir/$file";
2122 $status = zip_files($files, "$basedir/$name");
2124 //echo "<br/>Status: ".$status; //Debug
2125 return $status;
2129 //This function copies the final zip to the course dir
2130 function copy_zip_to_course_dir ($preferences) {
2132 global $CFG;
2134 $status = true;
2136 //Define zip location (from)
2137 $from_zip_file = $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/".$preferences->backup_name;
2139 //Initialise $to_zip_file
2140 $to_zip_file="";
2142 //If $preferences->backup_destination isn't empty, then copy to custom directory
2143 if (!empty($preferences->backup_destination)) {
2144 $to_zip_file = $preferences->backup_destination."/".$preferences->backup_name;
2145 } else {
2146 //Define zip destination (course dir)
2147 $to_zip_file = $CFG->dataroot."/".$preferences->backup_course;
2149 //echo "<p>From: ".$from_zip_file."<br />"; //Debug
2151 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2153 //Checks course dir exists
2154 $status = check_dir_exists($to_zip_file,true);
2156 //Define zip destination (backup dir)
2157 $to_zip_file = $to_zip_file."/backupdata";
2159 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2161 //Checks backup dir exists
2162 $status = check_dir_exists($to_zip_file,true);
2164 //Define zip destination (zip file)
2165 $to_zip_file = $to_zip_file."/".$preferences->backup_name;
2168 //echo "<p>To: ".$to_zip_file."<br />"; //Debug
2170 //Copy zip file
2171 if ($status) {
2172 $status = backup_copy_file ($from_zip_file,$to_zip_file);
2175 return $status;
2178 /**
2179 * compatibility function
2180 * with new granular backup
2181 * we need to know
2183 function backup_userdata_selected($preferences,$modname,$modid) {
2184 return ((empty($preferences->mods[$modname]->instances)
2185 && !empty($preferences->mods[$modname]->userinfo))
2186 || (is_array($preferences->mods[$modname]->instances)
2187 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2188 && !empty($preferences->mods[$modname]->instances[$modid]->userinfo)));
2192 function backup_mod_selected($preferences,$modname,$modid) {
2193 return ((empty($preferences->mods[$modname]->instances)
2194 && !empty($preferences->mods[$modname]->backup))
2195 || (is_array($preferences->mods[$modname]->instances)
2196 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2197 && !empty($preferences->mods[$modname]->instances[$modid]->backup)));
2201 * Checks for the required files/functions to backup every mod
2202 * And check if there is data about it
2204 function backup_fetch_prefs_from_request(&$preferences,&$count,$course) {
2205 global $CFG,$SESSION;
2207 // check to see if it's in the session already
2208 if (!empty($SESSION->backupprefs) && array_key_exists($course->id,$SESSION->backupprefs) && !empty($SESSION->backupprefs[$course->id])) {
2209 $sprefs = $SESSION->backupprefs[$course->id];
2210 $preferences = $sprefs;
2211 // refetch backup_name just in case.
2212 $bn = optional_param('backup_name','',PARAM_FILE);
2213 if (!empty($bn)) {
2214 $preferences->backup_name = $bn;
2216 $count = 1;
2217 return true;
2220 if ($allmods = get_records("modules") ) {
2221 foreach ($allmods as $mod) {
2222 $modname = $mod->name;
2223 $modfile = "$CFG->dirroot/mod/$modname/backuplib.php";
2224 $modbackup = $modname."_backup_mods";
2225 $modbackupone = $modname."_backup_one_mod";
2226 $modcheckbackup = $modname."_check_backup_mods";
2227 if (!file_exists($modfile)) {
2228 continue;
2230 include_once($modfile);
2231 if (!function_exists($modbackup) || !function_exists($modcheckbackup)) {
2232 continue;
2234 $var = "exists_".$modname;
2235 $preferences->$var = true;
2236 $count++;
2237 // check that there are instances and we can back them up individually
2238 if (!count_records('course_modules','course',$course->id,'module',$mod->id) || !function_exists($modbackupone)) {
2239 continue;
2241 $var = 'exists_one_'.$modname;
2242 $preferences->$var = true;
2243 $varname = $modname.'_instances';
2244 $preferences->$varname = get_all_instances_in_course($modname,$course);
2245 foreach ($preferences->$varname as $instance) {
2246 $preferences->mods[$modname]->instances[$instance->id]->name = $instance->name;
2247 $var = 'backup_'.$modname.'_instance_'.$instance->id;
2248 $$var = optional_param($var,0);
2249 $preferences->$var = $$var;
2250 $preferences->mods[$modname]->instances[$instance->id]->backup = $$var;
2251 $var = 'backup_user_info_'.$modname.'_instance_'.$instance->id;
2252 $$var = optional_param($var,0);
2253 $preferences->$var = $$var;
2254 $preferences->mods[$modname]->instances[$instance->id]->userinfo = $$var;
2255 $var = 'backup_'.$modname.'_instances';
2256 $preferences->$var = 1; // we need this later to determine what to display in modcheckbackup.
2259 //Check data
2260 //Check module info
2261 $preferences->mods[$modname]->name = $modname;
2263 $var = "backup_".$modname;
2264 $$var = optional_param( $var,0);
2265 $preferences->$var = $$var;
2266 $preferences->mods[$modname]->backup = $$var;
2268 //Check include user info
2269 $var = "backup_user_info_".$modname;
2270 $$var = optional_param( $var,0);
2271 $preferences->$var = $$var;
2272 $preferences->mods[$modname]->userinfo = $$var;
2277 //Check other parameters
2278 $preferences->backup_metacourse = optional_param('backup_metacourse',1,PARAM_INT);
2279 $preferences->backup_users = optional_param('backup_users',1,PARAM_INT);
2280 $preferences->backup_logs = optional_param('backup_logs',0,PARAM_INT);
2281 $preferences->backup_user_files = optional_param('backup_user_files',1,PARAM_INT);
2282 $preferences->backup_course_files = optional_param('backup_course_files',1,PARAM_INT);
2283 $preferences->backup_messages = optional_param('backup_messages',1,PARAM_INT);
2284 $preferences->backup_course = $course->id;
2285 $preferences->backup_name = required_param('backup_name',PARAM_FILE);
2286 $preferences->backup_unique_code = required_param('backup_unique_code');
2288 // put it (back) in the session
2289 $SESSION->backupprefs[$course->id] = $preferences;
2292 /* Finds all related roles used in course, mod and blocks context
2293 * @param object $preferences
2294 * @param object $course
2295 * @return array of role objects
2297 function backup_fetch_roles($preferences) {
2299 global $CFG;
2300 $contexts = array();
2301 $roles = array();
2303 /// adding course context
2304 $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
2305 $contexts[$coursecontext->id] = $coursecontext;
2307 /// adding mod contexts
2308 $mods = $preferences->mods;
2309 foreach ($mods as $modname => $mod) {
2310 $instances = $mod->instances;
2311 foreach ($instances as $id => $instance) {
2312 // if this type of mod is to be backed up
2313 if ($instance->backup) {
2314 $cm = get_coursemodule_from_instance($modname, $id);
2315 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2316 // put context in array keys
2317 $contexts[$context->id] = $context;
2322 // add all roles assigned at user context
2323 if ($preferences->backup_users) {
2324 if ($users = get_records_sql("SELECT u.old_id, u.table_name,u.info
2325 FROM {$CFG->prefix}backup_ids u
2326 WHERE u.backup_code = '$preferences->backup_unique_code' AND
2327 u.table_name = 'user'")) {
2328 foreach ($users as $user) {
2329 $context = get_context_instance(CONTEXT_USER, $user->old_id);
2330 $contexts[$context->id] = $context;
2336 // add all roles assigned at block context
2337 if ($courseblocks = get_records_sql("SELECT *
2338 FROM {$CFG->prefix}block_instance
2339 WHERE pagetype = '".PAGE_COURSE_VIEW."'
2340 AND pageid = {$preferences->backup_course}")) {
2342 foreach ($courseblocks as $courseblock) {
2344 $context = get_context_instance(CONTEXT_BLOCK, $courseblock->id);
2345 $contexts[$context->id] = $context;
2349 // foreach context, call get_roles_on_exact_context insert into array
2350 foreach ($contexts as $context) {
2351 if ($proles = get_roles_on_exact_context($context)) {
2352 foreach ($proles as $prole) {
2353 $roles[$prole->id] = $prole;
2358 return $roles;
2361 /* function to print xml for overrides */
2362 function write_role_overrides_xml($bf, $context, $startlevel) {
2363 fwrite ($bf, start_tag("ROLES_OVERRIDES", $startlevel, true));
2364 if ($roles = get_roles_with_override_on_context($context)) {
2365 foreach ($roles as $role) {
2366 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2367 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2368 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2369 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2370 fwrite ($bf, start_tag("CAPABILITIES", $startlevel+2, true));
2371 if ($capabilities = get_capabilities_from_role_on_context($role, $context)) {
2372 foreach ($capabilities as $capability) {
2373 fwrite ($bf, start_tag("CAPABILITY", $startlevel+3, true));
2374 fwrite ($bf, full_tag("NAME", $startlevel+4, false, $capability->capability));
2375 fwrite ($bf, full_tag("PERMISSION", $startlevel+4, false, $capability->permission));
2376 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $capability->timemodified));
2377 if (!isset($capability->modifierid)) {
2378 $capability->modifierid = 0;
2380 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $capability->modifierid));
2381 fwrite ($bf, end_tag("CAPABILITY", $startlevel+3, true));
2384 fwrite ($bf, end_tag("CAPABILITIES", $startlevel+2, true));
2385 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2388 fwrite ($bf, end_tag("ROLES_OVERRIDES", $startlevel, true));
2391 /* function to print xml for assignment */
2392 function write_role_assignments_xml($bf, $context, $startlevel) {
2393 /// write role_assign code here
2394 fwrite ($bf, start_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2396 if ($roles = get_roles_with_assignment_on_context($context)) {
2397 foreach ($roles as $role) {
2398 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2399 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2400 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2401 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2402 fwrite ($bf, start_tag("ASSIGNMENTS", $startlevel+2, true));
2403 if ($assignments = get_users_from_role_on_context($role, $context)) {
2404 foreach ($assignments as $assignment) {
2405 fwrite ($bf, start_tag("ASSIGNMENT", $startlevel+3, true));
2406 fwrite ($bf, full_tag("USERID", $startlevel+4, false, $assignment->userid));
2407 fwrite ($bf, full_tag("HIDDEN", $startlevel+4, false, $assignment->hidden));
2408 fwrite ($bf, full_tag("TIMESTART", $startlevel+4, false, $assignment->timestart));
2409 fwrite ($bf, full_tag("TIMEEND", $startlevel+4, false, $assignment->timeend));
2410 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $assignment->timemodified));
2411 if (!isset($assignment->modifierid)) {
2412 $assignment->modifierid = 0;
2414 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $assignment->modifierid));
2415 fwrite ($bf, full_tag("ENROL", $startlevel+4, false, $assignment->enrol));
2416 fwrite ($bf, full_tag("SORTORDER", $startlevel+4, false, $assignment->sortorder));
2417 fwrite ($bf, end_tag("ASSIGNMENT", $startlevel+3, true));
2420 fwrite ($bf, end_tag("ASSIGNMENTS", $startlevel+2, true));
2421 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2424 fwrite ($bf, end_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2428 function backup_execute(&$preferences, &$errorstr) {
2429 global $CFG;
2430 $status = true;
2432 //Check for temp and backup and backup_unique_code directory
2433 //Create them as needed
2434 if (!defined('BACKUP_SILENTLY')) {
2435 echo "<li>".get_string("creatingtemporarystructures").'</li>';
2438 $status = check_and_create_backup_dir($preferences->backup_unique_code);
2439 //Empty dir
2440 if ($status) {
2441 $status = clear_backup_dir($preferences->backup_unique_code);
2444 //Delete old_entries from backup tables
2445 if (!defined('BACKUP_SILENTLY')) {
2446 echo "<li>".get_string("deletingolddata").'</li>';
2448 $status = backup_delete_old_data();
2449 if (!$status) {
2450 if (!defined('BACKUP_SILENTLY')) {
2451 error ("An error occurred deleting old backup data");
2453 else {
2454 $errorstr = "An error occurred deleting old backup data";
2455 return false;
2459 //Create the moodle.xml file
2460 if ($status) {
2461 if (!defined('BACKUP_SILENTLY')) {
2462 echo "<li>".get_string("creatingxmlfile");
2463 //Begin a new list to xml contents
2464 echo "<ul>";
2465 echo "<li>".get_string("writingheader").'</li>';
2467 //Obtain the xml file (create and open) and print prolog information
2468 $backup_file = backup_open_xml($preferences->backup_unique_code);
2469 if (!defined('BACKUP_SILENTLY')) {
2470 echo "<li>".get_string("writinggeneralinfo").'</li>';
2472 //Prints general info about backup to file
2473 if ($backup_file) {
2474 if (!$status = backup_general_info($backup_file,$preferences)) {
2475 if (!defined('BACKUP_SILENTLY')) {
2476 notify("An error occurred while backing up general info");
2478 else {
2479 $errorstr = "An error occurred while backing up general info";
2480 return false;
2484 if (!defined('BACKUP_SILENTLY')) {
2485 echo "<li>".get_string("writingcoursedata");
2486 //Start new ul (for course)
2487 echo "<ul>";
2488 echo "<li>".get_string("courseinfo").'</li>';
2490 //Prints course start (tag and general info)
2491 if ($status) {
2492 if (!$status = backup_course_start($backup_file,$preferences)) {
2493 if (!defined('BACKUP_SILENTLY')) {
2494 notify("An error occurred while backing up course start");
2496 else {
2497 $errorstr = "An error occurred while backing up course start";
2498 return false;
2502 //Metacourse information
2503 if ($status && $preferences->backup_metacourse) {
2504 if (!defined('BACKUP_SILENTLY')) {
2505 echo "<li>".get_string("metacourse").'</li>';
2507 if (!$status = backup_course_metacourse($backup_file,$preferences)) {
2508 if (!defined('BACKUP_SILENTLY')) {
2509 notify("An error occurred while backing up metacourse info");
2511 else {
2512 $errorstr = "An error occurred while backing up metacourse info";
2513 return false;
2517 if (!defined('BACKUP_SILENTLY')) {
2518 echo "<li>".get_string("blocks").'</li>';
2520 //Blocks information
2521 if ($status) {
2522 if (!$status = backup_course_blocks($backup_file,$preferences)) {
2523 if (!defined('BACKUP_SILENTLY')) {
2524 notify("An error occurred while backing up course blocks");
2526 else {
2527 $errorstr = "An error occurred while backing up course blocks";
2528 return false;
2532 if (!defined('BACKUP_SILENTLY')) {
2533 echo "<li>".get_string("sections").'</li>';
2535 //Section info
2536 if ($status) {
2537 if (!$status = backup_course_sections($backup_file,$preferences)) {
2538 if (!defined('BACKUP_SILENTLY')) {
2539 notify("An error occurred while backing up course sections");
2541 else {
2542 $errorstr = "An error occurred while backing up course sections";
2543 return false;
2548 //End course contents (close ul)
2549 if (!defined('BACKUP_SILENTLY')) {
2550 echo "</ul></li>";
2553 //User info
2554 if ($status) {
2555 if (!defined('BACKUP_SILENTLY')) {
2556 echo "<li>".get_string("writinguserinfo").'</li>';
2558 if (!$status = backup_user_info($backup_file,$preferences)) {
2559 if (!defined('BACKUP_SILENTLY')) {
2560 notify("An error occurred while backing up user info");
2562 else {
2563 $errorstr = "An error occurred while backing up user info";
2564 return false;
2569 //If we have selected to backup messages and we are
2570 //doing a SITE backup, let's do it
2571 if ($status && $preferences->backup_messages && $preferences->backup_course == SITEID) {
2572 if (!defined('BACKUP_SILENTLY')) {
2573 echo "<li>".get_string("writingmessagesinfo").'</li>';
2575 if (!$status = backup_messages($backup_file,$preferences)) {
2576 if (!defined('BACKUP_SILENTLY')) {
2577 notify("An error occurred while backing up messages");
2579 else {
2580 $errorstr = "An error occurred while backing up messages";
2581 return false;
2586 //If we have selected to backup quizzes, backup categories and
2587 //questions structure (step 1). See notes on mod/quiz/backuplib.php
2588 if ($status and !empty($preferences->mods['quiz']->backup)) {
2589 if (!defined('BACKUP_SILENTLY')) {
2590 echo "<li>".get_string("writingcategoriesandquestions").'</li>';
2592 require_once($CFG->dirroot.'/mod/quiz/backuplib.php');
2593 if (!$status = backup_question_categories($backup_file,$preferences)) {
2594 if (!defined('BACKUP_SILENTLY')) {
2595 notify("An error occurred while backing up quiz categories");
2597 else {
2598 $errorstr = "An error occurred while backing up quiz categories";
2599 return false;
2604 //Print logs if selected
2605 if ($status) {
2606 if ($preferences->backup_logs) {
2607 if (!defined('BACKUP_SILENTLY')) {
2608 echo "<li>".get_string("writingloginfo").'</li>';
2610 if (!$status = backup_log_info($backup_file,$preferences)) {
2611 if (!defined('BACKUP_SILENTLY')) {
2612 notify("An error occurred while backing up log info");
2614 else {
2615 $errorstr = "An error occurred while backing up log info";
2616 return false;
2622 //Print scales info
2623 if ($status) {
2624 if (!defined('BACKUP_SILENTLY')) {
2625 echo "<li>".get_string("writingscalesinfo").'</li>';
2627 if (!$status = backup_scales_info($backup_file,$preferences)) {
2628 if (!defined('BACKUP_SILENTLY')) {
2629 notify("An error occurred while backing up scales");
2631 else {
2632 $errorstr = "An error occurred while backing up scales";
2633 return false;
2638 //Print groupings info
2639 if ($status) {
2640 if (!defined('BACKUP_SILENTLY')) {
2641 echo "<li>".get_string("writinggroupingsinfo").'</li>';
2643 if (!$status = backup_groupings_info($backup_file,$preferences)) {
2644 if (!defined('BACKUP_SILENTLY')) {
2645 notify("An error occurred while backing up groupings");
2647 else {
2648 $errorstr = "An error occurred while backing up groupings";
2649 return false;
2654 //Print groups info
2655 if ($status) {
2656 if (!defined('BACKUP_SILENTLY')) {
2657 echo "<li>".get_string("writinggroupsinfo").'</li>';
2659 if (!$status = backup_groups_info($backup_file,$preferences)) {
2660 if (!defined('BACKUP_SILENTLY')) {
2661 notify("An error occurred while backing up groups");
2663 else {
2664 $errostr = "An error occurred while backing up groups";
2665 return false;
2670 //Print events info
2671 if ($status) {
2672 if (!defined('BACKUP_SILENTLY')) {
2673 echo "<li>".get_string("writingeventsinfo").'</li>';
2675 if (!$status = backup_events_info($backup_file,$preferences)) {
2676 if (!defined('BACKUP_SILENTLY')) {
2677 notify("An error occurred while backing up events");
2679 else {
2680 $errorstr = "An error occurred while backing up events";
2681 return false;
2686 //Print gradebook info
2687 if ($status) {
2688 if (!defined('BACKUP_SILENTLY')) {
2689 echo "<li>".get_string("writinggradebookinfo").'</li>';
2691 if (!$status = backup_gradebook_info($backup_file,$preferences)) {
2692 if (!defined('BACKUP_SILENTLY')) {
2693 notify("An error occurred while backing up gradebook");
2695 else {
2696 $errorstr = "An error occurred while backing up gradebook";
2697 return false;
2702 //Module info, this unique function makes all the work!!
2703 //db export and module fileis copy
2704 if ($status) {
2705 $mods_to_backup = false;
2706 //Check if we have any mod to backup
2707 foreach ($preferences->mods as $module) {
2708 if ($module->backup) {
2709 $mods_to_backup = true;
2712 //If we have to backup some module
2713 if ($mods_to_backup) {
2714 if (!defined('BACKUP_SILENTLY')) {
2715 echo "<li>".get_string("writingmoduleinfo");
2717 //Start modules tag
2718 if (!$status = backup_modules_start ($backup_file,$preferences)) {
2719 if (!defined('BACKUP_SILENTLY')) {
2720 notify("An error occurred while backing up module info");
2722 else {
2723 $errorstr = "An error occurred while backing up module info";
2724 return false;
2727 //Open ul for module list
2728 if (!defined('BACKUP_SILENTLY')) {
2729 echo "<ul>";
2731 //Iterate over modules and call backup
2732 foreach ($preferences->mods as $module) {
2733 if ($module->backup and $status) {
2734 if (!defined('BACKUP_SILENTLY')) {
2735 echo "<li>".get_string("modulenameplural",$module->name).'</li>';
2737 if (!$status = backup_module($backup_file,$preferences,$module->name)) {
2738 if (!defined('BACKUP_SILENTLY')) {
2739 notify("An error occurred while backing up '$module->name'");
2741 else {
2742 $errorstr = "An error occurred while backing up '$module->name'";
2743 return false;
2748 //Close ul for module list
2749 if (!defined('BACKUP_SILENTLY')) {
2750 echo "</ul></li>";
2752 //Close modules tag
2753 if (!$status = backup_modules_end ($backup_file,$preferences)) {
2754 if (!defined('BACKUP_SILENTLY')) {
2755 notify("An error occurred while finishing the module backups");
2757 else {
2758 $errorstr = "An error occurred while finishing the module backups";
2759 return false;
2765 //Backup course format data, if any.
2766 if (!defined('BACKUP_SILENTLY')) {
2767 echo '<li>'.get_string("courseformatdata").'</li>';
2769 if($status) {
2770 if (!$status = backup_format_data($backup_file,$preferences)) {
2771 if (!defined('BACKUP_SILENTLY')) {
2772 notify("An error occurred while backing up the course format data");
2774 else {
2775 $errorstr = "An error occurred while backing up the course format data";
2776 return false;
2781 //Prints course end
2782 if ($status) {
2783 if (!$status = backup_course_end($backup_file,$preferences)) {
2784 if (!defined('BACKUP_SILENTLY')) {
2785 notify("An error occurred while closing the course backup");
2787 else {
2788 $errorstr = "An error occurred while closing the course backup";
2789 return false;
2793 //Close the xml file and xml data
2794 if ($backup_file) {
2795 backup_close_xml($backup_file);
2798 //End xml contents (close ul)
2799 if (!defined('BACKUP_SILENTLY')) {
2800 echo "</ul></li>";
2804 //Now, if selected, copy user files
2805 if ($status) {
2806 if ($preferences->backup_user_files) {
2807 if (!defined('BACKUP_SILENTLY')) {
2808 echo "<li>".get_string("copyinguserfiles").'</li>';
2810 if (!$status = backup_copy_user_files ($preferences)) {
2811 if (!defined('BACKUP_SILENTLY')) {
2812 notify("An error occurred while copying user files");
2814 else {
2815 $errorstr = "An error occurred while copying user files";
2816 return false;
2822 //Now, if selected, copy course files
2823 if ($status) {
2824 if ($preferences->backup_course_files) {
2825 if (!defined('BACKUP_SILENTLY')) {
2826 echo "<li>".get_string("copyingcoursefiles").'</li>';
2828 if (!$status = backup_copy_course_files ($preferences)) {
2829 if (!defined('BACKUP_SILENTLY')) {
2830 notify("An error occurred while copying course files");
2832 else {
2833 $errorstr = "An error occurred while copying course files";
2834 return false;
2840 //Now, zip all the backup directory contents
2841 if ($status) {
2842 if (!defined('BACKUP_SILENTLY')) {
2843 echo "<li>".get_string("zippingbackup").'</li>';
2845 if (!$status = backup_zip ($preferences)) {
2846 if (!defined('BACKUP_SILENTLY')) {
2847 notify("An error occurred while zipping the backup");
2849 else {
2850 $errorstr = "An error occurred while zipping the backup";
2851 return false;
2856 //Now, copy the zip file to course directory
2857 if ($status) {
2858 if (!defined('BACKUP_SILENTLY')) {
2859 echo "<li>".get_string("copyingzipfile").'</li>';
2861 if (!$status = copy_zip_to_course_dir ($preferences)) {
2862 if (!defined('BACKUP_SILENTLY')) {
2863 notify("An error occurred while copying the zip file to the course directory");
2865 else {
2866 $errorstr = "An error occurred while copying the zip file to the course directory";
2867 return false;
2872 //Now, clean temporary data (db and filesystem)
2873 if ($status) {
2874 if (!defined('BACKUP_SILENTLY')) {
2875 echo "<li>".get_string("cleaningtempdata").'</li>';
2877 if (!$status = clean_temp_data ($preferences)) {
2878 if (!defined('BACKUP_SILENTLY')) {
2879 notify("An error occurred while cleaning up temporary data");
2881 else {
2882 $errorstr = "An error occurred while cleaning up temporary data";
2883 return false;
2888 return $status;
2892 * This function generates the default zipfile name for a backup
2893 * based on the course id and the unique code.
2895 * @param object $course course object
2896 * @param string $backup_unique_code (optional, if left out current timestamp used)
2899 * @return string filename (excluding path information)
2901 function backup_get_zipfile_name($course, $backup_unique_code='') {
2903 if (empty($backup_unique_code)) {
2904 $backup_unique_code = time();
2907 //Calculate the backup word
2908 //Take off some characters in the filename !!
2909 $takeoff = array(" ", ":", "/", "\\", "|");
2910 $backup_word = str_replace($takeoff,"_",moodle_strtolower(get_string("backupfilename")));
2911 //If non-translated, use "backup"
2912 if (substr($backup_word,0,1) == "[") {
2913 $backup_word= "backup";
2916 //Calculate the date format string
2917 $backup_date_format = str_replace(" ","_",get_string("backupnameformat"));
2918 //If non-translated, use "%Y%m%d-%H%M"
2919 if (substr($backup_date_format,0,1) == "[") {
2920 $backup_date_format = "%%Y%%m%%d-%%H%%M";
2923 //Calculate the shortname
2924 $backup_shortname = clean_filename($course->shortname);
2925 if (empty($backup_shortname) or $backup_shortname == '_' ) {
2926 $backup_shortname = $course->id;
2929 //Calculate the final backup filename
2930 //The backup word
2931 $backup_name = $backup_word."-";
2932 //The shortname
2933 $backup_name .= moodle_strtolower($backup_shortname)."-";
2934 //The date format
2935 $backup_name .= userdate(time(),$backup_date_format,99,false);
2936 //The extension
2937 $backup_name .= ".zip";
2938 //And finally, clean everything
2939 $backup_name = clean_filename($backup_name);
2941 return $backup_name;
2946 * This function adds on the standard items to the preferences
2947 * Like moodle version and backup version
2949 * @param object $preferences existing preferences object.
2950 * (passed by reference)
2952 function backup_add_static_preferences(&$preferences) {
2953 global $CFG;
2954 $preferences->moodle_version = $CFG->version;
2955 $preferences->moodle_release = $CFG->release;
2956 $preferences->backup_version = $CFG->backup_version;
2957 $preferences->backup_release = $CFG->backup_release;