Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / backup / backuplib.php
blob690693fd7afbcf069bc1d635c402095bcc8e68d6
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 /**
7 * This function calculates the users to be added to backup based in the
8 * settings defined at backup. All the resulting user ids are sent to
9 * backup_ids for later usage.
10 * @param int $courseid id of the course to backup
11 * @param int $backup_unique_code unique code of the backup being executed
12 * @param int $backup_unique_code setting specifying what users to export (0=all, 1=needed, 2=none)
13 * @param int $backup_messages flag (true/false) defining if messages must be
14 * considered to extract needed users
15 * @param int $backup_blogs flag (true/false) defining if blogs must be
16 * considered to extract needed users
17 * @return array one array (key, value) sumarizing the result of the function (number of users)
19 function user_check_backup($courseid,$backup_unique_code,$backup_users,$backup_messages,$backup_blogs) {
21 $context = get_context_instance(CONTEXT_COURSE, $courseid);
22 $count_users = 0;
23 $backupable_users = array();
25 if ($backup_users == 0) { /// All users
26 $backupable_users = backup_get_all_users();
28 } else if ($backup_users == 1) { /// Needed users
30 /// Calculate needed users (calling every xxxx_get_participants function + scales users
31 /// + messages users + blogs users)
32 $needed_users = backup_get_needed_users($courseid, $backup_messages, $backup_blogs);
34 /// Calculate enrolled users (having course:view cap)
35 $enrolled_users = backup_get_enrolled_users($courseid);
37 /// Calculate backupable users (needed + enrolled)
38 /// First, needed
39 $backupable_users = $needed_users;
41 /// Now, enrolled
42 if ($enrolled_users) {
43 foreach ($enrolled_users as $enrolled_user) {
44 $backupable_users[$enrolled_user->id]->id = $enrolled_user->id;
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 or enrolled user, mark it as needed
56 if (isset($needed_users[$backupable_user->id]) || isset($enrolled_users[$backupable_user->id])) {
57 $backupable_user->info .= "needed";
58 } /// Yu: also needed because they can view course
59 /// might need another variable
61 /// Now create the backup_id record
62 $backupids_rec->backup_code = $backup_unique_code;
63 $backupids_rec->table_name = "user";
64 $backupids_rec->old_id = $backupable_user->id;
65 $backupids_rec->info = $backupable_user->info;
67 /// TODO: Change this call inserting to a standard backup_putid() call
68 /// And read data acordingly with backup_getid() when needed.
69 /// TODO: Also analyse it the "needed" info is really needed for anything. Drop if not.
70 /// Insert the user to the backup_ids table. backup_user_info() will use that info
71 $status = insert_record('backup_ids', $backupids_rec, false);
72 $count_users++;
74 /// Do some output
75 backup_flush(30);
78 /// Prepare Info
79 /// Gets the user data
80 $info[0][0] = get_string("users");
81 $info[0][1] = $count_users;
83 return $info;
86 //Returns every needed user (participant) in a course
87 //It uses the xxxx_get_participants() function
88 //plus users needed to backup scales.
89 //Also it search for users having messages and
90 //users having blogs
91 //WARNING: It returns only NEEDED users, not every
92 // every student and teacher in the course, so it
93 //must be merged with backup_get_enrrolled_users !!
95 function backup_get_needed_users ($courseid, $includemessages=false, $includeblogs=false) {
97 global $CFG;
99 $result = false;
101 $course_modules = get_records_sql ("SELECT cm.id, m.name, cm.instance
102 FROM {$CFG->prefix}modules m,
103 {$CFG->prefix}course_modules cm
104 WHERE m.id = cm.module and
105 cm.course = '$courseid'");
107 if ($course_modules) {
108 //Iterate over each module
109 foreach ($course_modules as $course_module) {
110 $modlib = "$CFG->dirroot/mod/$course_module->name/lib.php";
111 $modgetparticipants = $course_module->name."_get_participants";
112 if (file_exists($modlib)) {
113 include_once($modlib);
114 if (function_exists($modgetparticipants)) {
115 $module_participants = $modgetparticipants($course_module->instance);
116 //Add them to result
117 if ($module_participants) {
118 foreach ($module_participants as $module_participant) {
119 $result[$module_participant->id]->id = $module_participant->id;
127 //Now, add scale users (from site and course scales)
128 //Get users
129 $scaleusers = get_records_sql("SELECT DISTINCT userid,userid
130 FROM {$CFG->prefix}scale
131 WHERE courseid = '0' or courseid = '$courseid'");
132 //Add scale users to results
133 if ($scaleusers) {
134 foreach ($scaleusers as $scaleuser) {
135 //If userid != 0
136 if ($scaleuser->userid != 0) {
137 $result[$scaleuser->userid]->id = $scaleuser->userid;
142 //Now, add message users if necessary
143 if ($includemessages) {
144 include_once("$CFG->dirroot/message/lib.php");
145 //Get users
146 $messageusers = message_get_participants();
147 //Add message users to results
148 if ($messageusers) {
149 foreach ($messageusers as $messageuser) {
150 //If id != 0
151 if ($messageuser->id !=0) {
152 $result[$messageuser->id]->id = $messageuser->id;
158 //Now, add blog users if necessary
159 if ($includeblogs) {
160 include_once("$CFG->dirroot/blog/lib.php");
161 //Get users
162 $blogusers = blog_get_participants();
163 //Add blog users to results
164 if ($blogusers) {
165 foreach ($blogusers as $bloguser) {
166 //If id != 0
167 if ($bloguser->id !=0) {
168 $result[$bloguser->id]->id = $bloguser->id;
174 return $result;
178 //Returns every enrolled user (student and teacher) in a course
180 function backup_get_enrolled_users ($courseid) {
182 global $CFG;
184 // get all users with moodle/course:view capability, this will include people
185 // assigned at cat level, or site level
186 // but it should be ok if they have no direct assignment at course, mod, block level
187 return get_users_by_capability(get_context_instance(CONTEXT_COURSE, $courseid), 'moodle/course:view');
190 //Returns all users ids (every record in users table)
191 function backup_get_all_users() {
193 return get_records('user', '', '', '', 'id, id');
196 //Calculate the number of log entries to backup
197 //Return an array of info (name,value)
198 function log_check_backup($course) {
200 global $CFG;
202 //Now execute the count
203 $ids = count_records("log","course",$course);
205 //Gets the user data
206 $info[0][0] = get_string("logs");
207 if ($ids) {
208 $info[0][1] = $ids;
209 } else {
210 $info[0][1] = 0;
213 return $info;
216 //Calculate the number of user files to backup
217 //Under $CFG->dataroot/users
218 //Return an array of info (name,value)
219 function user_files_check_backup($course,$backup_unique_code) {
221 global $CFG;
222 $count = 0;
224 $backup_users = get_recordset_select("backup_ids",
225 "backup_code='$backup_unique_code' AND table_name='user'", "", "id, old_id");
227 while ($user = rs_fetch_next_record($backup_users)) {
228 //Is this user needed in the backup?
229 $userdir = make_user_directory($user->old_id, true);
230 if (check_dir_exists($userdir)) {
231 $count++;
233 //Do some output
234 backup_flush(30);
236 rs_close($backup_users);
237 //Gets the user data
238 $info[0][0] = get_string("userswithfiles");
239 $info[0][1] = $count;
241 return $info;
245 * Calculate the number of course files to backup
246 * under $CFG->dataroot/$course, except $CFG->moddata, and backupdata
247 * and put them (their path) in backup_ids
248 * Return an array of info (name,value)
250 function course_files_check_backup($course, $backup_unique_code) {
252 global $CFG;
254 $rootdir = $CFG->dataroot."/$course";
255 //Check if directory exists
256 if (is_dir($rootdir)) {
257 //Get files and directories without descend
258 $coursedirs = get_directory_list($rootdir,$CFG->moddata,false,true,true);
259 $backupdata_dir = "backupdata";
260 foreach ($coursedirs as $dir) {
261 //Check it isn't backupdata_dir
262 if (strpos($dir,$backupdata_dir)!==0) {
263 //Insert them into backup_files
264 $status = execute_sql("INSERT INTO {$CFG->prefix}backup_files
265 (backup_code, file_type, path)
266 VALUES
267 ('$backup_unique_code','course','".addslashes($dir)."')",false);
269 //Do some output
270 backup_flush(30);
274 //Now execute the select
275 $ids = get_records_sql("SELECT DISTINCT b.path, b.old_id
276 FROM {$CFG->prefix}backup_files b
277 WHERE backup_code = '$backup_unique_code' AND
278 file_type = 'course'");
279 //Gets the user data
280 $info = array();
281 $info[0] = array();
282 $info[0][0] = get_string("files");
283 if ($ids) {
284 $info[0][1] = count($ids);
285 } else {
286 $info[0][1] = 0;
289 return $info;
293 * Calculate the number of site files to backup
294 * under $CFG->dataroot/SITEID
295 * Their path is already in backup_ids, put there by modules check_backup functions.
296 * Modules only put in paths of files that are used.
298 * Return an array of info (name,value)
300 function site_files_check_backup($course, $backup_unique_code) {
301 global $CFG;
303 //execute the select, records have been inserted by modules during their ****_check_backup_mods function.
304 $ids = get_records_sql("SELECT DISTINCT b.path
305 FROM {$CFG->prefix}backup_files b
306 WHERE backup_code = '$backup_unique_code' AND
307 file_type = 'site'");
308 //Gets the user data
309 $info = array();
310 $info[0] = array();
311 $info[0][0] = get_string('files');
312 if ($ids) {
313 $info[0][1] = count($ids);
314 } else {
315 $info[0][1] = 0;
318 return $info;
321 //Function to check and create the needed moddata dir to
322 //save all the mod backup files. We always name it moddata
323 //to be able to restore it, but in restore we check for
324 //$CFG->moddata !!
325 function check_and_create_moddata_dir($backup_unique_code) {
327 global $CFG;
329 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/moddata",true);
331 return $status;
334 //Function to check and create the "user_files" dir to
335 //save all the user files we need from "users" dir
336 function check_and_create_user_files_dir($backup_unique_code) {
338 global $CFG;
340 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/user_files",true);
342 return $status;
345 //Function to check and create the "group_files" dir to
346 //save all the user files we need from "groups" dir
347 function check_and_create_group_files_dir($backup_unique_code) {
349 global $CFG;
351 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/group_files",true);
353 return $status;
356 //Function to check and create the "course_files" dir to
357 //save all the course files we need from "CFG->datadir/course" dir
358 function check_and_create_course_files_dir($backup_unique_code) {
360 global $CFG;
362 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/course_files",true);
364 return $status;
367 //Function to check and create the "site_files" dir to
368 //save all the course files we need from "CFG->datadir/SITEID" dir
369 function check_and_create_site_files_dir($backup_unique_code) {
371 global $CFG;
373 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/site_files",true);
375 return $status;
378 //Function to create, open and write header of the xml file
379 function backup_open_xml($backup_unique_code) {
381 global $CFG;
383 $status = true;
385 //Open for writing
387 $file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
388 $backup_file = fopen($file,"w");
389 //Writes the header
390 $status = fwrite ($backup_file,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
391 if ($status) {
392 $status = fwrite ($backup_file,start_tag("MOODLE_BACKUP",0,true));
394 if ($status) {
395 return $backup_file;
396 } else {
397 return false;
401 //Close the file
402 function backup_close_xml($backup_file) {
403 $status = fwrite ($backup_file,end_tag("MOODLE_BACKUP",0,true));
404 return fclose($backup_file);
407 //Return the xml start tag
408 function start_tag($tag,$level=0,$endline=false,$attributes=null) {
409 if ($endline) {
410 $endchar = "\n";
411 } else {
412 $endchar = "";
414 $attrstring = '';
415 if (!empty($attributes) && is_array($attributes)) {
416 foreach ($attributes as $key => $value) {
417 $attrstring .= " ".xml_tag_safe_content($key)."=\"".
418 xml_tag_safe_content($value)."\"";
421 return str_repeat(" ",$level*2)."<".strtoupper($tag).$attrstring.">".$endchar;
424 //Return the xml end tag
425 function end_tag($tag,$level=0,$endline=true) {
426 if ($endline) {
427 $endchar = "\n";
428 } else {
429 $endchar = "";
431 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
434 //Return the start tag, the contents and the end tag
435 function full_tag($tag,$level=0,$endline=true,$content,$attributes=null) {
437 global $CFG;
438 //Here we encode absolute links
439 // MDL-10770
440 if (is_null($content)) {
441 $content = '$@NULL@$';
442 } else {
443 $content = backup_encode_absolute_links($content);
445 $st = start_tag($tag,$level,$endline,$attributes);
447 $co = xml_tag_safe_content($content);
449 $et = end_tag($tag,0,true);
451 return $st.$co.$et;
455 function xml_tag_safe_content($content) {
456 global $CFG;
457 //If enabled, we strip all the control chars (\x0-\x1f) from the text but tabs (\x9),
458 //newlines (\xa) and returns (\xd). The delete control char (\x7f) is also included.
459 //because they are forbiden in XML 1.0 specs. The expression below seems to be
460 //UTF-8 safe too because it simply ignores the rest of characters.
461 $content = preg_replace("/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is","",$content);
462 $content = preg_replace("/\r\n|\r/", "\n", htmlspecialchars($content));
463 return $content;
466 //Prints General info about the course
467 //name, moodle_version (internal and release), backup_version, date, info in file...
468 function backup_general_info ($bf,$preferences) {
470 global $CFG;
472 fwrite ($bf,start_tag("INFO",1,true));
474 //The name of the backup
475 fwrite ($bf,full_tag("NAME",2,false,$preferences->backup_name));
476 //The moodle_version
477 fwrite ($bf,full_tag("MOODLE_VERSION",2,false,$preferences->moodle_version));
478 fwrite ($bf,full_tag("MOODLE_RELEASE",2,false,$preferences->moodle_release));
479 //The backup_version
480 fwrite ($bf,full_tag("BACKUP_VERSION",2,false,$preferences->backup_version));
481 fwrite ($bf,full_tag("BACKUP_RELEASE",2,false,$preferences->backup_release));
482 //The date
483 fwrite ($bf,full_tag("DATE",2,false,$preferences->backup_unique_code));
484 //The original site wwwroot
485 fwrite ($bf,full_tag("ORIGINAL_WWWROOT",2,false,$CFG->wwwroot));
486 //The zip method used
487 if (!empty($CFG->zip)) {
488 $zipmethod = 'external';
489 } else {
490 $zipmethod = 'internal';
492 //Indicate if it includes external MNET users
493 $sql = "SELECT b.old_id
494 FROM {$CFG->prefix}backup_ids b
495 JOIN {$CFG->prefix}user u ON b.old_id=u.id
496 WHERE b.backup_code = '$preferences->backup_unique_code'
497 AND b.table_name = 'user' AND u.mnethostid != '{$CFG->mnet_localhost_id}'";
498 if (record_exists_sql($sql)) {
499 fwrite ($bf,full_tag("MNET_REMOTEUSERS",2,false,'true'));
501 fwrite ($bf,full_tag("ZIP_METHOD",2,false,$zipmethod));
502 //Te includes tag
503 fwrite ($bf,start_tag("DETAILS",2,true));
504 //Now, go to mod element of preferences to print its status
505 foreach ($preferences->mods as $element) {
506 //Calculate info
507 $included = "false";
508 $userinfo = "false";
509 if ($element->backup) {
510 $included = "true";
511 if ($element->userinfo) {
512 $userinfo = "true";
515 //Prints the mod start
516 fwrite ($bf,start_tag("MOD",3,true));
517 fwrite ($bf,full_tag("NAME",4,false,$element->name));
518 fwrite ($bf,full_tag("INCLUDED",4,false,$included));
519 fwrite ($bf,full_tag("USERINFO",4,false,$userinfo));
521 if (isset($preferences->mods[$element->name]->instances)
522 && is_array($preferences->mods[$element->name]->instances)
523 && count($preferences->mods[$element->name]->instances)) {
524 fwrite ($bf, start_tag("INSTANCES",4,true));
525 foreach ($preferences->mods[$element->name]->instances as $id => $object) {
526 if (!empty($object->backup)) {
527 //Calculate info
528 $included = "false";
529 $userinfo = "false";
530 if ($object->backup) {
531 $included = "true";
532 if ($object->userinfo) {
533 $userinfo = "true";
536 fwrite ($bf, start_tag("INSTANCE",5,true));
537 fwrite ($bf, full_tag("ID",5,false,$id));
538 fwrite ($bf, full_tag("NAME",5,false,$object->name));
539 fwrite ($bf, full_tag("INCLUDED",5,false,$included)) ;
540 fwrite ($bf, full_tag("USERINFO",5,false,$userinfo));
541 fwrite ($bf, end_tag("INSTANCE",5,true));
544 fwrite ($bf, end_tag("INSTANCES",4,true));
548 //Print the end
549 fwrite ($bf,end_tag("MOD",3,true));
551 //The metacourse in backup
552 if ($preferences->backup_metacourse == 1) {
553 fwrite ($bf,full_tag("METACOURSE",3,false,"true"));
554 } else {
555 fwrite ($bf,full_tag("METACOURSE",3,false,"false"));
557 //The user in backup
558 if ($preferences->backup_users == 1) {
559 fwrite ($bf,full_tag("USERS",3,false,"course"));
560 } else if ($preferences->backup_users == 0) {
561 fwrite ($bf,full_tag("USERS",3,false,"all"));
562 } else {
563 fwrite ($bf,full_tag("USERS",3,false,"none"));
565 //The logs in backup
566 if ($preferences->backup_logs == 1) {
567 fwrite ($bf,full_tag("LOGS",3,false,"true"));
568 } else {
569 fwrite ($bf,full_tag("LOGS",3,false,"false"));
571 //The user files
572 if ($preferences->backup_user_files == 1) {
573 fwrite ($bf,full_tag("USERFILES",3,false,"true"));
574 } else {
575 fwrite ($bf,full_tag("USERFILES",3,false,"false"));
577 //The course files
578 if ($preferences->backup_course_files == 1) {
579 fwrite ($bf,full_tag("COURSEFILES",3,false,"true"));
580 } else {
581 fwrite ($bf,full_tag("COURSEFILES",3,false,"false"));
583 //The site files
584 if ($preferences->backup_site_files == 1) {
585 fwrite ($bf,full_tag("SITEFILES",3,false,"true"));
586 } else {
587 fwrite ($bf,full_tag("SITEFILES",3,false,"false"));
589 //The gradebook histories
590 if ($preferences->backup_gradebook_history == 1) {
591 fwrite ($bf,full_tag("GRADEBOOKHISTORIES",3,false,"true"));
592 } else {
593 fwrite ($bf,full_tag("GRADEBOOKHISTORIES",3,false,"false"));
595 //The messages in backup
596 if ($preferences->backup_messages == 1 && $preferences->backup_course == SITEID) {
597 fwrite ($bf,full_tag("MESSAGES",3,false,"true"));
598 } else {
599 fwrite ($bf,full_tag("MESSAGES",3,false,"false"));
601 //The blogs in backup
602 if ($preferences->backup_blogs == 1 && $preferences->backup_course == SITEID) {
603 fwrite ($bf,full_tag("BLOGS",3,false,"true"));
604 } else {
605 fwrite ($bf,full_tag("BLOGS",3,false,"false"));
607 //The mode of writing the block data
608 fwrite ($bf,full_tag('BLOCKFORMAT',3,false,'instances'));
609 fwrite ($bf,end_tag("DETAILS",2,true));
611 $status = fwrite ($bf,end_tag("INFO",1,true));
613 ///Roles stuff goes in here
615 fwrite ($bf, start_tag('ROLES', 1, true));
616 $roles = backup_fetch_roles($preferences);
618 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
619 $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
621 foreach ($roles as $role) {
622 fwrite ($bf,start_tag('ROLE',2,true));
623 fwrite ($bf,full_tag('ID', 3, false, $role->id));
624 fwrite ($bf,full_tag('NAME',3,false,$role->name));
625 fwrite ($bf,full_tag('SHORTNAME',3,false,$role->shortname));
626 /// Calculate $role name in course
627 $nameincourse = role_get_name($role, $coursecontext);
628 if ($nameincourse != $role->name) {
629 fwrite ($bf,full_tag('NAMEINCOURSE', 3, false, $nameincourse));
631 // find and write all default capabilities
632 fwrite ($bf,start_tag('CAPABILITIES',3,true));
633 // pull out all default (site context) capabilities
634 if ($capabilities = role_context_capabilities($role->id, $sitecontext)) {
635 foreach ($capabilities as $capability=>$value) {
636 fwrite ($bf,start_tag('CAPABILITY',4,true));
637 fwrite ($bf,full_tag('NAME', 5, false, $capability));
638 fwrite ($bf,full_tag('PERMISSION', 5, false, $value));
639 // use this to pull out the other info (timemodified and modifierid)
641 $cap = get_record_sql("SELECT *
642 FROM {$CFG->prefix}role_capabilities
643 WHERE capability = '$capability'
644 AND contextid = $sitecontext->id
645 AND roleid = $role->id");
646 fwrite ($bf, full_tag("TIMEMODIFIED", 5, false, $cap->timemodified));
647 fwrite ($bf, full_tag("MODIFIERID", 5, false, $cap->modifierid));
648 fwrite ($bf,end_tag('CAPABILITY',4,true));
651 fwrite ($bf,end_tag('CAPABILITIES',3,true));
652 fwrite ($bf,end_tag('ROLE',2,true));
654 fwrite ($bf,end_tag('ROLES', 1, true));
655 return $status;
658 //Prints course's general info (table course)
659 function backup_course_start ($bf,$preferences) {
661 global $CFG;
663 $status = true;
665 //Course open tag
666 fwrite ($bf,start_tag("COURSE",1,true));
667 //Header open tag
668 fwrite ($bf,start_tag("HEADER",2,true));
670 //Get info from course
671 $course = get_record("course","id",$preferences->backup_course);
672 $context = get_context_instance(CONTEXT_COURSE, $course->id);
673 if ($course) {
674 //Prints course info
675 fwrite ($bf,full_tag("ID",3,false,$course->id));
676 //Obtain the category
677 $category = get_record("course_categories","id","$course->category");
678 if ($category) {
679 //Prints category info
680 fwrite ($bf,start_tag("CATEGORY",3,true));
681 fwrite ($bf,full_tag("ID",4,false,$course->category));
682 fwrite ($bf,full_tag("NAME",4,false,$category->name));
683 fwrite ($bf,end_tag("CATEGORY",3,true));
685 //Continues with the course
686 fwrite ($bf,full_tag("PASSWORD",3,false,$course->password));
687 fwrite ($bf,full_tag("FULLNAME",3,false,$course->fullname));
688 fwrite ($bf,full_tag("SHORTNAME",3,false,$course->shortname));
689 fwrite ($bf,full_tag("IDNUMBER",3,false,$course->idnumber));
690 fwrite ($bf,full_tag("SUMMARY",3,false,$course->summary));
691 fwrite ($bf,full_tag("FORMAT",3,false,$course->format));
692 fwrite ($bf,full_tag("SHOWGRADES",3,false,$course->showgrades));
693 fwrite ($bf,full_tag("NEWSITEMS",3,false,$course->newsitems));
694 fwrite ($bf,full_tag("TEACHER",3,false,$course->teacher));
695 fwrite ($bf,full_tag("TEACHERS",3,false,$course->teachers));
696 fwrite ($bf,full_tag("STUDENT",3,false,$course->student));
697 fwrite ($bf,full_tag("STUDENTS",3,false,$course->students));
698 fwrite ($bf,full_tag("GUEST",3,false,$course->guest));
699 fwrite ($bf,full_tag("STARTDATE",3,false,$course->startdate));
700 fwrite ($bf,full_tag("NUMSECTIONS",3,false,$course->numsections));
701 //fwrite ($bf,full_tag("SHOWRECENT",3,false,$course->showrecent)); INFO: This is out in 1.3
702 fwrite ($bf,full_tag("MAXBYTES",3,false,$course->maxbytes));
703 fwrite ($bf,full_tag("SHOWREPORTS",3,false,$course->showreports));
704 fwrite ($bf,full_tag("GROUPMODE",3,false,$course->groupmode));
705 fwrite ($bf,full_tag("GROUPMODEFORCE",3,false,$course->groupmodeforce));
706 fwrite ($bf,full_tag("DEFAULTGROUPINGID",3,false,$course->defaultgroupingid));
707 fwrite ($bf,full_tag("LANG",3,false,$course->lang));
708 fwrite ($bf,full_tag("THEME",3,false,$course->theme));
709 fwrite ($bf,full_tag("COST",3,false,$course->cost));
710 fwrite ($bf,full_tag("CURRENCY",3,false,$course->currency));
711 fwrite ($bf,full_tag("MARKER",3,false,$course->marker));
712 fwrite ($bf,full_tag("VISIBLE",3,false,$course->visible));
713 fwrite ($bf,full_tag("HIDDENSECTIONS",3,false,$course->hiddensections));
714 fwrite ($bf,full_tag("TIMECREATED",3,false,$course->timecreated));
715 fwrite ($bf,full_tag("TIMEMODIFIED",3,false,$course->timemodified));
716 //If not selected, force metacourse to 0
717 if (!$preferences->backup_metacourse) {
718 $status = fwrite ($bf,full_tag("METACOURSE",3,false,'0'));
719 //else, export the field as is in DB
720 } else {
721 $status = fwrite ($bf,full_tag("METACOURSE",3,false,$course->metacourse));
723 fwrite ($bf,full_tag("EXPIRENOTIFY",3,false,$course->expirynotify));
724 fwrite ($bf,full_tag("NOTIFYSTUDENTS",3,false,$course->notifystudents));
725 fwrite ($bf,full_tag("EXPIRYTHRESHOLD",3,false,$course->expirythreshold));
726 fwrite ($bf,full_tag("ENROLLABLE",3,false,$course->enrollable));
727 fwrite ($bf,full_tag("ENROLSTARTDATE",3,false,$course->enrolstartdate));
728 fwrite ($bf,full_tag("ENROLENDDATE",3,false,$course->enrolenddate));
729 fwrite ($bf,full_tag("ENROLPERIOD",3,false,$course->enrolperiod));
731 /// write local course overrides here?
732 write_role_overrides_xml($bf, $context, 3);
733 /// write role_assign code here
734 write_role_assignments_xml($bf, $preferences, $context, 3);
735 //Print header end
736 fwrite ($bf,end_tag("HEADER",2,true));
737 } else {
738 $status = false;
741 return $status;
744 //Prints course's end tag
745 function backup_course_end ($bf,$preferences) {
747 //Course end tag
748 $status = fwrite ($bf,end_tag("COURSE",1,true));
750 return $status;
754 //Prints course's metacourse info (table course_meta)
755 function backup_course_metacourse ($bf,$preferences) {
757 global $CFG;
759 $status = true;
761 //Get info from meta
762 $parents = get_records_sql ("SELECT m.*, c.idnumber, c.shortname
763 FROM {$CFG->prefix}course_meta m,
764 {$CFG->prefix}course c
765 WHERE m.child_course = '$preferences->backup_course' AND
766 m.parent_course = c.id");
767 $childs = get_records_sql ("SELECT m.*, c.idnumber, c.shortname
768 FROM {$CFG->prefix}course_meta m,
769 {$CFG->prefix}course c
770 WHERE m.parent_course = '$preferences->backup_course' AND
771 m.child_course = c.id");
773 if ($parents || $childs) {
774 //metacourse open tag
775 fwrite ($bf,start_tag("METACOURSE",2,true));
776 if ($parents) {
777 fwrite($bf, start_tag("PARENTS",3,true));
778 //Iterate over every parent
779 foreach ($parents as $parent) {
780 //Begin parent
781 fwrite ($bf,start_tag("PARENT",4,true));
782 fwrite ($bf,full_tag("ID",5,false,$parent->parent_course));
783 fwrite ($bf,full_tag("IDNUMBER",5,false,$parent->idnumber));
784 fwrite ($bf,full_tag("SHORTNAME",5,false,$parent->shortname));
785 //End parent
786 fwrite ($bf,end_tag("PARENT",4,true));
788 fwrite ($bf,end_tag("PARENTS",3,true));
790 if ($childs) {
791 fwrite($bf, start_tag("CHILDS",3,true));
792 //Iterate over every child
793 foreach ($childs as $child) {
794 //Begin parent
795 fwrite ($bf,start_tag("CHILD",4,true));
796 fwrite ($bf,full_tag("ID",5,false,$child->child_course));
797 fwrite ($bf,full_tag("IDNUMBER",5,false,$child->idnumber));
798 fwrite ($bf,full_tag("SHORTNAME",5,false,$child->shortname));
799 //End parent
800 fwrite ($bf,end_tag("CHILD",4,true));
802 fwrite ($bf,end_tag("CHILDS",3,true));
804 //metacourse close tag
805 $status = fwrite ($bf,end_tag("METACOURSE",3,true));
808 return $status;
812 //Prints course's messages info (tables message, message_read and message_contacts)
813 function backup_messages ($bf,$preferences) {
815 global $CFG;
817 $status = true;
819 /// Check we have something to backup
820 $unreads = count_records ('message');
821 $reads = count_records ('message_read');
822 $contacts= count_records ('message_contacts');
824 if ($unreads || $reads || $contacts) {
825 $counter = 0;
826 /// message open tag
827 fwrite ($bf,start_tag("MESSAGES",2,true));
829 if ($unreads) {
830 $rs_unreads = get_recordset('message');
831 /// Iterate over every unread
832 while ($unread = rs_fetch_next_record($rs_unreads)) {
833 /// start message
834 fwrite($bf, start_tag("MESSAGE",3,true));
835 fwrite ($bf,full_tag("ID",4,false,$unread->id));
836 fwrite ($bf,full_tag("STATUS",4,false,"UNREAD"));
837 fwrite ($bf,full_tag("USERIDFROM",4,false,$unread->useridfrom));
838 fwrite ($bf,full_tag("USERIDTO",4,false,$unread->useridto));
839 fwrite ($bf,full_tag("MESSAGE",4,false,$unread->message));
840 fwrite ($bf,full_tag("FORMAT",4,false,$unread->format));
841 fwrite ($bf,full_tag("TIMECREATED",4,false,$unread->timecreated));
842 fwrite ($bf,full_tag("MESSAGETYPE",4,false,$unread->messagetype));
843 /// end message
844 fwrite ($bf,end_tag("MESSAGE",3,true));
846 /// Do some output
847 $counter++;
848 if ($counter % 20 == 0) {
849 echo ".";
850 if ($counter % 400 == 0) {
851 echo "<br />";
853 backup_flush(300);
856 rs_close($rs_unreads);
859 if ($reads) {
860 $rs_reads = get_recordset('message_read');
861 /// Iterate over every unread
862 while ($read = rs_fetch_next_record($rs_reads)) {
863 /// start message
864 fwrite($bf, start_tag("MESSAGE",3,true));
865 fwrite ($bf,full_tag("ID",4,false,$read->id));
866 fwrite ($bf,full_tag("STATUS",4,false,"READ"));
867 fwrite ($bf,full_tag("USERIDFROM",4,false,$read->useridfrom));
868 fwrite ($bf,full_tag("USERIDTO",4,false,$read->useridto));
869 fwrite ($bf,full_tag("MESSAGE",4,false,$read->message));
870 fwrite ($bf,full_tag("FORMAT",4,false,$read->format));
871 fwrite ($bf,full_tag("TIMECREATED",4,false,$read->timecreated));
872 fwrite ($bf,full_tag("MESSAGETYPE",4,false,$read->messagetype));
873 fwrite ($bf,full_tag("TIMEREAD",4,false,$read->timeread));
874 fwrite ($bf,full_tag("MAILED",4,false,$read->mailed));
875 /// end message
876 fwrite ($bf,end_tag("MESSAGE",3,true));
878 /// Do some output
879 $counter++;
880 if ($counter % 20 == 0) {
881 echo ".";
882 if ($counter % 400 == 0) {
883 echo "<br />";
885 backup_flush(300);
888 rs_close($rs_reads);
891 if ($contacts) {
892 fwrite($bf, start_tag("CONTACTS",3,true));
893 $rs_contacts = get_recordset('message_contacts');
894 /// Iterate over every contact
895 while ($contact = rs_fetch_next_record($rs_contacts)) {
896 /// start contact
897 fwrite($bf, start_tag("CONTACT",4,true));
898 fwrite ($bf,full_tag("ID",5,false,$contact->id));
899 fwrite ($bf,full_tag("USERID",5,false,$contact->userid));
900 fwrite ($bf,full_tag("CONTACTID",5,false,$contact->contactid));
901 fwrite ($bf,full_tag("BLOCKED",5,false,$contact->blocked));
902 /// end contact
903 fwrite ($bf,end_tag("CONTACT",4,true));
905 /// Do some output
906 $counter++;
907 if ($counter % 20 == 0) {
908 echo ".";
909 if ($counter % 400 == 0) {
910 echo "<br />";
912 backup_flush(300);
915 rs_close($rs_contacts);
916 fwrite($bf, end_tag("CONTACTS",3,true));
919 /// messages close tag
920 $status = fwrite ($bf,end_tag("MESSAGES",2,true));
923 return $status;
927 //Print blogs info (post table, module=blog, course=0)
928 function backup_blogs($bf, $preferences) {
930 global $CFG;
932 $status = true;
934 /// Check we have something to backup
935 $siteblogs = count_records('post', 'module', 'blog', 'courseid', 0);
937 if ($siteblogs) {
938 $counter = 0;
939 /// blogs open tag
940 fwrite ($bf, start_tag("BLOGS",2,true));
942 if ($siteblogs) {
943 $rs_blogs = get_recordset_sql("SELECT * from {$CFG->prefix}post
944 WHERE module = 'blog'
945 AND courseid = 0");
946 /// Iterate over every blog
947 while ($blog = rs_fetch_next_record($rs_blogs)) {
948 /// start blog
949 fwrite($bf, start_tag("BLOG",3,true));
950 /// blog body
951 fwrite ($bf,full_tag("ID",4,false,$blog->id));
952 fwrite ($bf,full_tag("MODULE",4,false,$blog->module));
953 fwrite ($bf,full_tag("USERID",4,false,$blog->userid));
954 fwrite ($bf,full_tag("COURSEID",4,false,$blog->courseid));
955 fwrite ($bf,full_tag("GROUPID",4,false,$blog->groupid));
956 fwrite ($bf,full_tag("MODULEID",4,false,$blog->moduleid));
957 fwrite ($bf,full_tag("COURSEMODULEID",4,false,$blog->coursemoduleid));
958 fwrite ($bf,full_tag("SUBJECT",4,false,$blog->subject));
959 fwrite ($bf,full_tag("SUMMARY",4,false,$blog->summary));
960 fwrite ($bf,full_tag("CONTENT",4,false,$blog->content));
961 fwrite ($bf,full_tag("UNIQUEHASH",4,false,$blog->uniquehash));
962 fwrite ($bf,full_tag("RATING",4,false,$blog->rating));
963 fwrite ($bf,full_tag("FORMAT",4,false,$blog->format));
964 fwrite ($bf,full_tag("ATTACHMENT",4,false,$blog->attachment));
965 fwrite ($bf,full_tag("PUBLISHSTATE",4,false,$blog->publishstate));
966 fwrite ($bf,full_tag("LASTMODIFIED",4,false,$blog->lastmodified));
967 fwrite ($bf,full_tag("CREATED",4,false,$blog->created));
968 fwrite ($bf,full_tag("USERMODIFIED",4,false,$blog->usermodified));
970 /// Blog tags
971 /// Check if we have blog tags to backup
972 if (!empty($CFG->usetags)) {
973 if ($tags = tag_get_tags('post', $blog->id)) { //This return them ordered by default
974 /// Start BLOG_TAGS tag
975 fwrite ($bf,start_tag("BLOG_TAGS",4,true));
976 /// Write blog tags fields
977 foreach ($tags as $tag) {
978 fwrite ($bf,start_tag("BLOG_TAG",5,true));
979 fwrite ($bf,full_tag("NAME",6,false,$tag->name));
980 fwrite ($bf,full_tag("RAWNAME",6,false,$tag->rawname));
981 fwrite ($bf,end_tag("BLOG_TAG",5,true));
983 /// End BLOG_TAGS tag
984 fwrite ($bf,end_tag("BLOG_TAGS",4,true));
988 /// Blog comments
989 /// TODO: Blog comments go here (2.0)
991 /// end blog
992 fwrite($bf, end_tag("BLOG",3,true));
994 /// Do some output
995 $counter++;
996 if ($counter % 20 == 0) {
997 echo ".";
998 if ($counter % 400 == 0) {
999 echo "<br />";
1001 backup_flush(300);
1004 rs_close($rs_blogs);
1006 /// blogs close tag
1007 $status = fwrite($bf, end_tag("BLOGS",2,true));
1010 return $status;
1013 //Prints course's blocks info (table block_instance)
1014 function backup_course_blocks ($bf,$preferences) {
1016 global $CFG;
1018 $status = true;
1020 // Read all of the block table
1021 $blocks = blocks_get_record();
1023 $pages = array();
1024 $pages[] = page_create_object(PAGE_COURSE_VIEW, $preferences->backup_course);
1026 if (!empty($CFG->showblocksonmodpages)) {
1027 // get course structure
1028 $course = get_record('course', 'id', $preferences->backup_course);
1029 $modinfo =& get_fast_modinfo($course);
1031 foreach($preferences->mods as $module) {
1032 if (!$module->backup) {
1033 continue;
1036 if (empty($modinfo->instances[$module->name])) {
1037 continue;
1040 $pagetypes = page_import_types('mod/'.$module->name.'/');
1041 if (empty($pagetypes)) {
1042 continue;
1045 foreach($pagetypes as $pagetype) {
1046 foreach($modinfo->instances[$module->name] as $cm) {
1047 if (!empty($module->instances[$cm->instance]->backup)) {
1048 $pages[] = page_create_object($pagetype, $cm->instance);
1055 //Blocks open tag
1056 fwrite ($bf,start_tag('BLOCKS',2,true));
1058 foreach($pages as $page) {
1059 if ($instances = blocks_get_by_page($page)) {
1060 //Iterate over every block
1061 foreach ($instances as $position) {
1062 foreach ($position as $instance) {
1064 //If we somehow have a block with an invalid id, skip it
1065 if(empty($blocks[$instance->blockid]->name)) {
1066 continue;
1068 $blockname = $blocks[$instance->blockid]->name;
1070 if (!$blockobj = block_instance($blockname, $instance)) {
1071 // Invalid block
1072 continue;
1075 // encode absolute links in block config
1076 $instance->configdata = $blockobj->get_backup_encoded_config();
1078 //Begin Block
1079 fwrite ($bf,start_tag('BLOCK',3,true));
1080 fwrite ($bf,full_tag('ID', 4, false,$instance->id));
1081 fwrite ($bf,full_tag('NAME',4,false,$blockname));
1082 fwrite ($bf,full_tag('PAGEID',4,false,$instance->pageid));
1083 fwrite ($bf,full_tag('PAGETYPE',4,false,$instance->pagetype));
1084 fwrite ($bf,full_tag('POSITION',4,false,$instance->position));
1085 fwrite ($bf,full_tag('WEIGHT',4,false,$instance->weight));
1086 fwrite ($bf,full_tag('VISIBLE',4,false,$instance->visible));
1087 fwrite ($bf,full_tag('CONFIGDATA',4,false,$instance->configdata));
1088 // Write instance data if needed
1089 if ($blockobj->backuprestore_instancedata_used()) {
1090 fwrite ($bf,start_tag('INSTANCEDATA',4,true));
1091 $status = $blockobj->instance_backup($bf, $preferences);
1092 fwrite ($bf,end_tag('INSTANCEDATA',4,true));
1094 $context = get_context_instance(CONTEXT_BLOCK, $instance->id);
1095 write_role_overrides_xml($bf, $context, 4);
1096 /// write role_assign code here
1097 write_role_assignments_xml($bf, $preferences, $context, 4);
1098 //End Block
1099 fwrite ($bf,end_tag('BLOCK',3,true));
1105 //Blocks close tag
1106 $status = fwrite ($bf,end_tag('BLOCKS',2,true));
1108 return $status;
1112 //Prints course's sections info (table course_sections)
1113 function backup_course_sections ($bf,$preferences) {
1115 global $CFG;
1117 $status = true;
1120 //Get info from sections
1121 $section=false;
1122 if ($sections = get_records("course_sections","course",$preferences->backup_course,"section")) {
1123 //Section open tag
1124 fwrite ($bf,start_tag("SECTIONS",2,true));
1125 //Iterate over every section (ordered by section)
1126 foreach ($sections as $section) {
1127 //Begin Section
1128 fwrite ($bf,start_tag("SECTION",3,true));
1129 fwrite ($bf,full_tag("ID",4,false,$section->id));
1130 fwrite ($bf,full_tag("NUMBER",4,false,$section->section));
1131 fwrite ($bf,full_tag("SUMMARY",4,false,$section->summary));
1132 fwrite ($bf,full_tag("VISIBLE",4,false,$section->visible));
1133 //Now print the mods in section
1134 backup_course_modules ($bf,$preferences,$section);
1135 //End section
1136 fwrite ($bf,end_tag("SECTION",3,true));
1138 //Section close tag
1139 $status = fwrite ($bf,end_tag("SECTIONS",2,true));
1142 return $status;
1146 //Prints course's format data (any data the format might want to save).
1147 function backup_format_data ($bf,$preferences) {
1148 global $CFG;
1150 // Check course format
1151 if(!($format=get_field('course','format','id',$preferences->backup_course))) {
1152 return false;
1154 // Write appropriate tag. Note that we always put this tag there even if
1155 // blank, it makes parsing easier
1156 fwrite ($bf,start_tag("FORMATDATA",2,true));
1158 $file=$CFG->dirroot."/course/format/$format/backuplib.php";
1159 if(file_exists($file)) {
1160 // If the file is there, the function must be or it's an error.
1161 require_once($file);
1162 $function=$format.'_backup_format_data';
1163 if(!function_exists($function)) {
1164 return false;
1166 if(!$function($bf,$preferences)) {
1167 return false;
1171 // This last return just checks the file writing has been ok (ish)
1172 return fwrite ($bf,end_tag("FORMATDATA",2,true));
1175 //Prints course's modules info (table course_modules)
1176 //Only for selected mods in preferences
1177 function backup_course_modules ($bf,$preferences,$section) {
1179 global $CFG;
1181 $status = true;
1183 $first_record = true;
1185 //Now print the mods in section
1186 //Extracts mod id from sequence
1187 $tok = strtok($section->sequence,",");
1188 while ($tok) {
1189 //Get module's type
1190 $moduletype = get_module_type ($preferences->backup_course,$tok);
1191 //Check if we've selected to backup that type
1192 if ($moduletype and $preferences->mods[$moduletype]->backup) {
1193 $selected = true;
1194 } else {
1195 $selected = false;
1198 if ($selected) {
1199 $context = get_context_instance(CONTEXT_MODULE, $tok);
1200 //Gets course_module data from db - verify activity exists and is enabled!
1201 $sql = "SELECT cm.*
1202 FROM {$CFG->prefix}course_modules cm
1203 JOIN {$CFG->prefix}modules m ON m.id = cm.module
1204 JOIN {$CFG->prefix}$moduletype a ON a.id = cm.instance
1205 WHERE m.visible = 1 AND cm.id = $tok";
1206 if (!$course_module = get_record_sql($sql)) {
1207 // cm exists but activity instance missing - probably caused by double clicking
1208 $tok = strtok(",");
1209 continue;
1212 //If it's the first, pring MODS tag
1213 if ($first_record) {
1214 fwrite ($bf,start_tag("MODS",4,true));
1215 $first_record = false;
1217 // if we're doing selected instances, check that too.
1218 if (is_array($preferences->mods[$moduletype]->instances)
1219 && count($preferences->mods[$moduletype]->instances)
1220 && (!array_key_exists($course_module->instance,$preferences->mods[$moduletype]->instances)
1221 || empty($preferences->mods[$moduletype]->instances[$course_module->instance]->backup))) {
1222 $tok = strtok(",");
1223 continue;
1226 // find all role values that has an override in this context
1227 $roles = get_records('role_capabilities', 'contextid', $context->id);
1229 //Print mod info from course_modules
1230 fwrite ($bf,start_tag("MOD",5,true));
1231 //Save neccesary info to backup_ids
1232 fwrite ($bf,full_tag("ID",6,false,$tok));
1233 fwrite ($bf,full_tag("TYPE",6,false,$moduletype));
1234 fwrite ($bf,full_tag("INSTANCE",6,false,$course_module->instance));
1235 fwrite ($bf,full_tag("ADDED",6,false,$course_module->added));
1236 fwrite ($bf,full_tag("SCORE",6,false,$course_module->score));
1237 fwrite ($bf,full_tag("INDENT",6,false,$course_module->indent));
1238 fwrite ($bf,full_tag("VISIBLE",6,false,$course_module->visible));
1239 fwrite ($bf,full_tag("GROUPMODE",6,false,$course_module->groupmode));
1240 fwrite ($bf,full_tag("GROUPINGID",6,false,$course_module->groupingid));
1241 fwrite ($bf,full_tag("GROUPMEMBERSONLY",6,false,$course_module->groupmembersonly));
1242 fwrite ($bf,full_tag("IDNUMBER",6,false,$course_module->idnumber));
1243 // get all the role_capabilities overrides in this mod
1244 write_role_overrides_xml($bf, $context, 6);
1245 /// write role_assign code here
1246 write_role_assignments_xml($bf, $preferences, $context, 6);
1247 /// write role_assign code here
1249 fwrite ($bf,end_tag("MOD",5,true));
1251 //check for next
1252 $tok = strtok(",");
1255 //Si ha habido modulos, final de MODS
1256 if (!$first_record) {
1257 $status =fwrite ($bf,end_tag("MODS",4,true));
1260 return $status;
1263 //Print users to xml
1264 //Only users previously calculated in backup_ids will output
1266 function backup_user_info ($bf,$preferences) {
1268 global $CFG;
1269 require_once ($CFG->dirroot.'/tag/lib.php');
1271 $status = true;
1273 // Use a recordset to for the memory handling on to
1274 // the DB and run faster
1275 $users = get_recordset_sql("SELECT b.old_id, b.table_name, b.info,
1276 u.*, m.wwwroot
1277 FROM {$CFG->prefix}backup_ids b
1278 JOIN {$CFG->prefix}user u ON b.old_id=u.id
1279 JOIN {$CFG->prefix}mnet_host m ON u.mnethostid=m.id
1280 WHERE b.backup_code = '$preferences->backup_unique_code' AND
1281 b.table_name = 'user'");
1283 //If we have users to backup
1284 if ($users && !rs_EOF($users)) {
1285 //Begin Users tag
1286 fwrite ($bf,start_tag("USERS",2,true));
1287 $counter = 0;
1288 //With every user
1289 while ($user = rs_fetch_next_record($users)) {
1290 //Begin User tag
1291 fwrite ($bf,start_tag("USER",3,true));
1292 //Output all user data
1293 fwrite ($bf,full_tag("ID",4,false,$user->id));
1294 fwrite ($bf,full_tag("AUTH",4,false,$user->auth));
1295 fwrite ($bf,full_tag("CONFIRMED",4,false,$user->confirmed));
1296 fwrite ($bf,full_tag("POLICYAGREED",4,false,$user->policyagreed));
1297 fwrite ($bf,full_tag("DELETED",4,false,$user->deleted));
1298 fwrite ($bf,full_tag("USERNAME",4,false,$user->username));
1299 fwrite ($bf,full_tag("PASSWORD",4,false,$user->password));
1300 fwrite ($bf,full_tag("IDNUMBER",4,false,$user->idnumber));
1301 fwrite ($bf,full_tag("FIRSTNAME",4,false,$user->firstname));
1302 fwrite ($bf,full_tag("LASTNAME",4,false,$user->lastname));
1303 fwrite ($bf,full_tag("EMAIL",4,false,$user->email));
1304 fwrite ($bf,full_tag("EMAILSTOP",4,false,$user->emailstop));
1305 fwrite ($bf,full_tag("ICQ",4,false,$user->icq));
1306 fwrite ($bf,full_tag("SKYPE",4,false,$user->skype));
1307 fwrite ($bf,full_tag("YAHOO",4,false,$user->yahoo));
1308 fwrite ($bf,full_tag("AIM",4,false,$user->aim));
1309 fwrite ($bf,full_tag("MSN",4,false,$user->msn));
1310 fwrite ($bf,full_tag("PHONE1",4,false,$user->phone1));
1311 fwrite ($bf,full_tag("PHONE2",4,false,$user->phone2));
1312 fwrite ($bf,full_tag("INSTITUTION",4,false,$user->institution));
1313 fwrite ($bf,full_tag("DEPARTMENT",4,false,$user->department));
1314 fwrite ($bf,full_tag("ADDRESS",4,false,$user->address));
1315 fwrite ($bf,full_tag("CITY",4,false,$user->city));
1316 fwrite ($bf,full_tag("COUNTRY",4,false,$user->country));
1317 fwrite ($bf,full_tag("LANG",4,false,$user->lang));
1318 fwrite ($bf,full_tag("THEME",4,false,$user->theme));
1319 fwrite ($bf,full_tag("TIMEZONE",4,false,$user->timezone));
1320 fwrite ($bf,full_tag("FIRSTACCESS",4,false,$user->firstaccess));
1321 fwrite ($bf,full_tag("LASTACCESS",4,false,$user->lastaccess));
1322 fwrite ($bf,full_tag("LASTLOGIN",4,false,$user->lastlogin));
1323 fwrite ($bf,full_tag("CURRENTLOGIN",4,false,$user->currentlogin));
1324 fwrite ($bf,full_tag("LASTIP",4,false,$user->lastip));
1325 fwrite ($bf,full_tag("SECRET",4,false,$user->secret));
1326 fwrite ($bf,full_tag("PICTURE",4,false,$user->picture));
1327 fwrite ($bf,full_tag("URL",4,false,$user->url));
1328 fwrite ($bf,full_tag("DESCRIPTION",4,false,$user->description));
1329 fwrite ($bf,full_tag("MAILFORMAT",4,false,$user->mailformat));
1330 fwrite ($bf,full_tag("MAILDIGEST",4,false,$user->maildigest));
1331 fwrite ($bf,full_tag("MAILDISPLAY",4,false,$user->maildisplay));
1332 fwrite ($bf,full_tag("HTMLEDITOR",4,false,$user->htmleditor));
1333 fwrite ($bf,full_tag("AJAX",4,false,$user->ajax));
1334 fwrite ($bf,full_tag("AUTOSUBSCRIBE",4,false,$user->autosubscribe));
1335 fwrite ($bf,full_tag("TRACKFORUMS",4,false,$user->trackforums));
1336 if ($user->mnethostid != $CFG->mnet_localhost_id) {
1337 fwrite ($bf,full_tag("MNETHOSTURL",4,false,$user->wwwroot));
1339 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$user->timemodified));
1341 /// write assign/override code for context_userid
1343 $user->isneeded = strpos($user->info,"needed");
1345 fwrite ($bf,start_tag("ROLES",4,true));
1346 if ($user->info != "needed" && $user->info!="") {
1347 //PRINT ROLE INFO
1348 $roles = explode(",", $user->info);
1349 foreach ($roles as $role) {
1350 if ($role!="" && $role!="needed") {
1351 fwrite ($bf,start_tag("ROLE",5,true));
1352 //Print Role info
1353 fwrite ($bf,full_tag("TYPE",6,false,$role));
1354 //Print ROLE end
1355 fwrite ($bf,end_tag("ROLE",5,true));
1359 //Needed
1360 if ($user->isneeded!==false) {
1361 //Print ROLE start
1362 fwrite ($bf,start_tag("ROLE",5,true));
1363 //Print Role info
1364 fwrite ($bf,full_tag("TYPE",6,false,"needed"));
1365 //Print ROLE end
1366 fwrite ($bf,end_tag("ROLE",5,true));
1369 //End ROLES tag
1370 fwrite ($bf,end_tag("ROLES",4,true));
1372 //Check if we have custom profile fields to backup
1373 if ($cpfields = get_records_sql("SELECT uif.shortname, uif.datatype, uid.data
1374 FROM {$CFG->prefix}user_info_field uif,
1375 {$CFG->prefix}user_info_data uid
1376 WHERE uif.id = uid.fieldid
1377 AND uid.userid = $user->id")) {
1378 //Start USER_CUSTOM_PROFILE_FIELDS tag
1379 fwrite ($bf,start_tag("USER_CUSTOM_PROFILE_FIELDS",4,true));
1380 //Write custom profile fields
1381 foreach ($cpfields as $cpfield) {
1382 fwrite ($bf,start_tag("USER_CUSTOM_PROFILE_FIELD",5,true));
1383 fwrite ($bf,full_tag("FIELD_NAME",6,false,$cpfield->shortname));
1384 fwrite ($bf,full_tag("FIELD_TYPE",6,false,$cpfield->datatype));
1385 fwrite ($bf,full_tag("FIELD_DATA",6,false,$cpfield->data));
1386 fwrite ($bf,end_tag("USER_CUSTOM_PROFILE_FIELD",5,true));
1388 //End USER_CUSTOM_PROFILE_FIELDS tag
1389 fwrite ($bf,end_tag("USER_CUSTOM_PROFILE_FIELDS",4,true));
1392 //Check if we have user tags to backup
1393 if (!empty($CFG->usetags)) {
1394 if ($tags = tag_get_tags('user', $user->id)) { //This return them ordered by default
1395 //Start USER_TAGS tag
1396 fwrite ($bf,start_tag("USER_TAGS",4,true));
1397 //Write user tags fields
1398 foreach ($tags as $tag) {
1399 fwrite ($bf,start_tag("USER_TAG",5,true));
1400 fwrite ($bf,full_tag("NAME",6,false,$tag->name));
1401 fwrite ($bf,full_tag("RAWNAME",6,false,$tag->rawname));
1402 fwrite ($bf,end_tag("USER_TAG",5,true));
1404 //End USER_TAGS tag
1405 fwrite ($bf,end_tag("USER_TAGS",4,true));
1409 //Check if we have user_preferences to backup
1410 if ($preferences_data = get_records("user_preferences","userid",$user->old_id)) {
1411 //Start USER_PREFERENCES tag
1412 fwrite ($bf,start_tag("USER_PREFERENCES",4,true));
1413 //Write each user_preference
1414 foreach ($preferences_data as $user_preference) {
1415 fwrite ($bf,start_tag("USER_PREFERENCE",5,true));
1416 fwrite ($bf,full_tag("NAME",6,false,$user_preference->name));
1417 fwrite ($bf,full_tag("VALUE",6,false,$user_preference->value));
1418 fwrite ($bf,end_tag("USER_PREFERENCE",5,true));
1420 //End USER_PREFERENCES tag
1421 fwrite ($bf,end_tag("USER_PREFERENCES",4,true));
1424 $context = get_context_instance(CONTEXT_USER, $user->old_id);
1426 write_role_overrides_xml($bf, $context, 4);
1427 /// write role_assign code here
1428 write_role_assignments_xml($bf, $preferences, $context, 4);
1429 //End User tag
1430 fwrite ($bf,end_tag("USER",3,true));
1431 //Do some output
1432 $counter++;
1433 if ($counter % 10 == 0) {
1434 echo ".";
1435 if ($counter % 200 == 0) {
1436 echo "<br />";
1438 backup_flush(300);
1441 //End Users tag
1442 fwrite ($bf,end_tag("USERS",2,true));
1443 } else {
1444 // There aren't any users.
1445 $status = true;
1448 if ($users) {
1449 rs_close($users);
1452 return $status;
1455 //Backup log info (time ordered)
1456 function backup_log_info($bf,$preferences) {
1458 global $CFG;
1460 //Number of records to get in every chunk
1461 $recordset_size = 1000;
1463 $status = true;
1465 //Counter, points to current record
1466 $counter = 0;
1468 //Count records
1469 $count_logs = count_records("log","course",$preferences->backup_course);
1471 //Pring logs header
1472 if ($count_logs > 0 ) {
1473 fwrite ($bf,start_tag("LOGS",2,true));
1475 while ($counter < $count_logs) {
1476 //Get a chunk of records
1477 $logs = get_records ("log","course",$preferences->backup_course,"time","*",$counter,$recordset_size);
1479 //We have logs
1480 if ($logs) {
1481 //Iterate
1482 foreach ($logs as $log) {
1483 //See if it is a valid module to backup
1484 if ($log->module == "course" or
1485 $log->module == "user" or
1486 (array_key_exists($log->module, $preferences->mods) and $preferences->mods[$log->module]->backup == 1)) {
1487 // logs with 'upload' in module field are ignored, there is no restore code anyway
1488 //Begin log tag
1489 fwrite ($bf,start_tag("LOG",3,true));
1491 //Output log tag
1492 fwrite ($bf,full_tag("ID",4,false,$log->id));
1493 fwrite ($bf,full_tag("TIME",4,false,$log->time));
1494 fwrite ($bf,full_tag("USERID",4,false,$log->userid));
1495 fwrite ($bf,full_tag("IP",4,false,$log->ip));
1496 fwrite ($bf,full_tag("MODULE",4,false,$log->module));
1497 fwrite ($bf,full_tag("CMID",4,false,$log->cmid));
1498 fwrite ($bf,full_tag("ACTION",4,false,$log->action));
1499 fwrite ($bf,full_tag("URL",4,false,$log->url));
1500 fwrite ($bf,full_tag("INFO",4,false,$log->info));
1502 //End log tag
1503 fwrite ($bf,end_tag("LOG",3,true));
1505 //Do some output
1506 $counter++;
1507 if ($counter % 20 == 0) {
1508 echo ".";
1509 if ($counter % 400 == 0) {
1510 echo "<br />";
1512 backup_flush(300);
1517 //End logs tag
1518 if ($count_logs > 0 ) {
1519 $status = fwrite ($bf,end_tag("LOGS",2,true));
1521 return $status;
1524 //Backup gradebook info
1525 function backup_gradebook_info($bf, $preferences) {
1526 global $CFG;
1527 require_once($CFG->libdir.'/gradelib.php');
1529 //first make sure items are properly sorted and everything is ok
1530 grade_category::fetch_course_tree($preferences->backup_course, true);
1531 grade_regrade_final_grades($preferences->backup_course);
1533 $status = true;
1535 // see if ALL grade items of type mod of this course are being backed up
1536 // if not, we do not need to backup grade category and associated grade items/grades
1537 $backupall = true;
1539 if ($grade_items = get_records_sql("SELECT *
1540 FROM {$CFG->prefix}grade_items
1541 WHERE courseid = $preferences->backup_course
1542 AND itemtype = 'mod'")) {
1543 foreach ($grade_items as $grade_item) {
1544 // get module information
1545 // if no user data selected, we do not backup categories
1546 if (!backup_userdata_selected($preferences,$grade_item->itemmodule,$grade_item->iteminstance)) {
1547 $backupall = false;
1548 break;
1551 unset($grade_items); //free memory
1554 //Gradebook header
1555 fwrite ($bf,start_tag("GRADEBOOK",2,true));
1557 $status = backup_gradebook_outcomes_info($bf, $preferences);
1558 $status = backup_gradebook_grade_letters_info($bf,$preferences);
1560 // Now backup grade_item (inside grade_category)
1561 if ($backupall) {
1562 $status = backup_gradebook_category_info($bf,$preferences);
1565 $status = backup_gradebook_item_info($bf,$preferences, $backupall);
1567 // backup gradebook histories
1568 if ($preferences->backup_gradebook_history) {
1569 $status = backup_gradebook_outcomes_history($bf, $preferences);
1570 $status = backup_gradebook_categories_history_info($bf, $preferences);
1571 $status = backup_gradebook_items_history_info($bf, $preferences);
1572 $status = backup_gradebook_grades_history_info($bf, $preferences);
1575 //Gradebook footer
1576 $status = fwrite ($bf,end_tag("GRADEBOOK",2,true));
1577 return $status;
1580 function backup_gradebook_category_info($bf, $preferences) {
1581 global $CFG;
1582 $status = true;
1584 // get grade categories in proper order - specified in category grade items
1585 $course_item = grade_item::fetch_course_item($preferences->backup_course);
1586 $grade_categories = get_records_sql("SELECT gc.*, gi.sortorder
1587 FROM {$CFG->prefix}grade_categories gc
1588 JOIN {$CFG->prefix}grade_items gi
1589 ON (gi.iteminstance = gc.id)
1590 WHERE gc.courseid = $preferences->backup_course
1591 AND (gi.itemtype='course' OR gi.itemtype='category')
1592 ORDER BY gi.sortorder ASC");
1594 if ($grade_categories) {
1595 //Begin grade_categories tag
1596 fwrite ($bf,start_tag("GRADE_CATEGORIES",3,true));
1597 //Iterate for each category
1598 foreach ($grade_categories as $grade_category) {
1599 //Begin grade_category
1600 fwrite ($bf,start_tag("GRADE_CATEGORY",4,true));
1601 //Output individual fields
1602 fwrite ($bf,full_tag("ID",5,false,$grade_category->id));
1604 // not keeping path and depth because they can be derived
1605 fwrite ($bf,full_tag("PARENT",5,false,$grade_category->parent));
1606 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_category->fullname));
1607 fwrite ($bf,full_tag("AGGREGATION",5,false,$grade_category->aggregation));
1608 fwrite ($bf,full_tag("KEEPHIGH",5,false,$grade_category->keephigh));
1609 fwrite ($bf,full_tag("DROPLOW",5,false,$grade_category->droplow));
1610 fwrite ($bf,full_tag("AGGREGATEONLYGRADED",5,false,$grade_category->aggregateonlygraded));
1611 fwrite ($bf,full_tag("AGGREGATEOUTCOMES",5,false,$grade_category->aggregateoutcomes));
1612 fwrite ($bf,full_tag("AGGREGATESUBCATS",5,false,$grade_category->aggregatesubcats));
1613 fwrite ($bf,full_tag("TIMECREATED",5,false,$grade_category->timecreated));
1614 fwrite ($bf,full_tag("TIMEMODIFIED",5,false,$grade_category->timemodified));
1616 //End grade_category
1617 fwrite ($bf,end_tag("GRADE_CATEGORY",4,true));
1619 //End grade_categories tag
1620 $status = fwrite ($bf,end_tag("GRADE_CATEGORIES",3,true));
1623 return $status;
1626 //Backup gradebook_item (called from backup_gradebook_info
1627 function backup_gradebook_item_info($bf, $preferences, $backupall) {
1628 global $CFG;
1630 $status = true;
1631 // get all the grade_items, ordered by sort order since upon restoring, it is not always
1632 // possible to use the same sort order. We could at least preserve the sortorder by restoring
1633 // grade_items in the original sortorder
1634 if ($grade_items = get_records_sql("SELECT *
1635 FROM {$CFG->prefix}grade_items
1636 WHERE courseid = $preferences->backup_course
1637 ORDER BY sortorder ASC")) {
1639 //Begin grade_items tag
1640 fwrite ($bf,start_tag("GRADE_ITEMS",3,true));
1641 //Iterate over each item
1642 foreach ($grade_items as $item) {
1643 // Instantiate a grade_item object, to access its methods
1644 $grade_item = new grade_item($item, false);
1646 // do not restore if this grade_item is a mod, and
1647 if ($grade_item->itemtype == 'mod') {
1648 //MDL-12463 - exclude grade_items of instances not chosen for backup
1649 if (empty($preferences->mods[$grade_item->itemmodule]->instances[$grade_item->iteminstance]->backup)) {
1650 continue;
1653 } else if ($grade_item->itemtype == 'category') {
1654 // if not all grade items are being backed up
1655 // we ignore this type of grade_item and grades associated
1656 if (!$backupall) {
1657 continue;
1661 //Begin grade_item
1662 fwrite ($bf,start_tag("GRADE_ITEM",4,true));
1663 //Output individual fields
1665 fwrite ($bf,full_tag("ID",5,false,$grade_item->id));
1666 fwrite ($bf,full_tag("CATEGORYID",5,false,$grade_item->categoryid));
1667 fwrite ($bf,full_tag("ITEMNAME",5,false,$grade_item->itemname));
1668 fwrite ($bf,full_tag("ITEMTYPE",5,false,$grade_item->itemtype));
1669 fwrite ($bf,full_tag("ITEMMODULE",5,false,$grade_item->itemmodule));
1670 fwrite ($bf,full_tag("ITEMINSTANCE",5,false,$grade_item->iteminstance));
1671 fwrite ($bf,full_tag("ITEMNUMBER",5,false,$grade_item->itemnumber));
1672 fwrite ($bf,full_tag("ITEMINFO",5,false,$grade_item->iteminfo));
1673 fwrite ($bf,full_tag("IDNUMBER",5,false,$grade_item->idnumber));
1674 // use [idnumber] in calculation instead of [#giXXX#]
1675 fwrite ($bf,full_tag("CALCULATION",5,false,$grade_item->get_calculation()));
1676 fwrite ($bf,full_tag("GRADETYPE",5,false,$grade_item->gradetype));
1677 fwrite ($bf,full_tag("GRADEMAX",5,false,$grade_item->grademax));
1678 fwrite ($bf,full_tag("GRADEMIN",5,false,$grade_item->grademin));
1679 fwrite ($bf,full_tag("SCALEID",5,false,$grade_item->scaleid));
1680 fwrite ($bf,full_tag("OUTCOMEID",5,false,$grade_item->outcomeid));
1681 fwrite ($bf,full_tag("GRADEPASS",5,false,$grade_item->gradepass));
1682 fwrite ($bf,full_tag("MULTFACTOR",5,false,$grade_item->multfactor));
1683 fwrite ($bf,full_tag("PLUSFACTOR",5,false,$grade_item->plusfactor));
1684 fwrite ($bf,full_tag("AGGREGATIONCOEF",5,false,$grade_item->aggregationcoef));
1685 fwrite ($bf,full_tag("DISPLAY",5,false,$grade_item->display));
1686 fwrite ($bf,full_tag("DECIMALS",5,false,$grade_item->decimals));
1687 fwrite ($bf,full_tag("HIDDEN",5,false,$grade_item->hidden));
1688 fwrite ($bf,full_tag("LOCKED",5,false,$grade_item->locked));
1689 fwrite ($bf,full_tag("LOCKTIME",5,false,$grade_item->locktime));
1690 fwrite ($bf,full_tag("NEEDSUPDATE",5,false,$grade_item->needsupdate));
1691 fwrite ($bf,full_tag("TIMECREATED",5,false,$grade_item->timecreated));
1692 fwrite ($bf,full_tag("TIMEMODIFIED",5,false,$grade_item->timemodified));
1694 // back up the other stuff here
1695 // mod grades should only be backed up if selected
1696 if ($grade_item->itemtype == 'mod' && !backup_userdata_selected($preferences,$grade_item->itemmodule,$grade_item->iteminstance)) {
1697 // do not write grades if a mod grade_item is being restored
1698 // but userdata is not selected
1699 } else {
1700 $status = backup_gradebook_grades_info($bf,$preferences,$grade_item->id);
1702 //End grade_item
1703 fwrite ($bf,end_tag("GRADE_ITEM",4,true));
1705 //End grade_items tag
1706 $status = fwrite ($bf,end_tag("GRADE_ITEMS",3,true));
1709 return $status;
1711 //Backup gradebook_item (called from backup_gradebook_info
1713 function backup_gradebook_grade_letters_info($bf, $preferences) {
1714 global $CFG;
1715 $status = true;
1717 $context = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
1718 $grade_letters = get_records_sql("SELECT *
1719 FROM {$CFG->prefix}grade_letters
1720 WHERE contextid = $context->id");
1721 if ($grade_letters) {
1722 //Begin grade_l tag
1723 fwrite ($bf,start_tag("GRADE_LETTERS",3,true));
1724 //Iterate for each letter
1725 foreach ($grade_letters as $grade_letter) {
1726 //Begin grade_letter
1727 fwrite ($bf,start_tag("GRADE_LETTER",4,true));
1728 //Output individual fields
1729 fwrite ($bf,full_tag("ID",5,false,$grade_letter->id));
1730 fwrite ($bf,full_tag("LOWERBOUNDARY",5,false,$grade_letter->lowerboundary));
1731 fwrite ($bf,full_tag("LETTER",5,false,$grade_letter->letter));
1733 //End grade_letter
1734 fwrite ($bf,end_tag("GRADE_LETTER",4,true));
1736 //End grade_categories tag
1737 $status = fwrite ($bf,end_tag("GRADE_LETTERS",3,true));
1740 return $status;
1743 function backup_gradebook_outcomes_info($bf, $preferences) {
1745 global $CFG;
1746 $status = true;
1747 // only back up courses already in the grade_outcomes_courses table
1748 $grade_outcomes = get_records_sql("SELECT go.*
1749 FROM {$CFG->prefix}grade_outcomes go
1750 JOIN {$CFG->prefix}grade_outcomes_courses goc
1751 ON (goc.outcomeid = go.id)
1752 WHERE goc.courseid = $preferences->backup_course");
1754 if (!empty($grade_outcomes)) {
1755 //Begin grade_outcomes tag
1756 fwrite ($bf,start_tag("GRADE_OUTCOMES",3,true));
1757 //Iterate for each outcome
1758 foreach ($grade_outcomes as $grade_outcome) {
1759 //Begin grade_outcome
1760 fwrite ($bf,start_tag("GRADE_OUTCOME",4,true));
1761 //Output individual fields
1763 fwrite ($bf,full_tag("ID",5,false,$grade_outcome->id));
1764 fwrite ($bf,full_tag("COURSEID",5,false,$grade_outcome->courseid));
1765 fwrite ($bf,full_tag("SHORTNAME",5,false,$grade_outcome->shortname));
1766 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_outcome->fullname));
1767 fwrite ($bf,full_tag("SCALEID",5,false,$grade_outcome->scaleid));
1768 fwrite ($bf,full_tag("DESCRIPTION",5,false,$grade_outcome->description));
1769 fwrite ($bf,full_tag("TIMECREATED",5,false,$grade_outcome->timecreated));
1770 fwrite ($bf,full_tag("TIMEMODIFIED",5,false,$grade_outcome->timemodified));
1771 fwrite ($bf,full_tag("USERMODIFIED",5,false,$grade_outcome->usermodified));
1773 //End grade_outcome
1774 fwrite ($bf,end_tag("GRADE_OUTCOME",4,true));
1776 //End grade_outcomes tag
1777 $status = fwrite ($bf,end_tag("GRADE_OUTCOMES",3,true));
1779 return $status;
1782 function backup_gradebook_grades_info($bf,$preferences, $itemid) {
1784 global $CFG;
1786 $status = true;
1788 // find all grades belonging to this item
1789 if ($grades = get_records('grade_grades', 'itemid', $itemid)) {
1790 fwrite ($bf,start_tag("GRADE_GRADES",5,true));
1791 foreach ($grades as $grade) {
1792 /// Grades are only sent to backup if the user is one target user
1793 if (backup_getid($preferences->backup_unique_code, 'user', $grade->userid)) {
1794 fwrite ($bf,start_tag("GRADE",6,true));
1795 fwrite ($bf,full_tag("ID",7,false,$grade->id));
1796 fwrite ($bf,full_tag("USERID",7,false,$grade->userid));
1797 fwrite ($bf,full_tag("RAWGRADE",7,false,$grade->rawgrade));
1798 fwrite ($bf,full_tag("RAWGRADEMAX",7,false,$grade->rawgrademax));
1799 fwrite ($bf,full_tag("RAWGRADEMIN",7,false,$grade->rawgrademin));
1800 fwrite ($bf,full_tag("RAWSCALEID",7,false,$grade->rawscaleid));
1801 fwrite ($bf,full_tag("USERMODIFIED",7,false,$grade->usermodified));
1802 fwrite ($bf,full_tag("FINALGRADE",7,false,$grade->finalgrade));
1803 fwrite ($bf,full_tag("HIDDEN",7,false,$grade->hidden));
1804 fwrite ($bf,full_tag("LOCKED",7,false,$grade->locked));
1805 fwrite ($bf,full_tag("LOCKTIME",7,false,$grade->locktime));
1806 fwrite ($bf,full_tag("EXPORTED",7,false,$grade->exported));
1807 fwrite ($bf,full_tag("OVERRIDDEN",7,false,$grade->overridden));
1808 fwrite ($bf,full_tag("EXCLUDED",7,false,$grade->excluded));
1809 fwrite ($bf,full_tag("FEEDBACK",7,false,$grade->feedback));
1810 fwrite ($bf,full_tag("FEEDBACKFORMAT",7,false,$grade->feedbackformat));
1811 fwrite ($bf,full_tag("INFORMATION",7,false,$grade->information));
1812 fwrite ($bf,full_tag("INFORMATIONFORMAT",7,false,$grade->informationformat));
1813 fwrite ($bf,full_tag("TIMECREATED",7,false,$grade->timecreated));
1814 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$grade->timemodified));
1815 fwrite ($bf,end_tag("GRADE",6,true));
1818 $status = fwrite ($bf,end_tag("GRADE_GRADES",5,true));
1820 return $status;
1823 function backup_gradebook_categories_history_info($bf, $preferences) {
1825 global $CFG;
1826 $status = true;
1828 // find all grade categories history
1829 if ($chs = get_records('grade_categories_history', 'courseid', $preferences->backup_course)) {
1830 fwrite ($bf,start_tag("GRADE_CATEGORIES_HISTORIES",5,true));
1831 foreach ($chs as $ch) {
1832 fwrite ($bf,start_tag("GRADE_CATEGORIES_HISTORY",6,true));
1833 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1834 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1835 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1836 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1837 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1838 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1839 fwrite ($bf,full_tag("PARENT",7,false,$ch->parent));
1840 fwrite ($bf,full_tag("DEPTH",7,false,$ch->depth));
1841 fwrite ($bf,full_tag("PATH",7,false,$ch->path));
1842 fwrite ($bf,full_tag("FULLNAME",7,false,$ch->fullname));
1843 fwrite ($bf,full_tag("AGGRETGATION",7,false,$ch->aggregation));
1844 fwrite ($bf,full_tag("KEEPHIGH",7,false,$ch->keephigh));
1845 fwrite ($bf,full_tag("DROPLOW",7,false,$ch->droplow));
1846 fwrite ($bf,full_tag("AGGREGATEONLYGRADED",7,false,$ch->aggregateonlygraded));
1847 fwrite ($bf,full_tag("AGGREGATEOUTCOMES",7,false,$ch->aggregateoutcomes));
1848 fwrite ($bf,full_tag("AGGREGATESUBCATS",7,false,$ch->aggregatesubcats));
1849 fwrite ($bf,end_tag("GRADE_CATEGORIES_HISTORY",6,true));
1851 $status = fwrite ($bf,end_tag("GRADE_CATEGORIES_HISTORIES",5,true));
1853 return $status;
1856 function backup_gradebook_grades_history_info($bf, $preferences) {
1858 global $CFG;
1859 $status = true;
1861 // find all grade categories history
1862 if ($chs = get_records_sql("SELECT ggh.*
1863 FROM {$CFG->prefix}grade_grades_history ggh
1864 JOIN {$CFG->prefix}grade_items gi
1865 ON gi.id = ggh.itemid
1866 WHERE gi.courseid = $preferences->backup_course")) {
1867 fwrite ($bf,start_tag("GRADE_GRADES_HISTORIES",5,true));
1868 foreach ($chs as $ch) {
1869 /// Grades are only sent to backup if the user is one target user
1870 if (backup_getid($preferences->backup_unique_code, 'user', $ch->userid)) {
1871 fwrite ($bf,start_tag("GRADE_GRADES_HISTORY",6,true));
1872 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1873 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1874 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1875 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1876 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1877 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1878 fwrite ($bf,full_tag("ITEMID",7,false,$ch->itemid));
1879 fwrite ($bf,full_tag("USERID",7,false,$ch->userid));
1880 fwrite ($bf,full_tag("RAWGRADE",7,false,$ch->rawgrade));
1881 fwrite ($bf,full_tag("RAWGRADEMAX",7,false,$ch->rawgrademax));
1882 fwrite ($bf,full_tag("RAWGRADEMIN",7,false,$ch->rawgrademin));
1883 fwrite ($bf,full_tag("RAWSCALEID",7,false,$ch->rawscaleid));
1884 fwrite ($bf,full_tag("USERMODIFIED",7,false,$ch->usermodified));
1885 fwrite ($bf,full_tag("FINALGRADE",7,false,$ch->finalgrade));
1886 fwrite ($bf,full_tag("HIDDEN",7,false,$ch->hidden));
1887 fwrite ($bf,full_tag("LOCKED",7,false,$ch->locked));
1888 fwrite ($bf,full_tag("LOCKTIME",7,false,$ch->locktime));
1889 fwrite ($bf,full_tag("EXPORTED",7,false,$ch->exported));
1890 fwrite ($bf,full_tag("OVERRIDDEN",7,false,$ch->overridden));
1891 fwrite ($bf,full_tag("EXCLUDED",7,false,$ch->excluded));
1892 fwrite ($bf,full_tag("FEEDBACK",7,false,$ch->feedback));
1893 fwrite ($bf,full_tag("FEEDBACKFORMAT",7,false,$ch->feedbackformat));
1894 fwrite ($bf,full_tag("INFORMATION",7,false,$ch->information));
1895 fwrite ($bf,full_tag("INFORMATIONFORMAT",7,false,$ch->informationformat));
1896 fwrite ($bf,end_tag("GRADE_GRADES_HISTORY",6,true));
1899 $status = fwrite ($bf,end_tag("GRADE_GRADES_HISTORIES",5,true));
1901 return $status;
1904 function backup_gradebook_items_history_info($bf, $preferences) {
1906 global $CFG;
1907 $status = true;
1909 // find all grade categories history
1910 if ($chs = get_records('grade_items_history','courseid', $preferences->backup_course)) {
1911 fwrite ($bf,start_tag("GRADE_ITEM_HISTORIES",5,true));
1912 foreach ($chs as $ch) {
1913 fwrite ($bf,start_tag("GRADE_ITEM_HISTORY",6,true));
1914 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1915 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1916 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1917 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1918 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1919 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1920 fwrite ($bf,full_tag("CATEGORYID",7,false,$ch->categoryid));
1921 fwrite ($bf,full_tag("ITEMNAME",7,false,$ch->itemname));
1922 fwrite ($bf,full_tag("ITEMTYPE",7,false,$ch->itemtype));
1923 fwrite ($bf,full_tag("ITEMMODULE",7,false,$ch->itemmodule));
1924 fwrite ($bf,full_tag("ITEMINSTANCE",7,false,$ch->iteminstance));
1925 fwrite ($bf,full_tag("ITEMNUMBER",7,false,$ch->itemnumber));
1926 fwrite ($bf,full_tag("ITEMINFO",7,false,$ch->iteminfo));
1927 fwrite ($bf,full_tag("IDNUMBER",7,false,$ch->idnumber));
1928 fwrite ($bf,full_tag("CALCULATION",7,false,$ch->calculation));
1929 fwrite ($bf,full_tag("GRADETYPE",7,false,$ch->gradetype));
1930 fwrite ($bf,full_tag("GRADEMAX",7,false,$ch->grademax));
1931 fwrite ($bf,full_tag("GRADEMIN",7,false,$ch->grademin));
1932 fwrite ($bf,full_tag("SCALEID",7,false,$ch->scaleid));
1933 fwrite ($bf,full_tag("OUTCOMEID",7,false,$ch->outcomeid));
1934 fwrite ($bf,full_tag("GRADEPASS",7,false,$ch->gradepass));
1935 fwrite ($bf,full_tag("MULTFACTOR",7,false,$ch->multfactor));
1936 fwrite ($bf,full_tag("PLUSFACTOR",7,false,$ch->plusfactor));
1937 fwrite ($bf,full_tag("AGGREGATIONCOEF",7,false,$ch->aggregationcoef));
1938 fwrite ($bf,full_tag("SORTORDER",7,false,$ch->sortorder));
1939 //fwrite ($bf,full_tag("DISPLAY",7,false,$ch->display));
1940 //fwrite ($bf,full_tag("DECIMALS",7,false,$ch->decimals));
1941 fwrite ($bf,full_tag("HIDDEN",7,false,$ch->hidden));
1942 fwrite ($bf,full_tag("LOCKED",7,false,$ch->locked));
1943 fwrite ($bf,full_tag("LOCKTIME",7,false,$ch->locktime));
1944 fwrite ($bf,full_tag("NEEDSUPDATE",7,false,$ch->needsupdate));
1945 fwrite ($bf,end_tag("GRADE_ITEM_HISTORY",6,true));
1947 $status = fwrite ($bf,end_tag("GRADE_ITEM_HISTORIES",5,true));
1950 return $status;
1953 function backup_gradebook_outcomes_history($bf, $preferences) {
1954 global $CFG;
1955 $status = true;
1957 // find all grade categories history
1958 if ($chs = get_records('grade_outcomes_history','courseid', $preferences->backup_course)) {
1959 fwrite ($bf,start_tag("GRADE_OUTCOME_HISTORIES",5,true));
1960 foreach ($chs as $ch) {
1961 fwrite ($bf,start_tag("GRADE_OUTCOME_HISTORY",6,true));
1962 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1963 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1964 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1965 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1966 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1967 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1968 fwrite ($bf,full_tag("SHORTNAME",7,false,$ch->shortname));
1969 fwrite ($bf,full_tag("FULLNAME",7,false,$ch->fullname));
1970 fwrite ($bf,full_tag("SCALEID",7,false,$ch->scaleid));
1971 fwrite ($bf,full_tag("DESCRIPTION",7,false,$ch->description));
1972 fwrite ($bf,end_tag("GRADE_OUTCOME_HISTORY",6,true));
1974 $status = fwrite ($bf,end_tag("GRADE_OUTCOME_HISTORIES",5,true));
1976 return $status;
1979 //Backup scales info (common and course scales)
1980 function backup_scales_info($bf,$preferences) {
1982 global $CFG;
1984 $status = true;
1986 //Counter, points to current record
1987 $counter = 0;
1989 //Get scales (common and course scales)
1990 $scales = get_records_sql("SELECT id, courseid, userid, name, scale, description, timemodified
1991 FROM {$CFG->prefix}scale
1992 WHERE courseid = 0 OR courseid = $preferences->backup_course");
1994 //Copy only used scales to $backupscales. They will be in backup (unused no). See Bug 1223.
1995 $backupscales = array();
1996 if ($scales) {
1997 foreach ($scales as $scale) {
1998 if (course_scale_used($preferences->backup_course, $scale->id)) {
1999 $backupscales[] = $scale;
2004 //Pring scales header
2005 if ($backupscales) {
2006 //Pring scales header
2007 fwrite ($bf,start_tag("SCALES",2,true));
2008 //Iterate
2009 foreach ($backupscales as $scale) {
2010 //Begin scale tag
2011 fwrite ($bf,start_tag("SCALE",3,true));
2012 //Output scale tag
2013 fwrite ($bf,full_tag("ID",4,false,$scale->id));
2014 fwrite ($bf,full_tag("COURSEID",4,false,$scale->courseid));
2015 fwrite ($bf,full_tag("USERID",4,false,$scale->userid));
2016 fwrite ($bf,full_tag("NAME",4,false,$scale->name));
2017 fwrite ($bf,full_tag("SCALETEXT",4,false,$scale->scale));
2018 fwrite ($bf,full_tag("DESCRIPTION",4,false,$scale->description));
2019 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$scale->timemodified));
2020 //End scale tag
2021 fwrite ($bf,end_tag("SCALE",3,true));
2023 //End scales tag
2024 $status = fwrite ($bf,end_tag("SCALES",2,true));
2026 return $status;
2029 //Backup events info (course events)
2030 function backup_events_info($bf,$preferences) {
2032 global $CFG;
2034 $status = true;
2036 //Counter, points to current record
2037 $counter = 0;
2039 //Get events (course events)
2040 $events = get_records_select("event","courseid='$preferences->backup_course' AND instance='0'","id");
2042 //Pring events header
2043 if ($events) {
2044 //Pring events header
2045 fwrite ($bf,start_tag("EVENTS",2,true));
2046 //Iterate
2047 foreach ($events as $event) {
2048 //Begin event tag
2049 fwrite ($bf,start_tag("EVENT",3,true));
2050 //Output event tag
2051 fwrite ($bf,full_tag("ID",4,false,$event->id));
2052 fwrite ($bf,full_tag("NAME",4,false,$event->name));
2053 fwrite ($bf,full_tag("DESCRIPTION",4,false,$event->description));
2054 fwrite ($bf,full_tag("FORMAT",4,false,$event->format));
2055 fwrite ($bf,full_tag("GROUPID",4,false,$event->groupid));
2056 fwrite ($bf,full_tag("USERID",4,false,$event->userid));
2057 fwrite ($bf,full_tag("REPEATID",4,false,$event->repeatid));
2058 fwrite ($bf,full_tag("EVENTTYPE",4,false,$event->eventtype));
2059 fwrite ($bf,full_tag("MODULENAME",4,false,$event->modulename));
2060 fwrite ($bf,full_tag("TIMESTART",4,false,$event->timestart));
2061 fwrite ($bf,full_tag("TIMEDURATION",4,false,$event->timeduration));
2062 fwrite ($bf,full_tag("VISIBLE",4,false,$event->visible));
2063 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$event->timemodified));
2064 //End event tag
2065 fwrite ($bf,end_tag("EVENT",3,true));
2067 //End events tag
2068 $status = fwrite ($bf,end_tag("EVENTS",2,true));
2070 return $status;
2073 //Backup groups info
2074 function backup_groups_info($bf,$preferences) {
2076 global $CFG;
2078 $status = true;
2079 $status2 = true;
2081 //Get groups
2082 $groups = get_records("groups","courseid",$preferences->backup_course);
2084 //Pring groups header
2085 if ($groups) {
2086 //Pring groups header
2087 fwrite ($bf,start_tag("GROUPS",2,true));
2088 //Iterate
2089 foreach ($groups as $group) {
2090 //Begin group tag
2091 fwrite ($bf,start_tag("GROUP",3,true));
2092 //Output group contents
2093 fwrite ($bf,full_tag("ID",4,false,$group->id));
2094 //fwrite ($bf,full_tag("COURSEID",4,false,$group->courseid));
2095 fwrite ($bf,full_tag("NAME",4,false,$group->name));
2096 fwrite ($bf,full_tag("DESCRIPTION",4,false,$group->description));
2097 fwrite ($bf,full_tag("ENROLMENTKEY",4,false,$group->enrolmentkey));
2098 fwrite ($bf,full_tag("PICTURE",4,false,$group->picture));
2099 fwrite ($bf,full_tag("HIDEPICTURE",4,false,$group->hidepicture));
2100 fwrite ($bf,full_tag("TIMECREATED",4,false,$group->timecreated));
2101 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$group->timemodified));
2103 //Now, backup groups_members, only if users are included
2104 if ($preferences->backup_users != 2) {
2105 $status2 = backup_groups_members_info($bf,$preferences,$group->id);
2108 //End group tag
2109 fwrite ($bf,end_tag("GROUP",3,true));
2111 //End groups tag
2112 $status = fwrite ($bf,end_tag("GROUPS",2,true));
2114 //Now save group_files
2115 if ($status && $status2) {
2116 $status2 = backup_copy_group_files($preferences);
2119 return ($status && $status2);
2122 //Backup groups_members info
2123 function backup_groups_members_info($bf,$preferences,$groupid) {
2125 global $CFG;
2127 $status = true;
2129 //Get groups_members that are being included in backup
2130 $groups_members = get_records_sql("SELECT gm.*
2131 FROM {$CFG->prefix}groups_members gm,
2132 {$CFG->prefix}backup_ids bi
2133 WHERE gm.groupid = $groupid
2134 AND bi.backup_code = $preferences->backup_unique_code
2135 AND bi.table_name = 'user'");
2137 //Pring groups_members header
2138 if ($groups_members) {
2139 //Pring groups_members header
2140 fwrite ($bf,start_tag("MEMBERS",4,true));
2141 //Iterate
2142 foreach ($groups_members as $group_member) {
2143 //Begin group_member tag
2144 fwrite ($bf,start_tag("MEMBER",5,true));
2145 //Output group_member contents
2146 fwrite ($bf,full_tag("GROUPID",6,false,$group_member->groupid));
2147 fwrite ($bf,full_tag("USERID",6,false,$group_member->userid));
2148 fwrite ($bf,full_tag("TIMEADDED",6,false,$group_member->timeadded));
2149 //End group_member tag
2150 fwrite ($bf,end_tag("MEMBER",5,true));
2152 //End groups_members tag
2153 $status = fwrite ($bf,end_tag("MEMBERS",4,true));
2155 return $status;
2158 //Backup groupings info
2159 function backup_groupings_info($bf,$preferences) {
2161 global $CFG;
2163 $status = true;
2165 //Get groups
2166 $groupings = get_records("groupings","courseid",$preferences->backup_course);
2168 //Pring groups header
2169 if ($groupings) {
2170 //Pring groups header
2171 fwrite ($bf,start_tag("GROUPINGS",2,true));
2172 //Iterate
2173 foreach ($groupings as $grouping) {
2174 //Begin group tag
2175 fwrite ($bf,start_tag("GROUPING",3,true));
2176 //Output group contents
2177 fwrite ($bf,full_tag("ID",4,false,$grouping->id));
2178 //fwrite ($bf,full_tag("COURSEID",4,false,$grouping->courseid));
2179 fwrite ($bf,full_tag("NAME",4,false,$grouping->name));
2180 fwrite ($bf,full_tag("DESCRIPTION",4,false,$grouping->description));
2181 fwrite ($bf,full_tag("CONFIGDATA",4,false,$grouping->configdata));
2182 fwrite ($bf,full_tag("TIMECREATED",4,false,$grouping->timecreated));
2183 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$grouping->timemodified));
2185 //End group tag
2186 fwrite ($bf,end_tag("GROUPING",3,true));
2188 //End groups tag
2189 $status = fwrite ($bf,end_tag("GROUPINGS",2,true));
2191 //(Now save grouping_files)
2193 return $status;
2196 //Backup groupings-groups info
2197 function backup_groupings_groups_info($bf,$preferences) {
2199 global $CFG;
2201 $status = true;
2203 //Get grouping_groups
2204 $courseid = $preferences->backup_course;
2205 $sql = "SELECT gg.* FROM {$CFG->prefix}groupings g, {$CFG->prefix}groupings_groups gg
2206 WHERE g.courseid=$courseid AND g.id=gg.groupingid";
2207 $grouping_groups = get_records_sql($sql);
2209 //Pring grouping_groups header
2210 if ($grouping_groups) {
2211 //Pring grouping_groups header
2212 fwrite ($bf,start_tag("GROUPINGSGROUPS",2,true));
2213 //Iterate
2214 foreach ($grouping_groups as $members) {
2215 //Begin grouping_group tag
2216 fwrite ($bf,start_tag("GROUPINGGROUP",3,true));
2217 //Output group_member contents
2218 fwrite ($bf,full_tag("ID",4,false,$members->id));
2219 fwrite ($bf,full_tag("GROUPINGID",4,false,$members->groupingid));
2220 fwrite ($bf,full_tag("GROUPID",4,false,$members->groupid));
2221 fwrite ($bf,full_tag("TIMEADDED",4,false,$members->timeadded));
2222 //End grouping_group tag
2223 fwrite ($bf,end_tag("GROUPINGGROUP",3,true));
2225 //End grouping_groups tag
2226 $status = fwrite ($bf,end_tag("GROUPINGSGROUPS",2,true));
2228 return $status;
2231 //Start the modules tag
2232 function backup_modules_start ($bf,$preferences) {
2234 return fwrite ($bf,start_tag("MODULES",2,true));
2237 //End the modules tag
2238 function backup_modules_end ($bf,$preferences) {
2240 return fwrite ($bf,end_tag("MODULES",2,true));
2243 //This function makes all the necesary calls to every mod
2244 //to export itself and its files !!!
2245 function backup_module($bf,$preferences,$module) {
2247 global $CFG;
2249 $status = true;
2250 $statusm = true;
2252 require_once($CFG->dirroot.'/mod/'.$module.'/backuplib.php');
2254 if (isset($preferences->mods[$module]->instances)
2255 && is_array($preferences->mods[$module]->instances)) {
2256 $onemodbackup = $module.'_backup_one_mod';
2257 if (function_exists($onemodbackup)) {
2258 foreach ($preferences->mods[$module]->instances as $instance => $object) {
2259 if (!empty($object->backup)) {
2260 $statusm = $onemodbackup($bf,$preferences,$instance);
2261 if (!$statusm) {
2262 if (!defined('BACKUP_SILENTLY')) {
2263 notify('backup of '.$module.'-'.$object->name.' failed.');
2265 $status = false;
2269 } else {
2270 $status = false;
2272 } else { // whole module.
2273 //First, re-check if necessary functions exists
2274 $modbackup = $module."_backup_mods";
2275 if (function_exists($modbackup)) {
2276 //Call the function
2277 $status = $modbackup($bf,$preferences);
2278 } else {
2279 //Something was wrong. Function should exist.
2280 $status = false;
2284 return $status;
2288 //This function encode things to make backup multi-site fully functional
2289 //It does this conversions:
2290 // - $CFG->wwwroot/file.php/courseid ------------------> $@FILEPHP@$ (slasharguments links)
2291 // - $CFG->wwwroot/file.php?file=/courseid ------------> $@FILEPHP@$ (non-slasharguments links)
2292 // - Every module xxxx_encode_content_links() is executed too
2294 function backup_encode_absolute_links($content) {
2296 global $CFG,$preferences;
2298 /// MDL-14072: Prevent NULLs, empties and numbers to be processed by the
2299 /// heavy interlinking. Just a few cpu cycles saved.
2300 if ($content === NULL) {
2301 return NULL;
2302 } else if ($content === '') {
2303 return '';
2304 } else if (is_numeric($content)) {
2305 return $content;
2308 //Use one static variable to cache all the require_once calls that,
2309 //under PHP5 seems to increase load too much, and we are requiring
2310 //them here thousands of times (one per content). MDL-8700.
2311 //Once fixed by PHP, we'll delete this hack
2313 static $includedfiles;
2314 if (!isset($includedfiles)) {
2315 $includedfiles = array();
2318 //Check if preferences is ok. If it isn't set, we are
2319 //in a scheduled_backup to we are able to get a copy
2320 //from CFG->backup_preferences
2321 if (!isset($preferences)) {
2322 $mypreferences = $CFG->backup_preferences;
2323 } else {
2324 //We are in manual backups so global preferences must exist!!
2325 $mypreferences = $preferences;
2328 //First, we check for every call to file.php inside the course
2329 $search = array($CFG->wwwroot.'/file.php/'.$mypreferences->backup_course,
2330 $CFG->wwwroot.'/file.php?file=/'.$mypreferences->backup_course);
2332 $replace = array('$@FILEPHP@$','$@FILEPHP@$');
2334 $result = str_replace($search,$replace,$content);
2336 foreach ($mypreferences->mods as $name => $info) {
2337 /// We only include the corresponding backuplib.php if it hasn't been included before
2338 /// This will save some load under PHP5. MDL-8700.
2339 /// Once fixed by PHP, we'll delete this hack
2340 if (!in_array($name, $includedfiles)) {
2341 include_once("$CFG->dirroot/mod/$name/backuplib.php");
2342 $includedfiles[] = $name;
2344 //Check if the xxxx_encode_content_links exists
2345 $function_name = $name."_encode_content_links";
2346 if (function_exists($function_name)) {
2347 $result = $function_name($result,$mypreferences);
2351 // For each block, call its encode_content_links method.
2352 // This encodes forexample links to blocks/something/viewphp?id=666
2353 // that are stored in other activities.
2354 static $blockobjects = null;
2355 if (!isset($blockobjects)) {
2356 $blockobjects = array();
2357 if ($blocks = get_records('block', 'visible', 1)) {
2358 foreach ($blocks as $block) {
2359 if ($blockobject = block_instance($block->name)) {
2360 $blockobjects[] = $blockobject;
2366 foreach ($blockobjects as $blockobject) {
2367 $result = $blockobject->encode_content_links($result,$mypreferences);
2370 if ($result != $content) {
2371 debugging('<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />');
2374 return $result;
2377 //This function copies all the needed files under the "user" directory to the "user_files"
2378 //directory under temp/backup
2379 function backup_copy_user_files ($preferences) {
2381 global $CFG;
2383 $status = true;
2385 //First we check that "user_files" exists and create it if necessary
2386 //in temp/backup/$backup_code dir
2387 $status = check_and_create_user_files_dir($preferences->backup_unique_code);
2388 //now get a list of users that we need for this backup.
2389 $backup_users = get_recordset_select("backup_ids",
2390 "backup_code='$preferences->backup_unique_code' AND table_name='user'", "", "id, old_id");
2391 while ($user = rs_fetch_next_record($backup_users)) {
2392 //If this user's directory exists, copy it
2393 $userdir = make_user_directory($user->old_id, true);
2394 if (check_dir_exists($userdir)) {
2395 //first remove dirroot so we can split out the folders.
2396 $parts = explode('/', str_replace($CFG->dataroot.'/user/', '', $userdir));
2397 $status = true;
2398 if (is_array($parts)) {
2399 $group = $parts[0];
2400 $userid = $parts[1];
2402 // Create group dir first
2403 $status = check_dir_exists("$CFG->dataroot/temp/backup/$preferences->backup_unique_code/user_files/". $group, true);
2406 $status = $status && backup_copy_file($userdir,
2407 "$CFG->dataroot/temp/backup/$preferences->backup_unique_code/user_files/$group/$user->old_id");
2409 //Do some output
2410 backup_flush(30);
2412 rs_close($backup_users);
2414 return $status;
2417 //This function copies all the needed files under the "groups" directory to the "group_files"
2418 //directory under temp/backup
2419 function backup_copy_group_files ($preferences) {
2421 global $CFG;
2423 $status = true;
2425 //First we check if "group_files" exists and create it as necessary
2426 //in temp/backup/$backup_code dir
2427 $status = check_and_create_group_files_dir($preferences->backup_unique_code);
2429 //Now iterate over directories under "groups" to check if that user must be
2430 //copied to backup
2432 $rootdir = $CFG->dataroot.'/groups';
2433 //Check if directory exists
2434 if (is_dir($rootdir)) {
2435 $list = list_directories ($rootdir);
2436 if ($list) {
2437 //Iterate
2438 foreach ($list as $dir) {
2439 //Look for dir like group in groups table
2440 $data = get_record ('groups', 'courseid', $preferences->backup_course,
2441 'id',$dir);
2442 //If exists, copy it
2443 if ($data) {
2444 $status = backup_copy_file($rootdir."/".$dir,
2445 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/group_files/".$dir);
2450 return $status;
2453 //This function copies all the course files under the course directory (except the moddata
2454 //directory to the "course_files" directory under temp/backup
2455 function backup_copy_course_files ($preferences) {
2457 global $CFG;
2459 $status = true;
2461 //First we check to "course_files" exists and create it as necessary
2462 //in temp/backup/$backup_code dir
2463 $status = check_and_create_course_files_dir($preferences->backup_unique_code);
2465 //Now iterate over files and directories except $CFG->moddata and backupdata to be
2466 //copied to backup
2468 $rootdir = $CFG->dataroot."/".$preferences->backup_course;
2470 $name_moddata = $CFG->moddata;
2471 $name_backupdata = "backupdata";
2472 //Check if directory exists
2473 if (is_dir($rootdir)) {
2474 $list = list_directories_and_files ($rootdir);
2475 if ($list) {
2476 //Iterate
2477 foreach ($list as $dir) {
2478 if ($dir !== $name_moddata and $dir !== $name_backupdata) {
2479 $status = backup_copy_file($rootdir."/".$dir,
2480 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/course_files/".$dir);
2485 return $status;
2488 * This function copies all the site files under the site directory (except the moddata and backupdata
2489 * directories to the "site_files" directory under temp/backup
2491 function backup_copy_site_files ($preferences) {
2493 global $CFG;
2495 $status = true;
2497 if ($preferences->backup_course == SITEID){
2498 return $status;
2501 //First we check to "site_files" exists and create it as necessary
2502 //in temp/backup/$backup_code dir
2503 $status = $status && check_and_create_site_files_dir($preferences->backup_unique_code);
2505 $rootdir = $CFG->dataroot."/".SITEID;
2509 $files = get_records_select('backup_files',
2510 "backup_code = '$preferences->backup_unique_code' AND file_type = 'site'");
2511 if ($files) {
2512 //Iterate
2513 foreach ($files as $fileobj) {
2514 //check for dir structure and create recursively
2515 $file = $fileobj->path;
2516 $status = $status && check_dir_exists(dirname($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/site_files/".$file), true, true);
2517 $status = $status && backup_copy_file($rootdir."/".$file,
2518 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/site_files/".$file);
2521 return $status;
2523 //This function creates the zip file containing all the backup info
2524 //moodle.xml, moddata, user_files, course_files.
2525 //The zipped file is created in the backup directory and named with
2526 //the "oficial" name of the backup
2527 //It uses "pclzip" if available or system "zip" (unix only)
2528 function backup_zip ($preferences) {
2530 global $CFG;
2532 $status = true;
2534 //Base dir where everything happens
2535 $basedir = cleardoubleslashes($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code);
2536 //Backup zip file name
2537 $name = $preferences->backup_name;
2538 //List of files and directories
2539 $filelist = list_directories_and_files ($basedir);
2541 //Convert them to full paths
2542 $files = array();
2543 foreach ($filelist as $file) {
2544 $files[] = "$basedir/$file";
2547 $status = zip_files($files, "$basedir/$name");
2549 //echo "<br/>Status: ".$status; //Debug
2550 return $status;
2554 //This function copies the final zip to the course dir
2555 function copy_zip_to_course_dir ($preferences) {
2557 global $CFG;
2559 $status = true;
2561 //Define zip location (from)
2562 $from_zip_file = $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/".$preferences->backup_name;
2564 //Initialise $to_zip_file
2565 $to_zip_file="";
2567 //If $preferences->backup_destination isn't empty, then copy to custom directory
2568 if (!empty($preferences->backup_destination)) {
2569 $to_zip_file = $preferences->backup_destination."/".$preferences->backup_name;
2570 } else {
2571 //Define zip destination (course dir)
2572 $to_zip_file = $CFG->dataroot."/".$preferences->backup_course;
2574 //echo "<p>From: ".$from_zip_file."<br />"; //Debug
2576 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2578 //Checks course dir exists
2579 $status = check_dir_exists($to_zip_file,true);
2581 //Define zip destination (backup dir)
2582 $to_zip_file = $to_zip_file."/backupdata";
2584 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2586 //Checks backup dir exists
2587 $status = check_dir_exists($to_zip_file,true);
2589 //Define zip destination (zip file)
2590 $to_zip_file = $to_zip_file."/".$preferences->backup_name;
2593 //echo "<p>To: ".$to_zip_file."<br />"; //Debug
2595 //Copy zip file
2596 if ($status) {
2597 $status = backup_copy_file ($from_zip_file,$to_zip_file);
2600 return $status;
2604 * compatibility function
2605 * with new granular backup
2606 * we need to know
2608 function backup_userdata_selected($preferences,$modname,$modid) {
2609 return ((empty($preferences->mods[$modname]->instances)
2610 && !empty($preferences->mods[$modname]->userinfo))
2611 || (is_array($preferences->mods[$modname]->instances)
2612 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2613 && !empty($preferences->mods[$modname]->instances[$modid]->userinfo)));
2617 function backup_mod_selected($preferences,$modname,$modid) {
2618 return ((empty($preferences->mods[$modname]->instances)
2619 && !empty($preferences->mods[$modname]->backup))
2620 || (is_array($preferences->mods[$modname]->instances)
2621 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2622 && !empty($preferences->mods[$modname]->instances[$modid]->backup)));
2626 * Checks for the required files/functions to backup every mod
2627 * And check if there is data about it
2629 function backup_fetch_prefs_from_request(&$preferences,&$count,$course) {
2630 global $CFG,$SESSION;
2632 // check to see if it's in the session already
2633 if (!empty($SESSION->backupprefs) && array_key_exists($course->id,$SESSION->backupprefs) && !empty($SESSION->backupprefs[$course->id])) {
2634 $sprefs = $SESSION->backupprefs[$course->id];
2635 $preferences = $sprefs;
2636 // refetch backup_name just in case.
2637 $bn = optional_param('backup_name','',PARAM_FILE);
2638 if (!empty($bn)) {
2639 $preferences->backup_name = $bn;
2641 $count = 1;
2642 return true;
2645 if ($allmods = get_records("modules") ) {
2646 foreach ($allmods as $mod) {
2647 $modname = $mod->name;
2648 $modfile = "$CFG->dirroot/mod/$modname/backuplib.php";
2649 $modbackup = $modname."_backup_mods";
2650 $modbackupone = $modname."_backup_one_mod";
2651 $modcheckbackup = $modname."_check_backup_mods";
2652 if (!file_exists($modfile)) {
2653 continue;
2655 include_once($modfile);
2656 if (!function_exists($modbackup) || !function_exists($modcheckbackup)) {
2657 continue;
2659 $var = "exists_".$modname;
2660 $preferences->$var = true;
2661 $count++;
2662 // check that there are instances and we can back them up individually
2663 if (!count_records('course_modules','course',$course->id,'module',$mod->id) || !function_exists($modbackupone)) {
2664 continue;
2666 $var = 'exists_one_'.$modname;
2667 $preferences->$var = true;
2668 $varname = $modname.'_instances';
2669 $preferences->$varname = get_all_instances_in_course($modname, $course, NULL, true);
2670 foreach ($preferences->$varname as $instance) {
2671 $preferences->mods[$modname]->instances[$instance->id]->name = $instance->name;
2672 $var = 'backup_'.$modname.'_instance_'.$instance->id;
2673 $$var = optional_param($var,0);
2674 $preferences->$var = $$var;
2675 $preferences->mods[$modname]->instances[$instance->id]->backup = $$var;
2676 $var = 'backup_user_info_'.$modname.'_instance_'.$instance->id;
2677 $$var = optional_param($var,0);
2678 $preferences->$var = $$var;
2679 $preferences->mods[$modname]->instances[$instance->id]->userinfo = $$var;
2680 $var = 'backup_'.$modname.'_instances';
2681 $preferences->$var = 1; // we need this later to determine what to display in modcheckbackup.
2684 //Check data
2685 //Check module info
2686 $preferences->mods[$modname]->name = $modname;
2688 $var = "backup_".$modname;
2689 $$var = optional_param( $var,0);
2690 $preferences->$var = $$var;
2691 $preferences->mods[$modname]->backup = $$var;
2693 //Check include user info
2694 $var = "backup_user_info_".$modname;
2695 $$var = optional_param( $var,0);
2696 $preferences->$var = $$var;
2697 $preferences->mods[$modname]->userinfo = $$var;
2702 //Check other parameters
2703 $preferences->backup_metacourse = optional_param('backup_metacourse',1,PARAM_INT);
2704 $preferences->backup_users = optional_param('backup_users',1,PARAM_INT);
2705 $preferences->backup_logs = optional_param('backup_logs',0,PARAM_INT);
2706 $preferences->backup_user_files = optional_param('backup_user_files',1,PARAM_INT);
2707 $preferences->backup_course_files = optional_param('backup_course_files',1,PARAM_INT);
2708 $preferences->backup_gradebook_history = optional_param('backup_gradebook_history', 1, PARAM_INT);
2709 $preferences->backup_site_files = optional_param('backup_site_files',1,PARAM_INT);
2710 $preferences->backup_messages = optional_param('backup_messages',1,PARAM_INT);
2711 $preferences->backup_blogs = optional_param('backup_blogs',1,PARAM_INT);
2712 $preferences->backup_course = $course->id;
2713 $preferences->backup_name = required_param('backup_name',PARAM_FILE);
2714 $preferences->backup_unique_code = required_param('backup_unique_code');
2716 $roles = get_records('role', '', '', 'sortorder');
2717 $preferences->backuproleassignments = array();
2718 foreach ($roles as $role) {
2719 if (optional_param('backupassignments_' . $role->shortname, 0, PARAM_INT)) {
2720 $preferences->backuproleassignments[$role->id] = $role;
2724 // put it (back) in the session
2725 $SESSION->backupprefs[$course->id] = $preferences;
2728 /* Finds all related roles used in course, mod and blocks context
2729 * @param object $preferences
2730 * @param object $course
2731 * @return array of role objects
2733 function backup_fetch_roles($preferences) {
2735 global $CFG;
2736 $contexts = array();
2737 $roles = array();
2739 /// adding course context
2740 $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
2741 $contexts[$coursecontext->id] = $coursecontext;
2743 /// adding mod contexts
2744 $mods = $preferences->mods;
2745 foreach ($mods as $modname => $mod) {
2746 $instances = $mod->instances;
2747 foreach ($instances as $id => $instance) {
2748 // if this type of mod is to be backed up
2749 if ($instance->backup) {
2750 $cm = get_coursemodule_from_instance($modname, $id);
2751 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2752 // put context in array keys
2753 $contexts[$context->id] = $context;
2758 // add all roles assigned at user context
2759 if ($preferences->backup_users) {
2760 if ($users = get_records_sql("SELECT u.old_id, u.table_name,u.info
2761 FROM {$CFG->prefix}backup_ids u
2762 WHERE u.backup_code = '$preferences->backup_unique_code' AND
2763 u.table_name = 'user'")) {
2764 foreach ($users as $user) {
2765 $context = get_context_instance(CONTEXT_USER, $user->old_id);
2766 $contexts[$context->id] = $context;
2772 // add all roles assigned at block context
2773 if ($courseblocks = get_records_sql("SELECT *
2774 FROM {$CFG->prefix}block_instance
2775 WHERE pagetype = '".PAGE_COURSE_VIEW."'
2776 AND pageid = {$preferences->backup_course}")) {
2778 foreach ($courseblocks as $courseblock) {
2780 $context = get_context_instance(CONTEXT_BLOCK, $courseblock->id);
2781 $contexts[$context->id] = $context;
2785 // foreach context, call get_roles_on_exact_context insert into array
2786 foreach ($contexts as $context) {
2787 if ($proles = get_roles_on_exact_context($context)) {
2788 foreach ($proles as $prole) {
2789 $roles[$prole->id] = $prole;
2794 return $roles;
2797 /* function to print xml for overrides */
2798 function write_role_overrides_xml($bf, $context, $startlevel) {
2799 fwrite ($bf, start_tag("ROLES_OVERRIDES", $startlevel, true));
2800 if ($roles = get_roles_with_override_on_context($context)) {
2801 foreach ($roles as $role) {
2802 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2803 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2804 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2805 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2806 fwrite ($bf, start_tag("CAPABILITIES", $startlevel+2, true));
2807 if ($capabilities = get_capabilities_from_role_on_context($role, $context)) {
2808 foreach ($capabilities as $capability) {
2809 fwrite ($bf, start_tag("CAPABILITY", $startlevel+3, true));
2810 fwrite ($bf, full_tag("NAME", $startlevel+4, false, $capability->capability));
2811 fwrite ($bf, full_tag("PERMISSION", $startlevel+4, false, $capability->permission));
2812 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $capability->timemodified));
2813 if (!isset($capability->modifierid)) {
2814 $capability->modifierid = 0;
2816 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $capability->modifierid));
2817 fwrite ($bf, end_tag("CAPABILITY", $startlevel+3, true));
2820 fwrite ($bf, end_tag("CAPABILITIES", $startlevel+2, true));
2821 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2824 fwrite ($bf, end_tag("ROLES_OVERRIDES", $startlevel, true));
2827 /* function to print xml for assignment */
2828 function write_role_assignments_xml($bf, $preferences, $context, $startlevel) {
2829 /// write role_assign code here
2830 fwrite ($bf, start_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2832 if ($roles = get_roles_with_assignment_on_context($context)) {
2833 foreach ($roles as $role) {
2834 /// Skip non-selected roles
2835 if (!isset($preferences->backuproleassignments[$role->id])) {
2836 continue;
2838 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2839 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2840 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2841 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2842 fwrite ($bf, start_tag("ASSIGNMENTS", $startlevel+2, true));
2843 if ($assignments = get_users_from_role_on_context($role, $context)) {
2844 foreach ($assignments as $assignment) {
2845 /// Role assignments are only sent to backup if the user is one target user
2846 if (backup_getid($preferences->backup_unique_code, 'user', $assignment->userid)) {
2847 fwrite ($bf, start_tag("ASSIGNMENT", $startlevel+3, true));
2848 fwrite ($bf, full_tag("USERID", $startlevel+4, false, $assignment->userid));
2849 fwrite ($bf, full_tag("HIDDEN", $startlevel+4, false, $assignment->hidden));
2850 fwrite ($bf, full_tag("TIMESTART", $startlevel+4, false, $assignment->timestart));
2851 fwrite ($bf, full_tag("TIMEEND", $startlevel+4, false, $assignment->timeend));
2852 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $assignment->timemodified));
2853 if (!isset($assignment->modifierid)) {
2854 $assignment->modifierid = 0;
2856 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $assignment->modifierid));
2857 fwrite ($bf, full_tag("ENROL", $startlevel+4, false, $assignment->enrol));
2858 fwrite ($bf, full_tag("SORTORDER", $startlevel+4, false, $assignment->sortorder));
2859 fwrite ($bf, end_tag("ASSIGNMENT", $startlevel+3, true));
2863 fwrite ($bf, end_tag("ASSIGNMENTS", $startlevel+2, true));
2864 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2867 fwrite ($bf, end_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2871 function backup_execute(&$preferences, &$errorstr) {
2872 global $CFG;
2873 $status = true;
2875 //Check for temp and backup and backup_unique_code directory
2876 //Create them as needed
2877 if (!defined('BACKUP_SILENTLY')) {
2878 echo "<li>".get_string("creatingtemporarystructures").'</li>';
2881 $status = check_and_create_backup_dir($preferences->backup_unique_code);
2882 //Empty dir
2883 if ($status) {
2884 $status = clear_backup_dir($preferences->backup_unique_code);
2887 //Delete old_entries from backup tables
2888 if (!defined('BACKUP_SILENTLY')) {
2889 echo "<li>".get_string("deletingolddata").'</li>';
2891 $status = backup_delete_old_data();
2892 if (!$status) {
2893 if (!defined('BACKUP_SILENTLY')) {
2894 notify ("An error occurred deleting old backup data");
2896 else {
2897 $errorstr = "An error occurred deleting old backup data";
2898 return false;
2902 //Create the moodle.xml file
2903 if ($status) {
2904 if (!defined('BACKUP_SILENTLY')) {
2905 echo "<li>".get_string("creatingxmlfile");
2906 //Begin a new list to xml contents
2907 echo "<ul>";
2908 echo "<li>".get_string("writingheader").'</li>';
2910 //Obtain the xml file (create and open) and print prolog information
2911 $backup_file = backup_open_xml($preferences->backup_unique_code);
2912 if (!defined('BACKUP_SILENTLY')) {
2913 echo "<li>".get_string("writinggeneralinfo").'</li>';
2915 //Prints general info about backup to file
2916 if ($backup_file) {
2917 if (!$status = backup_general_info($backup_file,$preferences)) {
2918 if (!defined('BACKUP_SILENTLY')) {
2919 notify("An error occurred while backing up general info");
2921 else {
2922 $errorstr = "An error occurred while backing up general info";
2923 return false;
2927 if (!defined('BACKUP_SILENTLY')) {
2928 echo "<li>".get_string("writingcoursedata");
2929 //Start new ul (for course)
2930 echo "<ul>";
2931 echo "<li>".get_string("courseinfo").'</li>';
2933 //Prints course start (tag and general info)
2934 if ($status) {
2935 if (!$status = backup_course_start($backup_file,$preferences)) {
2936 if (!defined('BACKUP_SILENTLY')) {
2937 notify("An error occurred while backing up course start");
2939 else {
2940 $errorstr = "An error occurred while backing up course start";
2941 return false;
2945 //Metacourse information
2946 if ($status && $preferences->backup_metacourse) {
2947 if (!defined('BACKUP_SILENTLY')) {
2948 echo "<li>".get_string("metacourse").'</li>';
2950 if (!$status = backup_course_metacourse($backup_file,$preferences)) {
2951 if (!defined('BACKUP_SILENTLY')) {
2952 notify("An error occurred while backing up metacourse info");
2954 else {
2955 $errorstr = "An error occurred while backing up metacourse info";
2956 return false;
2960 if (!defined('BACKUP_SILENTLY')) {
2961 echo "<li>".get_string("blocks").'</li>';
2963 //Blocks information
2964 if ($status) {
2965 if (!$status = backup_course_blocks($backup_file,$preferences)) {
2966 if (!defined('BACKUP_SILENTLY')) {
2967 notify("An error occurred while backing up course blocks");
2969 else {
2970 $errorstr = "An error occurred while backing up course blocks";
2971 return false;
2975 if (!defined('BACKUP_SILENTLY')) {
2976 echo "<li>".get_string("sections").'</li>';
2978 //Section info
2979 if ($status) {
2980 if (!$status = backup_course_sections($backup_file,$preferences)) {
2981 if (!defined('BACKUP_SILENTLY')) {
2982 notify("An error occurred while backing up course sections");
2984 else {
2985 $errorstr = "An error occurred while backing up course sections";
2986 return false;
2991 //End course contents (close ul)
2992 if (!defined('BACKUP_SILENTLY')) {
2993 echo "</ul></li>";
2996 //User info
2997 if ($status) {
2998 if (!defined('BACKUP_SILENTLY')) {
2999 echo "<li>".get_string("writinguserinfo").'</li>';
3001 if (!$status = backup_user_info($backup_file,$preferences)) {
3002 if (!defined('BACKUP_SILENTLY')) {
3003 notify("An error occurred while backing up user info");
3005 else {
3006 $errorstr = "An error occurred while backing up user info";
3007 return false;
3012 //If we have selected to backup messages and we are
3013 //doing a SITE backup, let's do it
3014 if ($status && $preferences->backup_messages && $preferences->backup_course == SITEID) {
3015 if (!defined('BACKUP_SILENTLY')) {
3016 echo "<li>".get_string("writingmessagesinfo").'</li>';
3018 if (!$status = backup_messages($backup_file,$preferences)) {
3019 if (!defined('BACKUP_SILENTLY')) {
3020 notify("An error occurred while backing up messages");
3022 else {
3023 $errorstr = "An error occurred while backing up messages";
3024 return false;
3029 //If we have selected to backup blogs and we are
3030 //doing a SITE backup, let's do it
3031 if ($status && $preferences->backup_blogs && $preferences->backup_course == SITEID) {
3032 if (!defined('BACKUP_SILENTLY')) {
3033 echo "<li>".get_string("writingblogsinfo").'</li>';
3035 if (!$status = backup_blogs($backup_file,$preferences)) {
3036 if (!defined('BACKUP_SILENTLY')) {
3037 notify("An error occurred while backing up blogs");
3039 else {
3040 $errorstr = "An error occurred while backing up blogs";
3041 return false;
3046 //If we have selected to backup quizzes or other modules that use questions
3047 //we've already added ids of categories and questions to backup to backup_ids table
3048 if ($status) {
3049 if (!defined('BACKUP_SILENTLY')) {
3050 echo "<li>".get_string("writingcategoriesandquestions").'</li>';
3052 require_once($CFG->dirroot.'/question/backuplib.php');
3053 if (!$status = backup_question_categories($backup_file, $preferences)) {
3054 if (!defined('BACKUP_SILENTLY')) {
3055 notify("An error occurred while backing up quiz categories");
3057 else {
3058 $errorstr = "An error occurred while backing up quiz categories";
3059 return false;
3064 //Print logs if selected
3065 if ($status) {
3066 if ($preferences->backup_logs) {
3067 if (!defined('BACKUP_SILENTLY')) {
3068 echo "<li>".get_string("writingloginfo").'</li>';
3070 if (!$status = backup_log_info($backup_file,$preferences)) {
3071 if (!defined('BACKUP_SILENTLY')) {
3072 notify("An error occurred while backing up log info");
3074 else {
3075 $errorstr = "An error occurred while backing up log info";
3076 return false;
3082 //Print scales info
3083 if ($status) {
3084 if (!defined('BACKUP_SILENTLY')) {
3085 echo "<li>".get_string("writingscalesinfo").'</li>';
3087 if (!$status = backup_scales_info($backup_file,$preferences)) {
3088 if (!defined('BACKUP_SILENTLY')) {
3089 notify("An error occurred while backing up scales");
3091 else {
3092 $errorstr = "An error occurred while backing up scales";
3093 return false;
3098 //Print groups info
3099 if ($status) {
3100 if (!defined('BACKUP_SILENTLY')) {
3101 echo "<li>".get_string("writinggroupsinfo").'</li>';
3103 if (!$status = backup_groups_info($backup_file,$preferences)) {
3104 if (!defined('BACKUP_SILENTLY')) {
3105 notify("An error occurred while backing up groups");
3107 else {
3108 $errostr = "An error occurred while backing up groups";
3109 return false;
3114 //Print groupings info
3115 if ($status) {
3116 if (!defined('BACKUP_SILENTLY')) {
3117 echo "<li>".get_string("writinggroupingsinfo").'</li>';
3119 if (!$status = backup_groupings_info($backup_file,$preferences)) {
3120 if (!defined('BACKUP_SILENTLY')) {
3121 notify("An error occurred while backing up groupings");
3123 else {
3124 $errorstr = "An error occurred while backing up groupings";
3125 return false;
3130 //Print groupings_groups info
3131 if ($status) {
3132 if (!defined('BACKUP_SILENTLY')) {
3133 echo "<li>".get_string("writinggroupingsgroupsinfo").'</li>';
3135 if (!$status = backup_groupings_groups_info($backup_file,$preferences)) {
3136 if (!defined('BACKUP_SILENTLY')) {
3137 notify("An error occurred while backing up groupings groups");
3139 else {
3140 $errorstr = "An error occurred while backing up groupings groups";
3141 return false;
3146 //Print events info
3147 if ($status) {
3148 if (!defined('BACKUP_SILENTLY')) {
3149 echo "<li>".get_string("writingeventsinfo").'</li>';
3151 if (!$status = backup_events_info($backup_file,$preferences)) {
3152 if (!defined('BACKUP_SILENTLY')) {
3153 notify("An error occurred while backing up events");
3155 else {
3156 $errorstr = "An error occurred while backing up events";
3157 return false;
3162 //Print gradebook info
3163 if ($status) {
3164 if (!defined('BACKUP_SILENTLY')) {
3165 echo "<li>".get_string("writinggradebookinfo").'</li>';
3167 if (!$status = backup_gradebook_info($backup_file,$preferences)) {
3168 if (!defined('BACKUP_SILENTLY')) {
3169 notify("An error occurred while backing up gradebook");
3171 else {
3172 $errorstr = "An error occurred while backing up gradebook";
3173 return false;
3178 //Module info, this unique function makes all the work!!
3179 //db export and module fileis copy
3180 if ($status) {
3181 $mods_to_backup = false;
3182 //Check if we have any mod to backup
3183 foreach ($preferences->mods as $module) {
3184 if ($module->backup) {
3185 $mods_to_backup = true;
3188 //If we have to backup some module
3189 if ($mods_to_backup) {
3190 if (!defined('BACKUP_SILENTLY')) {
3191 echo "<li>".get_string("writingmoduleinfo");
3193 //Start modules tag
3194 if (!$status = backup_modules_start ($backup_file,$preferences)) {
3195 if (!defined('BACKUP_SILENTLY')) {
3196 notify("An error occurred while backing up module info");
3198 else {
3199 $errorstr = "An error occurred while backing up module info";
3200 return false;
3203 //Open ul for module list
3204 if (!defined('BACKUP_SILENTLY')) {
3205 echo "<ul>";
3207 //Iterate over modules and call backup
3208 foreach ($preferences->mods as $module) {
3209 if ($module->backup and $status) {
3210 if (!defined('BACKUP_SILENTLY')) {
3211 echo "<li>".get_string("modulenameplural",$module->name).'</li>';
3213 if (!$status = backup_module($backup_file,$preferences,$module->name)) {
3214 if (!defined('BACKUP_SILENTLY')) {
3215 notify("An error occurred while backing up '$module->name'");
3217 else {
3218 $errorstr = "An error occurred while backing up '$module->name'";
3219 return false;
3224 //Close ul for module list
3225 if (!defined('BACKUP_SILENTLY')) {
3226 echo "</ul></li>";
3228 //Close modules tag
3229 if (!$status = backup_modules_end ($backup_file,$preferences)) {
3230 if (!defined('BACKUP_SILENTLY')) {
3231 notify("An error occurred while finishing the module backups");
3233 else {
3234 $errorstr = "An error occurred while finishing the module backups";
3235 return false;
3241 //Backup course format data, if any.
3242 if (!defined('BACKUP_SILENTLY')) {
3243 echo '<li>'.get_string("courseformatdata").'</li>';
3245 if($status) {
3246 if (!$status = backup_format_data($backup_file,$preferences)) {
3247 if (!defined('BACKUP_SILENTLY')) {
3248 notify("An error occurred while backing up the course format data");
3250 else {
3251 $errorstr = "An error occurred while backing up the course format data";
3252 return false;
3257 //Prints course end
3258 if ($status) {
3259 if (!$status = backup_course_end($backup_file,$preferences)) {
3260 if (!defined('BACKUP_SILENTLY')) {
3261 notify("An error occurred while closing the course backup");
3263 else {
3264 $errorstr = "An error occurred while closing the course backup";
3265 return false;
3269 //Close the xml file and xml data
3270 if ($backup_file) {
3271 backup_close_xml($backup_file);
3274 //End xml contents (close ul)
3275 if (!defined('BACKUP_SILENTLY')) {
3276 echo "</ul></li>";
3280 //Now, if selected, copy user files
3281 if ($status) {
3282 if ($preferences->backup_user_files) {
3283 if (!defined('BACKUP_SILENTLY')) {
3284 echo "<li>".get_string("copyinguserfiles").'</li>';
3286 if (!$status = backup_copy_user_files ($preferences)) {
3287 if (!defined('BACKUP_SILENTLY')) {
3288 notify("An error occurred while copying user files");
3290 else {
3291 $errorstr = "An error occurred while copying user files";
3292 return false;
3298 //Now, if selected, copy course files
3299 if ($status) {
3300 if ($preferences->backup_course_files) {
3301 if (!defined('BACKUP_SILENTLY')) {
3302 echo "<li>".get_string("copyingcoursefiles").'</li>';
3304 if (!$status = backup_copy_course_files ($preferences)) {
3305 if (!defined('BACKUP_SILENTLY')) {
3306 notify("An error occurred while copying course files");
3308 else {
3309 $errorstr = "An error occurred while copying course files";
3310 return false;
3315 //Now, if selected, copy site files
3316 if ($status) {
3317 if ($preferences->backup_site_files) {
3318 if (!defined('BACKUP_SILENTLY')) {
3319 echo "<li>".get_string("copyingsitefiles").'</li>';
3321 if (!$status = backup_copy_site_files ($preferences)) {
3322 if (!defined('BACKUP_SILENTLY')) {
3323 notify("An error occurred while copying site files");
3325 else {
3326 $errorstr = "An error occurred while copying site files";
3327 return false;
3332 //Now, zip all the backup directory contents
3333 if ($status) {
3334 if (!defined('BACKUP_SILENTLY')) {
3335 echo "<li>".get_string("zippingbackup").'</li>';
3337 if (!$status = backup_zip ($preferences)) {
3338 if (!defined('BACKUP_SILENTLY')) {
3339 notify("An error occurred while zipping the backup");
3341 else {
3342 $errorstr = "An error occurred while zipping the backup";
3343 return false;
3348 //Now, copy the zip file to course directory
3349 if ($status) {
3350 if (!defined('BACKUP_SILENTLY')) {
3351 echo "<li>".get_string("copyingzipfile").'</li>';
3353 if (!$status = copy_zip_to_course_dir ($preferences)) {
3354 if (!defined('BACKUP_SILENTLY')) {
3355 notify("An error occurred while copying the zip file to the course directory");
3357 else {
3358 $errorstr = "An error occurred while copying the zip file to the course directory";
3359 return false;
3364 //Now, clean temporary data (db and filesystem)
3365 if ($status) {
3366 if (!defined('BACKUP_SILENTLY')) {
3367 echo "<li>".get_string("cleaningtempdata").'</li>';
3369 if (!$status = clean_temp_data ($preferences)) {
3370 if (!defined('BACKUP_SILENTLY')) {
3371 notify("An error occurred while cleaning up temporary data");
3373 else {
3374 $errorstr = "An error occurred while cleaning up temporary data";
3375 return false;
3380 return $status;
3384 * This function calculates the "backup" part of the file name
3385 * from lang files. Used both in manual and scheduled backups
3387 * @param object $course course object
3388 * @return string "backup" part of the filename
3390 function backup_get_backup_string($course) {
3392 /// Calculate the backup word
3393 /// Take off some characters in the filename !!
3394 $takeoff = array(" ", ":", "/", "\\", "|");
3395 $backup_word = str_replace($takeoff,"_",moodle_strtolower(get_string("backupfilename")));
3396 /// If non-translated, use "backup"
3397 if (substr($backup_word,0,1) == "[") {
3398 $backup_word= "backup";
3401 return $backup_word;
3405 * This function generates the default zipfile name for a backup
3406 * based on the course shortname
3408 * @param object $course course object
3409 * @return string filename (excluding path information)
3411 function backup_get_zipfile_name($course) {
3413 //Calculate the backup word
3414 $backup_word = backup_get_backup_string($course);
3416 //Calculate the date format string
3417 $backup_date_format = str_replace(" ","_",get_string("backupnameformat"));
3418 //If non-translated, use "%Y%m%d-%H%M"
3419 if (substr($backup_date_format,0,1) == "[") {
3420 $backup_date_format = "%%Y%%m%%d-%%H%%M";
3423 //Calculate the shortname
3424 $backup_shortname = clean_filename($course->shortname);
3425 if (empty($backup_shortname) or $backup_shortname == '_' ) {
3426 $backup_shortname = $course->id;
3429 //Calculate the final backup filename
3430 //The backup word
3431 $backup_name = $backup_word."-";
3432 //The shortname
3433 $backup_name .= moodle_strtolower($backup_shortname)."-";
3434 //The date format
3435 $backup_name .= userdate(time(),$backup_date_format,99,false);
3436 //The extension
3437 $backup_name .= ".zip";
3438 //And finally, clean everything
3439 $backup_name = clean_filename($backup_name);
3441 return $backup_name;
3445 * This function generates the common file substring for a course
3446 * used to keep n copies by the scheduled backup
3448 * @param object $course course object
3449 * @return string common part of filename in backups of this course
3451 function backup_get_keep_name($course) {
3453 //Calculate the backup word
3454 $backup_word = backup_get_backup_string($course);
3456 //Calculate the shortname
3457 $backup_shortname = clean_filename($course->shortname);
3458 if (empty($backup_shortname) or $backup_shortname == '_' ) {
3459 $backup_shortname = $course->id;
3462 $keep_name = $backup_word . "-" . moodle_strtolower($backup_shortname)."-";
3463 $keep_name = clean_filename($keep_name);
3465 return $keep_name;
3468 * This function adds on the standard items to the preferences
3469 * Like moodle version and backup version
3471 * @param object $preferences existing preferences object.
3472 * (passed by reference)
3474 function backup_add_static_preferences(&$preferences) {
3475 global $CFG;
3476 $preferences->moodle_version = $CFG->version;
3477 $preferences->moodle_release = $CFG->release;
3478 $preferences->backup_version = $CFG->backup_version;
3479 $preferences->backup_release = $CFG->backup_release;