Restoring from courses having custom role name doesn't cause duplicate roles. MDL...
[moodle-linuxchix.git] / backup / backuplib.php
blob56d1f2e569433e8a4efe89e8532f4f06abd64024
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 //and put them (their path) in backup_ids
219 //Return an array of info (name,value)
220 function user_files_check_backup($course,$backup_unique_code) {
222 global $CFG;
224 $rootdir = $CFG->dataroot."/users";
225 //Check if directory exists
226 if (is_dir($rootdir)) {
227 //Get directories without descend
228 $userdirs = get_directory_list($rootdir,"",false,true,false);
229 foreach ($userdirs as $dir) {
230 //Extracts user id from file path
231 $tok = strtok($dir,"/");
232 if ($tok) {
233 $userid = $tok;
234 } else {
235 //We were getting $dir='0', so continue (WAS: $tok = "";)
236 continue;
238 //Look it is a backupable user
239 $data = get_record ("backup_ids","backup_code","$backup_unique_code",
240 "table_name","user",
241 "old_id",$userid);
242 if ($data) {
243 //Insert them into backup_files
244 $status = execute_sql("INSERT INTO {$CFG->prefix}backup_files
245 (backup_code, file_type, path, old_id)
246 VALUES
247 ('$backup_unique_code','user','".addslashes($dir)."','$userid')",false);
249 //Do some output
250 backup_flush(30);
254 //Now execute the select
255 $ids = get_records_sql("SELECT DISTINCT b.path, b.old_id
256 FROM {$CFG->prefix}backup_files b
257 WHERE backup_code = '$backup_unique_code' AND
258 file_type = 'user'");
259 //Gets the user data
260 $info[0][0] = get_string("files");
261 if ($ids) {
262 $info[0][1] = count($ids);
263 } else {
264 $info[0][1] = 0;
267 return $info;
271 * Calculate the number of course files to backup
272 * under $CFG->dataroot/$course, except $CFG->moddata, and backupdata
273 * and put them (their path) in backup_ids
274 * Return an array of info (name,value)
276 function course_files_check_backup($course, $backup_unique_code) {
278 global $CFG;
280 $rootdir = $CFG->dataroot."/$course";
281 //Check if directory exists
282 if (is_dir($rootdir)) {
283 //Get files and directories without descend
284 $coursedirs = get_directory_list($rootdir,$CFG->moddata,false,true,true);
285 $backupdata_dir = "backupdata";
286 foreach ($coursedirs as $dir) {
287 //Check it isn't backupdata_dir
288 if (strpos($dir,$backupdata_dir)!==0) {
289 //Insert them into backup_files
290 $status = execute_sql("INSERT INTO {$CFG->prefix}backup_files
291 (backup_code, file_type, path)
292 VALUES
293 ('$backup_unique_code','course','".addslashes($dir)."')",false);
295 //Do some output
296 backup_flush(30);
300 //Now execute the select
301 $ids = get_records_sql("SELECT DISTINCT b.path, b.old_id
302 FROM {$CFG->prefix}backup_files b
303 WHERE backup_code = '$backup_unique_code' AND
304 file_type = 'course'");
305 //Gets the user data
306 $info = array();
307 $info[0] = array();
308 $info[0][0] = get_string("files");
309 if ($ids) {
310 $info[0][1] = count($ids);
311 } else {
312 $info[0][1] = 0;
315 return $info;
319 * Calculate the number of site files to backup
320 * under $CFG->dataroot/SITEID
321 * Their path is already in backup_ids, put there by modules check_backup functions.
322 * Modules only put in paths of files that are used.
324 * Return an array of info (name,value)
326 function site_files_check_backup($course, $backup_unique_code) {
327 global $CFG;
329 //execute the select, records have been inserted by modules during their ****_check_backup_mods function.
330 $ids = get_records_sql("SELECT DISTINCT b.path
331 FROM {$CFG->prefix}backup_files b
332 WHERE backup_code = '$backup_unique_code' AND
333 file_type = 'site'");
334 //Gets the user data
335 $info = array();
336 $info[0] = array();
337 $info[0][0] = get_string('files');
338 if ($ids) {
339 $info[0][1] = count($ids);
340 } else {
341 $info[0][1] = 0;
344 return $info;
347 //Function to check and create the needed moddata dir to
348 //save all the mod backup files. We always name it moddata
349 //to be able to restore it, but in restore we check for
350 //$CFG->moddata !!
351 function check_and_create_moddata_dir($backup_unique_code) {
353 global $CFG;
355 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/moddata",true);
357 return $status;
360 //Function to check and create the "user_files" dir to
361 //save all the user files we need from "users" dir
362 function check_and_create_user_files_dir($backup_unique_code) {
364 global $CFG;
366 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/user_files",true);
368 return $status;
371 //Function to check and create the "group_files" dir to
372 //save all the user files we need from "groups" dir
373 function check_and_create_group_files_dir($backup_unique_code) {
375 global $CFG;
377 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/group_files",true);
379 return $status;
382 //Function to check and create the "course_files" dir to
383 //save all the course files we need from "CFG->datadir/course" dir
384 function check_and_create_course_files_dir($backup_unique_code) {
386 global $CFG;
388 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/course_files",true);
390 return $status;
393 //Function to check and create the "site_files" dir to
394 //save all the course files we need from "CFG->datadir/SITEID" dir
395 function check_and_create_site_files_dir($backup_unique_code) {
397 global $CFG;
399 $status = check_dir_exists($CFG->dataroot."/temp/backup/".$backup_unique_code."/site_files",true);
401 return $status;
404 //Function to create, open and write header of the xml file
405 function backup_open_xml($backup_unique_code) {
407 global $CFG;
409 $status = true;
411 //Open for writing
413 $file = $CFG->dataroot."/temp/backup/".$backup_unique_code."/moodle.xml";
414 $backup_file = fopen($file,"w");
415 //Writes the header
416 $status = fwrite ($backup_file,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
417 if ($status) {
418 $status = fwrite ($backup_file,start_tag("MOODLE_BACKUP",0,true));
420 if ($status) {
421 return $backup_file;
422 } else {
423 return false;
427 //Close the file
428 function backup_close_xml($backup_file) {
429 $status = fwrite ($backup_file,end_tag("MOODLE_BACKUP",0,true));
430 return fclose($backup_file);
433 //Return the xml start tag
434 function start_tag($tag,$level=0,$endline=false,$attributes=null) {
435 if ($endline) {
436 $endchar = "\n";
437 } else {
438 $endchar = "";
440 $attrstring = '';
441 if (!empty($attributes) && is_array($attributes)) {
442 foreach ($attributes as $key => $value) {
443 $attrstring .= " ".xml_tag_safe_content($key)."=\"".
444 xml_tag_safe_content($value)."\"";
447 return str_repeat(" ",$level*2)."<".strtoupper($tag).$attrstring.">".$endchar;
450 //Return the xml end tag
451 function end_tag($tag,$level=0,$endline=true) {
452 if ($endline) {
453 $endchar = "\n";
454 } else {
455 $endchar = "";
457 return str_repeat(" ",$level*2)."</".strtoupper($tag).">".$endchar;
460 //Return the start tag, the contents and the end tag
461 function full_tag($tag,$level=0,$endline=true,$content,$attributes=null) {
463 global $CFG;
464 //Here we encode absolute links
465 // MDL-10770
466 if (is_null($content)) {
467 $content = '$@NULL@$';
468 } else {
469 $content = backup_encode_absolute_links($content);
471 $st = start_tag($tag,$level,$endline,$attributes);
473 $co = xml_tag_safe_content($content);
475 $et = end_tag($tag,0,true);
477 return $st.$co.$et;
481 function xml_tag_safe_content($content) {
482 global $CFG;
483 //If enabled, we strip all the control chars (\x0-\x1f) from the text but tabs (\x9),
484 //newlines (\xa) and returns (\xd). The delete control char (\x7f) is also included.
485 //because they are forbiden in XML 1.0 specs. The expression below seems to be
486 //UTF-8 safe too because it simply ignores the rest of characters.
487 $content = preg_replace("/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is","",$content);
488 $content = preg_replace("/\r\n|\r/", "\n", htmlspecialchars($content));
489 return $content;
492 //Prints General info about the course
493 //name, moodle_version (internal and release), backup_version, date, info in file...
494 function backup_general_info ($bf,$preferences) {
496 global $CFG;
498 fwrite ($bf,start_tag("INFO",1,true));
500 //The name of the backup
501 fwrite ($bf,full_tag("NAME",2,false,$preferences->backup_name));
502 //The moodle_version
503 fwrite ($bf,full_tag("MOODLE_VERSION",2,false,$preferences->moodle_version));
504 fwrite ($bf,full_tag("MOODLE_RELEASE",2,false,$preferences->moodle_release));
505 //The backup_version
506 fwrite ($bf,full_tag("BACKUP_VERSION",2,false,$preferences->backup_version));
507 fwrite ($bf,full_tag("BACKUP_RELEASE",2,false,$preferences->backup_release));
508 //The date
509 fwrite ($bf,full_tag("DATE",2,false,$preferences->backup_unique_code));
510 //The original site wwwroot
511 fwrite ($bf,full_tag("ORIGINAL_WWWROOT",2,false,$CFG->wwwroot));
512 //The zip method used
513 if (!empty($CFG->zip)) {
514 $zipmethod = 'external';
515 } else {
516 $zipmethod = 'internal';
518 //Indicate if it includes external MNET users
519 $sql = "SELECT b.old_id
520 FROM {$CFG->prefix}backup_ids b
521 JOIN {$CFG->prefix}user u ON b.old_id=u.id
522 WHERE b.backup_code = '$preferences->backup_unique_code'
523 AND b.table_name = 'user' AND u.mnethostid != '{$CFG->mnet_localhost_id}'";
524 if (record_exists_sql($sql)) {
525 fwrite ($bf,full_tag("MNET_REMOTEUSERS",2,false,'true'));
527 fwrite ($bf,full_tag("ZIP_METHOD",2,false,$zipmethod));
528 //Te includes tag
529 fwrite ($bf,start_tag("DETAILS",2,true));
530 //Now, go to mod element of preferences to print its status
531 foreach ($preferences->mods as $element) {
532 //Calculate info
533 $included = "false";
534 $userinfo = "false";
535 if ($element->backup) {
536 $included = "true";
537 if ($element->userinfo) {
538 $userinfo = "true";
541 //Prints the mod start
542 fwrite ($bf,start_tag("MOD",3,true));
543 fwrite ($bf,full_tag("NAME",4,false,$element->name));
544 fwrite ($bf,full_tag("INCLUDED",4,false,$included));
545 fwrite ($bf,full_tag("USERINFO",4,false,$userinfo));
547 if (isset($preferences->mods[$element->name]->instances)
548 && is_array($preferences->mods[$element->name]->instances)
549 && count($preferences->mods[$element->name]->instances)) {
550 fwrite ($bf, start_tag("INSTANCES",4,true));
551 foreach ($preferences->mods[$element->name]->instances as $id => $object) {
552 if (!empty($object->backup)) {
553 //Calculate info
554 $included = "false";
555 $userinfo = "false";
556 if ($object->backup) {
557 $included = "true";
558 if ($object->userinfo) {
559 $userinfo = "true";
562 fwrite ($bf, start_tag("INSTANCE",5,true));
563 fwrite ($bf, full_tag("ID",5,false,$id));
564 fwrite ($bf, full_tag("NAME",5,false,$object->name));
565 fwrite ($bf, full_tag("INCLUDED",5,false,$included)) ;
566 fwrite ($bf, full_tag("USERINFO",5,false,$userinfo));
567 fwrite ($bf, end_tag("INSTANCE",5,true));
570 fwrite ($bf, end_tag("INSTANCES",4,true));
574 //Print the end
575 fwrite ($bf,end_tag("MOD",3,true));
577 //The metacourse in backup
578 if ($preferences->backup_metacourse == 1) {
579 fwrite ($bf,full_tag("METACOURSE",3,false,"true"));
580 } else {
581 fwrite ($bf,full_tag("METACOURSE",3,false,"false"));
583 //The user in backup
584 if ($preferences->backup_users == 1) {
585 fwrite ($bf,full_tag("USERS",3,false,"course"));
586 } else if ($preferences->backup_users == 0) {
587 fwrite ($bf,full_tag("USERS",3,false,"all"));
588 } else {
589 fwrite ($bf,full_tag("USERS",3,false,"none"));
591 //The logs in backup
592 if ($preferences->backup_logs == 1) {
593 fwrite ($bf,full_tag("LOGS",3,false,"true"));
594 } else {
595 fwrite ($bf,full_tag("LOGS",3,false,"false"));
597 //The user files
598 if ($preferences->backup_user_files == 1) {
599 fwrite ($bf,full_tag("USERFILES",3,false,"true"));
600 } else {
601 fwrite ($bf,full_tag("USERFILES",3,false,"false"));
603 //The course files
604 if ($preferences->backup_course_files == 1) {
605 fwrite ($bf,full_tag("COURSEFILES",3,false,"true"));
606 } else {
607 fwrite ($bf,full_tag("COURSEFILES",3,false,"false"));
609 //The site files
610 if ($preferences->backup_site_files == 1) {
611 fwrite ($bf,full_tag("SITEFILES",3,false,"true"));
612 } else {
613 fwrite ($bf,full_tag("SITEFILES",3,false,"false"));
615 //The gradebook histories
616 if ($preferences->backup_gradebook_history == 1) {
617 fwrite ($bf,full_tag("GRADEBOOKHISTORIES",3,false,"true"));
618 } else {
619 fwrite ($bf,full_tag("GRADEBOOKHISTORIES",3,false,"false"));
621 //The messages in backup
622 if ($preferences->backup_messages == 1 && $preferences->backup_course == SITEID) {
623 fwrite ($bf,full_tag("MESSAGES",3,false,"true"));
624 } else {
625 fwrite ($bf,full_tag("MESSAGES",3,false,"false"));
627 //The blogs in backup
628 if ($preferences->backup_blogs == 1 && $preferences->backup_course == SITEID) {
629 fwrite ($bf,full_tag("BLOGS",3,false,"true"));
630 } else {
631 fwrite ($bf,full_tag("BLOGS",3,false,"false"));
633 //The mode of writing the block data
634 fwrite ($bf,full_tag('BLOCKFORMAT',3,false,'instances'));
635 fwrite ($bf,end_tag("DETAILS",2,true));
637 $status = fwrite ($bf,end_tag("INFO",1,true));
639 ///Roles stuff goes in here
641 fwrite ($bf, start_tag('ROLES', 1, true));
642 $roles = backup_fetch_roles($preferences);
644 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
646 foreach ($roles as $role) {
647 fwrite ($bf,start_tag('ROLE',2,true));
648 fwrite ($bf,full_tag('ID', 3, false, $role->id));
649 fwrite ($bf,full_tag('NAME',3,false,$role->name));
650 fwrite ($bf,full_tag('SHORTNAME',3,false,$role->shortname));
651 // find and write all default capabilities
652 fwrite ($bf,start_tag('CAPABILITIES',3,true));
653 // pull out all default (site context) capabilities
654 if ($capabilities = role_context_capabilities($role->id, $sitecontext)) {
655 foreach ($capabilities as $capability=>$value) {
656 fwrite ($bf,start_tag('CAPABILITY',4,true));
657 fwrite ($bf,full_tag('NAME', 5, false, $capability));
658 fwrite ($bf,full_tag('PERMISSION', 5, false, $value));
659 // use this to pull out the other info (timemodified and modifierid)
660 $cap = get_record_sql("SELECT *
661 FROM {$CFG->prefix}role_capabilities
662 WHERE capability = '$capability'
663 AND contextid = $sitecontext->id
664 AND roleid = $role->id");
665 fwrite ($bf, full_tag("TIMEMODIFIED", 5, false, $cap->timemodified));
666 fwrite ($bf, full_tag("MODIFIERID", 5, false, $cap->modifierid));
667 fwrite ($bf,end_tag('CAPABILITY',4,true));
670 fwrite ($bf,end_tag('CAPABILITIES',3,true));
671 fwrite ($bf,end_tag('ROLE',2,true));
673 fwrite ($bf,end_tag('ROLES', 1, true));
674 return $status;
677 //Prints course's general info (table course)
678 function backup_course_start ($bf,$preferences) {
680 global $CFG;
682 $status = true;
684 //Course open tag
685 fwrite ($bf,start_tag("COURSE",1,true));
686 //Header open tag
687 fwrite ($bf,start_tag("HEADER",2,true));
689 //Get info from course
690 $course = get_record("course","id",$preferences->backup_course);
691 $context = get_context_instance(CONTEXT_COURSE, $course->id);
692 if ($course) {
693 //Prints course info
694 fwrite ($bf,full_tag("ID",3,false,$course->id));
695 //Obtain the category
696 $category = get_record("course_categories","id","$course->category");
697 if ($category) {
698 //Prints category info
699 fwrite ($bf,start_tag("CATEGORY",3,true));
700 fwrite ($bf,full_tag("ID",4,false,$course->category));
701 fwrite ($bf,full_tag("NAME",4,false,$category->name));
702 fwrite ($bf,end_tag("CATEGORY",3,true));
704 //Continues with the course
705 fwrite ($bf,full_tag("PASSWORD",3,false,$course->password));
706 fwrite ($bf,full_tag("FULLNAME",3,false,$course->fullname));
707 fwrite ($bf,full_tag("SHORTNAME",3,false,$course->shortname));
708 fwrite ($bf,full_tag("IDNUMBER",3,false,$course->idnumber));
709 fwrite ($bf,full_tag("SUMMARY",3,false,$course->summary));
710 fwrite ($bf,full_tag("FORMAT",3,false,$course->format));
711 fwrite ($bf,full_tag("SHOWGRADES",3,false,$course->showgrades));
712 fwrite ($bf,full_tag("NEWSITEMS",3,false,$course->newsitems));
713 fwrite ($bf,full_tag("TEACHER",3,false,$course->teacher));
714 fwrite ($bf,full_tag("TEACHERS",3,false,$course->teachers));
715 fwrite ($bf,full_tag("STUDENT",3,false,$course->student));
716 fwrite ($bf,full_tag("STUDENTS",3,false,$course->students));
717 fwrite ($bf,full_tag("GUEST",3,false,$course->guest));
718 fwrite ($bf,full_tag("STARTDATE",3,false,$course->startdate));
719 fwrite ($bf,full_tag("NUMSECTIONS",3,false,$course->numsections));
720 //fwrite ($bf,full_tag("SHOWRECENT",3,false,$course->showrecent)); INFO: This is out in 1.3
721 fwrite ($bf,full_tag("MAXBYTES",3,false,$course->maxbytes));
722 fwrite ($bf,full_tag("SHOWREPORTS",3,false,$course->showreports));
723 fwrite ($bf,full_tag("GROUPMODE",3,false,$course->groupmode));
724 fwrite ($bf,full_tag("GROUPMODEFORCE",3,false,$course->groupmodeforce));
725 fwrite ($bf,full_tag("DEFAULTGROUPINGID",3,false,$course->defaultgroupingid));
726 fwrite ($bf,full_tag("LANG",3,false,$course->lang));
727 fwrite ($bf,full_tag("THEME",3,false,$course->theme));
728 fwrite ($bf,full_tag("COST",3,false,$course->cost));
729 fwrite ($bf,full_tag("CURRENCY",3,false,$course->currency));
730 fwrite ($bf,full_tag("MARKER",3,false,$course->marker));
731 fwrite ($bf,full_tag("VISIBLE",3,false,$course->visible));
732 fwrite ($bf,full_tag("HIDDENSECTIONS",3,false,$course->hiddensections));
733 fwrite ($bf,full_tag("TIMECREATED",3,false,$course->timecreated));
734 fwrite ($bf,full_tag("TIMEMODIFIED",3,false,$course->timemodified));
735 //If not selected, force metacourse to 0
736 if (!$preferences->backup_metacourse) {
737 $status = fwrite ($bf,full_tag("METACOURSE",3,false,'0'));
738 //else, export the field as is in DB
739 } else {
740 $status = fwrite ($bf,full_tag("METACOURSE",3,false,$course->metacourse));
742 fwrite ($bf,full_tag("EXPIRENOTIFY",3,false,$course->expirynotify));
743 fwrite ($bf,full_tag("NOTIFYSTUDENTS",3,false,$course->notifystudents));
744 fwrite ($bf,full_tag("EXPIRYTHRESHOLD",3,false,$course->expirythreshold));
745 fwrite ($bf,full_tag("ENROLLABLE",3,false,$course->enrollable));
746 fwrite ($bf,full_tag("ENROLSTARTDATE",3,false,$course->enrolstartdate));
747 fwrite ($bf,full_tag("ENROLENDDATE",3,false,$course->enrolenddate));
748 fwrite ($bf,full_tag("ENROLPERIOD",3,false,$course->enrolperiod));
750 /// write local course overrides here?
751 write_role_overrides_xml($bf, $context, 3);
752 /// write role_assign code here
753 write_role_assignments_xml($bf, $preferences, $context, 3);
754 //Print header end
755 fwrite ($bf,end_tag("HEADER",2,true));
756 } else {
757 $status = false;
760 return $status;
763 //Prints course's end tag
764 function backup_course_end ($bf,$preferences) {
766 //Course end tag
767 $status = fwrite ($bf,end_tag("COURSE",1,true));
769 return $status;
773 //Prints course's metacourse info (table course_meta)
774 function backup_course_metacourse ($bf,$preferences) {
776 global $CFG;
778 $status = true;
780 //Get info from meta
781 $parents = get_records_sql ("SELECT m.*, c.idnumber, c.shortname
782 FROM {$CFG->prefix}course_meta m,
783 {$CFG->prefix}course c
784 WHERE m.child_course = '$preferences->backup_course' AND
785 m.parent_course = c.id");
786 $childs = get_records_sql ("SELECT m.*, c.idnumber, c.shortname
787 FROM {$CFG->prefix}course_meta m,
788 {$CFG->prefix}course c
789 WHERE m.parent_course = '$preferences->backup_course' AND
790 m.child_course = c.id");
792 if ($parents || $childs) {
793 //metacourse open tag
794 fwrite ($bf,start_tag("METACOURSE",2,true));
795 if ($parents) {
796 fwrite($bf, start_tag("PARENTS",3,true));
797 //Iterate over every parent
798 foreach ($parents as $parent) {
799 //Begin parent
800 fwrite ($bf,start_tag("PARENT",4,true));
801 fwrite ($bf,full_tag("ID",5,false,$parent->parent_course));
802 fwrite ($bf,full_tag("IDNUMBER",5,false,$parent->idnumber));
803 fwrite ($bf,full_tag("SHORTNAME",5,false,$parent->shortname));
804 //End parent
805 fwrite ($bf,end_tag("PARENT",4,true));
807 fwrite ($bf,end_tag("PARENTS",3,true));
809 if ($childs) {
810 fwrite($bf, start_tag("CHILDS",3,true));
811 //Iterate over every child
812 foreach ($childs as $child) {
813 //Begin parent
814 fwrite ($bf,start_tag("CHILD",4,true));
815 fwrite ($bf,full_tag("ID",5,false,$child->child_course));
816 fwrite ($bf,full_tag("IDNUMBER",5,false,$child->idnumber));
817 fwrite ($bf,full_tag("SHORTNAME",5,false,$child->shortname));
818 //End parent
819 fwrite ($bf,end_tag("CHILD",4,true));
821 fwrite ($bf,end_tag("CHILDS",3,true));
823 //metacourse close tag
824 $status = fwrite ($bf,end_tag("METACOURSE",3,true));
827 return $status;
831 //Prints course's messages info (tables message, message_read and message_contacts)
832 function backup_messages ($bf,$preferences) {
834 global $CFG;
836 $status = true;
838 /// Check we have something to backup
839 $unreads = count_records ('message');
840 $reads = count_records ('message_read');
841 $contacts= count_records ('message_contacts');
843 if ($unreads || $reads || $contacts) {
844 $counter = 0;
845 /// message open tag
846 fwrite ($bf,start_tag("MESSAGES",2,true));
848 if ($unreads) {
849 $rs_unreads = get_recordset('message');
850 /// Iterate over every unread
851 while ($unread = rs_fetch_next_record($rs_unreads)) {
852 /// start message
853 fwrite($bf, start_tag("MESSAGE",3,true));
854 fwrite ($bf,full_tag("ID",4,false,$unread->id));
855 fwrite ($bf,full_tag("STATUS",4,false,"UNREAD"));
856 fwrite ($bf,full_tag("USERIDFROM",4,false,$unread->useridfrom));
857 fwrite ($bf,full_tag("USERIDTO",4,false,$unread->useridto));
858 fwrite ($bf,full_tag("MESSAGE",4,false,$unread->message));
859 fwrite ($bf,full_tag("FORMAT",4,false,$unread->format));
860 fwrite ($bf,full_tag("TIMECREATED",4,false,$unread->timecreated));
861 fwrite ($bf,full_tag("MESSAGETYPE",4,false,$unread->messagetype));
862 /// end message
863 fwrite ($bf,end_tag("MESSAGE",3,true));
865 /// Do some output
866 $counter++;
867 if ($counter % 20 == 0) {
868 echo ".";
869 if ($counter % 400 == 0) {
870 echo "<br />";
872 backup_flush(300);
875 rs_close($rs_unreads);
878 if ($reads) {
879 $rs_reads = get_recordset('message_read');
880 /// Iterate over every unread
881 while ($read = rs_fetch_next_record($rs_reads)) {
882 /// start message
883 fwrite($bf, start_tag("MESSAGE",3,true));
884 fwrite ($bf,full_tag("ID",4,false,$read->id));
885 fwrite ($bf,full_tag("STATUS",4,false,"READ"));
886 fwrite ($bf,full_tag("USERIDFROM",4,false,$read->useridfrom));
887 fwrite ($bf,full_tag("USERIDTO",4,false,$read->useridto));
888 fwrite ($bf,full_tag("MESSAGE",4,false,$read->message));
889 fwrite ($bf,full_tag("FORMAT",4,false,$read->format));
890 fwrite ($bf,full_tag("TIMECREATED",4,false,$read->timecreated));
891 fwrite ($bf,full_tag("MESSAGETYPE",4,false,$read->messagetype));
892 fwrite ($bf,full_tag("TIMEREAD",4,false,$read->timeread));
893 fwrite ($bf,full_tag("MAILED",4,false,$read->mailed));
894 /// end message
895 fwrite ($bf,end_tag("MESSAGE",3,true));
897 /// Do some output
898 $counter++;
899 if ($counter % 20 == 0) {
900 echo ".";
901 if ($counter % 400 == 0) {
902 echo "<br />";
904 backup_flush(300);
907 rs_close($rs_reads);
910 if ($contacts) {
911 fwrite($bf, start_tag("CONTACTS",3,true));
912 $rs_contacts = get_recordset('message_contacts');
913 /// Iterate over every contact
914 while ($contact = rs_fetch_next_record($rs_contacts)) {
915 /// start contact
916 fwrite($bf, start_tag("CONTACT",4,true));
917 fwrite ($bf,full_tag("ID",5,false,$contact->id));
918 fwrite ($bf,full_tag("USERID",5,false,$contact->userid));
919 fwrite ($bf,full_tag("CONTACTID",5,false,$contact->contactid));
920 fwrite ($bf,full_tag("BLOCKED",5,false,$contact->blocked));
921 /// end contact
922 fwrite ($bf,end_tag("CONTACT",4,true));
924 /// Do some output
925 $counter++;
926 if ($counter % 20 == 0) {
927 echo ".";
928 if ($counter % 400 == 0) {
929 echo "<br />";
931 backup_flush(300);
934 rs_close($rs_contacts);
935 fwrite($bf, end_tag("CONTACTS",3,true));
938 /// messages close tag
939 $status = fwrite ($bf,end_tag("MESSAGES",2,true));
942 return $status;
946 //Print blogs info (post table, module=blog, course=0)
947 function backup_blogs($bf, $preferences) {
949 global $CFG;
951 $status = true;
953 /// Check we have something to backup
954 $siteblogs = count_records('post', 'module', 'blog', 'courseid', 0);
956 if ($siteblogs) {
957 $counter = 0;
958 /// blogs open tag
959 fwrite ($bf, start_tag("BLOGS",2,true));
961 if ($siteblogs) {
962 $rs_blogs = get_recordset_sql("SELECT * from {$CFG->prefix}post
963 WHERE module = 'blog'
964 AND courseid = 0");
965 /// Iterate over every blog
966 while ($blog = rs_fetch_next_record($rs_blogs)) {
967 /// start blog
968 fwrite($bf, start_tag("BLOG",3,true));
969 /// blog body
970 fwrite ($bf,full_tag("ID",4,false,$blog->id));
971 fwrite ($bf,full_tag("MODULE",4,false,$blog->module));
972 fwrite ($bf,full_tag("USERID",4,false,$blog->userid));
973 fwrite ($bf,full_tag("COURSEID",4,false,$blog->courseid));
974 fwrite ($bf,full_tag("GROUPID",4,false,$blog->groupid));
975 fwrite ($bf,full_tag("MODULEID",4,false,$blog->moduleid));
976 fwrite ($bf,full_tag("COURSEMODULEID",4,false,$blog->coursemoduleid));
977 fwrite ($bf,full_tag("SUBJECT",4,false,$blog->subject));
978 fwrite ($bf,full_tag("SUMMARY",4,false,$blog->summary));
979 fwrite ($bf,full_tag("CONTENT",4,false,$blog->content));
980 fwrite ($bf,full_tag("UNIQUEHASH",4,false,$blog->uniquehash));
981 fwrite ($bf,full_tag("RATING",4,false,$blog->rating));
982 fwrite ($bf,full_tag("FORMAT",4,false,$blog->format));
983 fwrite ($bf,full_tag("ATTACHMENT",4,false,$blog->attachment));
984 fwrite ($bf,full_tag("PUBLISHSTATE",4,false,$blog->publishstate));
985 fwrite ($bf,full_tag("LASTMODIFIED",4,false,$blog->lastmodified));
986 fwrite ($bf,full_tag("CREATED",4,false,$blog->created));
987 fwrite ($bf,full_tag("USERMODIFIED",4,false,$blog->usermodified));
989 /// Blog tags
990 /// Check if we have blog tags to backup
991 if (!empty($CFG->usetags)) {
992 if ($tags = tag_get_tags('post', $blog->id)) { //This return them ordered by default
993 /// Start BLOG_TAGS tag
994 fwrite ($bf,start_tag("BLOG_TAGS",4,true));
995 /// Write blog tags fields
996 foreach ($tags as $tag) {
997 fwrite ($bf,start_tag("BLOG_TAG",5,true));
998 fwrite ($bf,full_tag("NAME",6,false,$tag->name));
999 fwrite ($bf,full_tag("RAWNAME",6,false,$tag->rawname));
1000 fwrite ($bf,end_tag("BLOG_TAG",5,true));
1002 /// End BLOG_TAGS tag
1003 fwrite ($bf,end_tag("BLOG_TAGS",4,true));
1007 /// Blog comments
1008 /// TODO: Blog comments go here (2.0)
1010 /// end blog
1011 fwrite($bf, end_tag("BLOG",3,true));
1013 /// Do some output
1014 $counter++;
1015 if ($counter % 20 == 0) {
1016 echo ".";
1017 if ($counter % 400 == 0) {
1018 echo "<br />";
1020 backup_flush(300);
1023 rs_close($rs_blogs);
1025 /// blogs close tag
1026 $status = fwrite($bf, end_tag("BLOGS",2,true));
1029 return $status;
1032 //Prints course's blocks info (table block_instance)
1033 function backup_course_blocks ($bf,$preferences) {
1035 global $CFG;
1037 $status = true;
1039 // Read all of the block table
1040 $blocks = blocks_get_record();
1042 $pages = array();
1043 $pages[] = page_create_object(PAGE_COURSE_VIEW, $preferences->backup_course);
1045 if (!empty($CFG->showblocksonmodpages)) {
1046 // get course structure
1047 $course = get_record('course', 'id', $preferences->backup_course);
1048 $modinfo =& get_fast_modinfo($course);
1050 foreach($preferences->mods as $module) {
1051 if (!$module->backup) {
1052 continue;
1055 if (empty($modinfo->instances[$module->name])) {
1056 continue;
1059 $pagetypes = page_import_types('mod/'.$module->name.'/');
1060 if (empty($pagetypes)) {
1061 continue;
1064 foreach($pagetypes as $pagetype) {
1065 foreach($modinfo->instances[$module->name] as $cm) {
1066 if (!empty($module->instances[$cm->instance]->backup)) {
1067 $pages[] = page_create_object($pagetype, $cm->instance);
1074 //Blocks open tag
1075 fwrite ($bf,start_tag('BLOCKS',2,true));
1077 foreach($pages as $page) {
1078 if ($instances = blocks_get_by_page($page)) {
1079 //Iterate over every block
1080 foreach ($instances as $position) {
1081 foreach ($position as $instance) {
1083 //If we somehow have a block with an invalid id, skip it
1084 if(empty($blocks[$instance->blockid]->name)) {
1085 continue;
1087 $blockname = $blocks[$instance->blockid]->name;
1089 if (!$blockobj = block_instance($blockname, $instance)) {
1090 // Invalid block
1091 continue;
1094 // encode absolute links in block config
1095 $instance->configdata = $blockobj->get_backup_encoded_config();
1097 //Begin Block
1098 fwrite ($bf,start_tag('BLOCK',3,true));
1099 fwrite ($bf,full_tag('ID', 4, false,$instance->id));
1100 fwrite ($bf,full_tag('NAME',4,false,$blockname));
1101 fwrite ($bf,full_tag('PAGEID',4,false,$instance->pageid));
1102 fwrite ($bf,full_tag('PAGETYPE',4,false,$instance->pagetype));
1103 fwrite ($bf,full_tag('POSITION',4,false,$instance->position));
1104 fwrite ($bf,full_tag('WEIGHT',4,false,$instance->weight));
1105 fwrite ($bf,full_tag('VISIBLE',4,false,$instance->visible));
1106 fwrite ($bf,full_tag('CONFIGDATA',4,false,$instance->configdata));
1107 // Write instance data if needed
1108 if ($blockobj->backuprestore_instancedata_used()) {
1109 fwrite ($bf,start_tag('INSTANCEDATA',4,true));
1110 $status = $blockobj->instance_backup($bf, $preferences);
1111 fwrite ($bf,end_tag('INSTANCEDATA',4,true));
1113 $context = get_context_instance(CONTEXT_BLOCK, $instance->id);
1114 write_role_overrides_xml($bf, $context, 4);
1115 /// write role_assign code here
1116 write_role_assignments_xml($bf, $preferences, $context, 4);
1117 //End Block
1118 fwrite ($bf,end_tag('BLOCK',3,true));
1124 //Blocks close tag
1125 $status = fwrite ($bf,end_tag('BLOCKS',2,true));
1127 return $status;
1131 //Prints course's sections info (table course_sections)
1132 function backup_course_sections ($bf,$preferences) {
1134 global $CFG;
1136 $status = true;
1139 //Get info from sections
1140 $section=false;
1141 if ($sections = get_records("course_sections","course",$preferences->backup_course,"section")) {
1142 //Section open tag
1143 fwrite ($bf,start_tag("SECTIONS",2,true));
1144 //Iterate over every section (ordered by section)
1145 foreach ($sections as $section) {
1146 //Begin Section
1147 fwrite ($bf,start_tag("SECTION",3,true));
1148 fwrite ($bf,full_tag("ID",4,false,$section->id));
1149 fwrite ($bf,full_tag("NUMBER",4,false,$section->section));
1150 fwrite ($bf,full_tag("SUMMARY",4,false,$section->summary));
1151 fwrite ($bf,full_tag("VISIBLE",4,false,$section->visible));
1152 //Now print the mods in section
1153 backup_course_modules ($bf,$preferences,$section);
1154 //End section
1155 fwrite ($bf,end_tag("SECTION",3,true));
1157 //Section close tag
1158 $status = fwrite ($bf,end_tag("SECTIONS",2,true));
1161 return $status;
1165 //Prints course's format data (any data the format might want to save).
1166 function backup_format_data ($bf,$preferences) {
1167 global $CFG;
1169 // Check course format
1170 if(!($format=get_field('course','format','id',$preferences->backup_course))) {
1171 return false;
1173 // Write appropriate tag. Note that we always put this tag there even if
1174 // blank, it makes parsing easier
1175 fwrite ($bf,start_tag("FORMATDATA",2,true));
1177 $file=$CFG->dirroot."/course/format/$format/backuplib.php";
1178 if(file_exists($file)) {
1179 // If the file is there, the function must be or it's an error.
1180 require_once($file);
1181 $function=$format.'_backup_format_data';
1182 if(!function_exists($function)) {
1183 return false;
1185 if(!$function($bf,$preferences)) {
1186 return false;
1190 // This last return just checks the file writing has been ok (ish)
1191 return fwrite ($bf,end_tag("FORMATDATA",2,true));
1194 //Prints course's modules info (table course_modules)
1195 //Only for selected mods in preferences
1196 function backup_course_modules ($bf,$preferences,$section) {
1198 global $CFG;
1200 $status = true;
1202 $first_record = true;
1204 //Now print the mods in section
1205 //Extracts mod id from sequence
1206 $tok = strtok($section->sequence,",");
1207 while ($tok) {
1208 //Get module's type
1209 $moduletype = get_module_type ($preferences->backup_course,$tok);
1210 //Check if we've selected to backup that type
1211 if ($moduletype and $preferences->mods[$moduletype]->backup) {
1212 $selected = true;
1213 } else {
1214 $selected = false;
1217 if ($selected) {
1218 $context = get_context_instance(CONTEXT_MODULE, $tok);
1219 //Gets course_module data from db - verify activity exists and is enabled!
1220 $sql = "SELECT cm.*
1221 FROM {$CFG->prefix}course_modules cm
1222 JOIN {$CFG->prefix}modules m ON m.id = cm.module
1223 JOIN {$CFG->prefix}$moduletype a ON a.id = cm.instance
1224 WHERE m.visible = 1 AND cm.id = $tok";
1225 if (!$course_module = get_record_sql($sql)) {
1226 // cm exists but activity instance missing - probably caused by double clicking
1227 $tok = strtok(",");
1228 continue;
1231 //If it's the first, pring MODS tag
1232 if ($first_record) {
1233 fwrite ($bf,start_tag("MODS",4,true));
1234 $first_record = false;
1236 // if we're doing selected instances, check that too.
1237 if (is_array($preferences->mods[$moduletype]->instances)
1238 && count($preferences->mods[$moduletype]->instances)
1239 && (!array_key_exists($course_module->instance,$preferences->mods[$moduletype]->instances)
1240 || empty($preferences->mods[$moduletype]->instances[$course_module->instance]->backup))) {
1241 $tok = strtok(",");
1242 continue;
1245 // find all role values that has an override in this context
1246 $roles = get_records('role_capabilities', 'contextid', $context->id);
1248 //Print mod info from course_modules
1249 fwrite ($bf,start_tag("MOD",5,true));
1250 //Save neccesary info to backup_ids
1251 fwrite ($bf,full_tag("ID",6,false,$tok));
1252 fwrite ($bf,full_tag("TYPE",6,false,$moduletype));
1253 fwrite ($bf,full_tag("INSTANCE",6,false,$course_module->instance));
1254 fwrite ($bf,full_tag("ADDED",6,false,$course_module->added));
1255 fwrite ($bf,full_tag("SCORE",6,false,$course_module->score));
1256 fwrite ($bf,full_tag("INDENT",6,false,$course_module->indent));
1257 fwrite ($bf,full_tag("VISIBLE",6,false,$course_module->visible));
1258 fwrite ($bf,full_tag("GROUPMODE",6,false,$course_module->groupmode));
1259 fwrite ($bf,full_tag("GROUPINGID",6,false,$course_module->groupingid));
1260 fwrite ($bf,full_tag("GROUPMEMBERSONLY",6,false,$course_module->groupmembersonly));
1261 fwrite ($bf,full_tag("IDNUMBER",6,false,$course_module->idnumber));
1262 // get all the role_capabilities overrides in this mod
1263 write_role_overrides_xml($bf, $context, 6);
1264 /// write role_assign code here
1265 write_role_assignments_xml($bf, $preferences, $context, 6);
1266 /// write role_assign code here
1268 fwrite ($bf,end_tag("MOD",5,true));
1270 //check for next
1271 $tok = strtok(",");
1274 //Si ha habido modulos, final de MODS
1275 if (!$first_record) {
1276 $status =fwrite ($bf,end_tag("MODS",4,true));
1279 return $status;
1282 //Print users to xml
1283 //Only users previously calculated in backup_ids will output
1285 function backup_user_info ($bf,$preferences) {
1287 global $CFG;
1288 require_once ($CFG->dirroot.'/tag/lib.php');
1290 $status = true;
1292 // Use a recordset to for the memory handling on to
1293 // the DB and run faster
1294 $users = get_recordset_sql("SELECT b.old_id, b.table_name, b.info,
1295 u.*, m.wwwroot
1296 FROM {$CFG->prefix}backup_ids b
1297 JOIN {$CFG->prefix}user u ON b.old_id=u.id
1298 JOIN {$CFG->prefix}mnet_host m ON u.mnethostid=m.id
1299 WHERE b.backup_code = '$preferences->backup_unique_code' AND
1300 b.table_name = 'user'");
1302 //If we have users to backup
1303 if ($users && !rs_EOF($users)) {
1304 //Begin Users tag
1305 fwrite ($bf,start_tag("USERS",2,true));
1306 $counter = 0;
1307 //With every user
1308 while ($user = rs_fetch_next_record($users)) {
1309 //Begin User tag
1310 fwrite ($bf,start_tag("USER",3,true));
1311 //Output all user data
1312 fwrite ($bf,full_tag("ID",4,false,$user->id));
1313 fwrite ($bf,full_tag("AUTH",4,false,$user->auth));
1314 fwrite ($bf,full_tag("CONFIRMED",4,false,$user->confirmed));
1315 fwrite ($bf,full_tag("POLICYAGREED",4,false,$user->policyagreed));
1316 fwrite ($bf,full_tag("DELETED",4,false,$user->deleted));
1317 fwrite ($bf,full_tag("USERNAME",4,false,$user->username));
1318 fwrite ($bf,full_tag("PASSWORD",4,false,$user->password));
1319 fwrite ($bf,full_tag("IDNUMBER",4,false,$user->idnumber));
1320 fwrite ($bf,full_tag("FIRSTNAME",4,false,$user->firstname));
1321 fwrite ($bf,full_tag("LASTNAME",4,false,$user->lastname));
1322 fwrite ($bf,full_tag("EMAIL",4,false,$user->email));
1323 fwrite ($bf,full_tag("EMAILSTOP",4,false,$user->emailstop));
1324 fwrite ($bf,full_tag("ICQ",4,false,$user->icq));
1325 fwrite ($bf,full_tag("SKYPE",4,false,$user->skype));
1326 fwrite ($bf,full_tag("YAHOO",4,false,$user->yahoo));
1327 fwrite ($bf,full_tag("AIM",4,false,$user->aim));
1328 fwrite ($bf,full_tag("MSN",4,false,$user->msn));
1329 fwrite ($bf,full_tag("PHONE1",4,false,$user->phone1));
1330 fwrite ($bf,full_tag("PHONE2",4,false,$user->phone2));
1331 fwrite ($bf,full_tag("INSTITUTION",4,false,$user->institution));
1332 fwrite ($bf,full_tag("DEPARTMENT",4,false,$user->department));
1333 fwrite ($bf,full_tag("ADDRESS",4,false,$user->address));
1334 fwrite ($bf,full_tag("CITY",4,false,$user->city));
1335 fwrite ($bf,full_tag("COUNTRY",4,false,$user->country));
1336 fwrite ($bf,full_tag("LANG",4,false,$user->lang));
1337 fwrite ($bf,full_tag("THEME",4,false,$user->theme));
1338 fwrite ($bf,full_tag("TIMEZONE",4,false,$user->timezone));
1339 fwrite ($bf,full_tag("FIRSTACCESS",4,false,$user->firstaccess));
1340 fwrite ($bf,full_tag("LASTACCESS",4,false,$user->lastaccess));
1341 fwrite ($bf,full_tag("LASTLOGIN",4,false,$user->lastlogin));
1342 fwrite ($bf,full_tag("CURRENTLOGIN",4,false,$user->currentlogin));
1343 fwrite ($bf,full_tag("LASTIP",4,false,$user->lastip));
1344 fwrite ($bf,full_tag("SECRET",4,false,$user->secret));
1345 fwrite ($bf,full_tag("PICTURE",4,false,$user->picture));
1346 fwrite ($bf,full_tag("URL",4,false,$user->url));
1347 fwrite ($bf,full_tag("DESCRIPTION",4,false,$user->description));
1348 fwrite ($bf,full_tag("MAILFORMAT",4,false,$user->mailformat));
1349 fwrite ($bf,full_tag("MAILDIGEST",4,false,$user->maildigest));
1350 fwrite ($bf,full_tag("MAILDISPLAY",4,false,$user->maildisplay));
1351 fwrite ($bf,full_tag("HTMLEDITOR",4,false,$user->htmleditor));
1352 fwrite ($bf,full_tag("AJAX",4,false,$user->ajax));
1353 fwrite ($bf,full_tag("AUTOSUBSCRIBE",4,false,$user->autosubscribe));
1354 fwrite ($bf,full_tag("TRACKFORUMS",4,false,$user->trackforums));
1355 if ($user->mnethostid != $CFG->mnet_localhost_id) {
1356 fwrite ($bf,full_tag("MNETHOSTURL",4,false,$user->wwwroot));
1358 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$user->timemodified));
1360 /// write assign/override code for context_userid
1362 $user->isneeded = strpos($user->info,"needed");
1364 fwrite ($bf,start_tag("ROLES",4,true));
1365 if ($user->info != "needed" && $user->info!="") {
1366 //PRINT ROLE INFO
1367 $roles = explode(",", $user->info);
1368 foreach ($roles as $role) {
1369 if ($role!="" && $role!="needed") {
1370 fwrite ($bf,start_tag("ROLE",5,true));
1371 //Print Role info
1372 fwrite ($bf,full_tag("TYPE",6,false,$role));
1373 //Print ROLE end
1374 fwrite ($bf,end_tag("ROLE",5,true));
1378 //Needed
1379 if ($user->isneeded!==false) {
1380 //Print ROLE start
1381 fwrite ($bf,start_tag("ROLE",5,true));
1382 //Print Role info
1383 fwrite ($bf,full_tag("TYPE",6,false,"needed"));
1384 //Print ROLE end
1385 fwrite ($bf,end_tag("ROLE",5,true));
1388 //End ROLES tag
1389 fwrite ($bf,end_tag("ROLES",4,true));
1391 //Check if we have custom profile fields to backup
1392 if ($cpfields = get_records_sql("SELECT uif.shortname, uif.datatype, uid.data
1393 FROM {$CFG->prefix}user_info_field uif,
1394 {$CFG->prefix}user_info_data uid
1395 WHERE uif.id = uid.fieldid
1396 AND uid.userid = $user->id")) {
1397 //Start USER_CUSTOM_PROFILE_FIELDS tag
1398 fwrite ($bf,start_tag("USER_CUSTOM_PROFILE_FIELDS",4,true));
1399 //Write custom profile fields
1400 foreach ($cpfields as $cpfield) {
1401 fwrite ($bf,start_tag("USER_CUSTOM_PROFILE_FIELD",5,true));
1402 fwrite ($bf,full_tag("FIELD_NAME",6,false,$cpfield->shortname));
1403 fwrite ($bf,full_tag("FIELD_TYPE",6,false,$cpfield->datatype));
1404 fwrite ($bf,full_tag("FIELD_DATA",6,false,$cpfield->data));
1405 fwrite ($bf,end_tag("USER_CUSTOM_PROFILE_FIELD",5,true));
1407 //End USER_CUSTOM_PROFILE_FIELDS tag
1408 fwrite ($bf,end_tag("USER_CUSTOM_PROFILE_FIELDS",4,true));
1411 //Check if we have user tags to backup
1412 if (!empty($CFG->usetags)) {
1413 if ($tags = tag_get_tags('user', $user->id)) { //This return them ordered by default
1414 //Start USER_TAGS tag
1415 fwrite ($bf,start_tag("USER_TAGS",4,true));
1416 //Write user tags fields
1417 foreach ($tags as $tag) {
1418 fwrite ($bf,start_tag("USER_TAG",5,true));
1419 fwrite ($bf,full_tag("NAME",6,false,$tag->name));
1420 fwrite ($bf,full_tag("RAWNAME",6,false,$tag->rawname));
1421 fwrite ($bf,end_tag("USER_TAG",5,true));
1423 //End USER_TAGS tag
1424 fwrite ($bf,end_tag("USER_TAGS",4,true));
1428 //Check if we have user_preferences to backup
1429 if ($preferences_data = get_records("user_preferences","userid",$user->old_id)) {
1430 //Start USER_PREFERENCES tag
1431 fwrite ($bf,start_tag("USER_PREFERENCES",4,true));
1432 //Write each user_preference
1433 foreach ($preferences_data as $user_preference) {
1434 fwrite ($bf,start_tag("USER_PREFERENCE",5,true));
1435 fwrite ($bf,full_tag("NAME",6,false,$user_preference->name));
1436 fwrite ($bf,full_tag("VALUE",6,false,$user_preference->value));
1437 fwrite ($bf,end_tag("USER_PREFERENCE",5,true));
1439 //End USER_PREFERENCES tag
1440 fwrite ($bf,end_tag("USER_PREFERENCES",4,true));
1443 $context = get_context_instance(CONTEXT_USER, $user->old_id);
1445 write_role_overrides_xml($bf, $context, 4);
1446 /// write role_assign code here
1447 write_role_assignments_xml($bf, $preferences, $context, 4);
1448 //End User tag
1449 fwrite ($bf,end_tag("USER",3,true));
1450 //Do some output
1451 $counter++;
1452 if ($counter % 10 == 0) {
1453 echo ".";
1454 if ($counter % 200 == 0) {
1455 echo "<br />";
1457 backup_flush(300);
1460 //End Users tag
1461 fwrite ($bf,end_tag("USERS",2,true));
1462 } else {
1463 // There aren't any users.
1464 $status = true;
1467 if ($users) {
1468 rs_close($users);
1471 return $status;
1474 //Backup log info (time ordered)
1475 function backup_log_info($bf,$preferences) {
1477 global $CFG;
1479 //Number of records to get in every chunk
1480 $recordset_size = 1000;
1482 $status = true;
1484 //Counter, points to current record
1485 $counter = 0;
1487 //Count records
1488 $count_logs = count_records("log","course",$preferences->backup_course);
1490 //Pring logs header
1491 if ($count_logs > 0 ) {
1492 fwrite ($bf,start_tag("LOGS",2,true));
1494 while ($counter < $count_logs) {
1495 //Get a chunk of records
1496 $logs = get_records ("log","course",$preferences->backup_course,"time","*",$counter,$recordset_size);
1498 //We have logs
1499 if ($logs) {
1500 //Iterate
1501 foreach ($logs as $log) {
1502 //See if it is a valid module to backup
1503 if ($log->module == "course" or
1504 $log->module == "user" or
1505 (array_key_exists($log->module, $preferences->mods) and $preferences->mods[$log->module]->backup == 1)) {
1506 // logs with 'upload' in module field are ignored, there is no restore code anyway
1507 //Begin log tag
1508 fwrite ($bf,start_tag("LOG",3,true));
1510 //Output log tag
1511 fwrite ($bf,full_tag("ID",4,false,$log->id));
1512 fwrite ($bf,full_tag("TIME",4,false,$log->time));
1513 fwrite ($bf,full_tag("USERID",4,false,$log->userid));
1514 fwrite ($bf,full_tag("IP",4,false,$log->ip));
1515 fwrite ($bf,full_tag("MODULE",4,false,$log->module));
1516 fwrite ($bf,full_tag("CMID",4,false,$log->cmid));
1517 fwrite ($bf,full_tag("ACTION",4,false,$log->action));
1518 fwrite ($bf,full_tag("URL",4,false,$log->url));
1519 fwrite ($bf,full_tag("INFO",4,false,$log->info));
1521 //End log tag
1522 fwrite ($bf,end_tag("LOG",3,true));
1524 //Do some output
1525 $counter++;
1526 if ($counter % 20 == 0) {
1527 echo ".";
1528 if ($counter % 400 == 0) {
1529 echo "<br />";
1531 backup_flush(300);
1536 //End logs tag
1537 if ($count_logs > 0 ) {
1538 $status = fwrite ($bf,end_tag("LOGS",2,true));
1540 return $status;
1543 //Backup gradebook info
1544 function backup_gradebook_info($bf, $preferences) {
1545 global $CFG;
1546 require_once($CFG->libdir.'/gradelib.php');
1548 //first make sure items are properly sorted and everything is ok
1549 grade_category::fetch_course_tree($preferences->backup_course, true);
1550 grade_regrade_final_grades($preferences->backup_course);
1552 $status = true;
1554 // see if ALL grade items of type mod of this course are being backed up
1555 // if not, we do not need to backup grade category and associated grade items/grades
1556 $backupall = true;
1558 if ($grade_items = get_records_sql("SELECT *
1559 FROM {$CFG->prefix}grade_items
1560 WHERE courseid = $preferences->backup_course
1561 AND itemtype = 'mod'")) {
1562 foreach ($grade_items as $grade_item) {
1563 // get module information
1564 // if no user data selected, we do not backup categories
1565 if (!backup_userdata_selected($preferences,$grade_item->itemmodule,$grade_item->iteminstance)) {
1566 $backupall = false;
1567 break;
1570 unset($grade_items); //free memory
1573 //Gradebook header
1574 fwrite ($bf,start_tag("GRADEBOOK",2,true));
1576 $status = backup_gradebook_outcomes_info($bf, $preferences);
1577 $status = backup_gradebook_grade_letters_info($bf,$preferences);
1579 // Now backup grade_item (inside grade_category)
1580 if ($backupall) {
1581 $status = backup_gradebook_category_info($bf,$preferences);
1584 $status = backup_gradebook_item_info($bf,$preferences, $backupall);
1586 // backup gradebook histories
1587 if ($preferences->backup_gradebook_history) {
1588 $status = backup_gradebook_outcomes_history($bf, $preferences);
1589 $status = backup_gradebook_categories_history_info($bf, $preferences);
1590 $status = backup_gradebook_items_history_info($bf, $preferences);
1591 $status = backup_gradebook_grades_history_info($bf, $preferences);
1594 //Gradebook footer
1595 $status = fwrite ($bf,end_tag("GRADEBOOK",2,true));
1596 return $status;
1599 function backup_gradebook_category_info($bf, $preferences) {
1600 global $CFG;
1601 $status = true;
1603 // get grade categories in proper order - specified in category grade items
1604 $course_item = grade_item::fetch_course_item($preferences->backup_course);
1605 $grade_categories = get_records_sql("SELECT gc.*, gi.sortorder
1606 FROM {$CFG->prefix}grade_categories gc
1607 JOIN {$CFG->prefix}grade_items gi
1608 ON (gi.iteminstance = gc.id)
1609 WHERE gc.courseid = $preferences->backup_course
1610 AND (gi.itemtype='course' OR gi.itemtype='category')
1611 ORDER BY gi.sortorder ASC");
1613 if ($grade_categories) {
1614 //Begin grade_categories tag
1615 fwrite ($bf,start_tag("GRADE_CATEGORIES",3,true));
1616 //Iterate for each category
1617 foreach ($grade_categories as $grade_category) {
1618 //Begin grade_category
1619 fwrite ($bf,start_tag("GRADE_CATEGORY",4,true));
1620 //Output individual fields
1621 fwrite ($bf,full_tag("ID",5,false,$grade_category->id));
1623 // not keeping path and depth because they can be derived
1624 fwrite ($bf,full_tag("PARENT",5,false,$grade_category->parent));
1625 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_category->fullname));
1626 fwrite ($bf,full_tag("AGGREGATION",5,false,$grade_category->aggregation));
1627 fwrite ($bf,full_tag("KEEPHIGH",5,false,$grade_category->keephigh));
1628 fwrite ($bf,full_tag("DROPLOW",5,false,$grade_category->droplow));
1629 fwrite ($bf,full_tag("AGGREGATEONLYGRADED",5,false,$grade_category->aggregateonlygraded));
1630 fwrite ($bf,full_tag("AGGREGATEOUTCOMES",5,false,$grade_category->aggregateoutcomes));
1631 fwrite ($bf,full_tag("AGGREGATESUBCATS",5,false,$grade_category->aggregatesubcats));
1632 fwrite ($bf,full_tag("TIMECREATED",5,false,$grade_category->timecreated));
1633 fwrite ($bf,full_tag("TIMEMODIFIED",5,false,$grade_category->timemodified));
1635 //End grade_category
1636 fwrite ($bf,end_tag("GRADE_CATEGORY",4,true));
1638 //End grade_categories tag
1639 $status = fwrite ($bf,end_tag("GRADE_CATEGORIES",3,true));
1642 return $status;
1645 //Backup gradebook_item (called from backup_gradebook_info
1646 function backup_gradebook_item_info($bf, $preferences, $backupall) {
1647 global $CFG;
1649 $status = true;
1650 // get all the grade_items, ordered by sort order since upon restoring, it is not always
1651 // possible to use the same sort order. We could at least preserve the sortorder by restoring
1652 // grade_items in the original sortorder
1653 if ($grade_items = get_records_sql("SELECT *
1654 FROM {$CFG->prefix}grade_items
1655 WHERE courseid = $preferences->backup_course
1656 ORDER BY sortorder ASC")) {
1658 //Begin grade_items tag
1659 fwrite ($bf,start_tag("GRADE_ITEMS",3,true));
1660 //Iterate over each item
1661 foreach ($grade_items as $item) {
1662 // Instantiate a grade_item object, to access its methods
1663 $grade_item = new grade_item($item, false);
1665 // do not restore if this grade_item is a mod, and
1666 if ($grade_item->itemtype == 'mod') {
1667 //MDL-12463 - exclude grade_items of instances not chosen for backup
1668 if (empty($preferences->mods[$grade_item->itemmodule]->instances[$grade_item->iteminstance]->backup)) {
1669 continue;
1672 } else if ($grade_item->itemtype == 'category') {
1673 // if not all grade items are being backed up
1674 // we ignore this type of grade_item and grades associated
1675 if (!$backupall) {
1676 continue;
1680 //Begin grade_item
1681 fwrite ($bf,start_tag("GRADE_ITEM",4,true));
1682 //Output individual fields
1684 fwrite ($bf,full_tag("ID",5,false,$grade_item->id));
1685 fwrite ($bf,full_tag("CATEGORYID",5,false,$grade_item->categoryid));
1686 fwrite ($bf,full_tag("ITEMNAME",5,false,$grade_item->itemname));
1687 fwrite ($bf,full_tag("ITEMTYPE",5,false,$grade_item->itemtype));
1688 fwrite ($bf,full_tag("ITEMMODULE",5,false,$grade_item->itemmodule));
1689 fwrite ($bf,full_tag("ITEMINSTANCE",5,false,$grade_item->iteminstance));
1690 fwrite ($bf,full_tag("ITEMNUMBER",5,false,$grade_item->itemnumber));
1691 fwrite ($bf,full_tag("ITEMINFO",5,false,$grade_item->iteminfo));
1692 fwrite ($bf,full_tag("IDNUMBER",5,false,$grade_item->idnumber));
1693 // use [idnumber] in calculation instead of [#giXXX#]
1694 fwrite ($bf,full_tag("CALCULATION",5,false,$grade_item->get_calculation()));
1695 fwrite ($bf,full_tag("GRADETYPE",5,false,$grade_item->gradetype));
1696 fwrite ($bf,full_tag("GRADEMAX",5,false,$grade_item->grademax));
1697 fwrite ($bf,full_tag("GRADEMIN",5,false,$grade_item->grademin));
1698 fwrite ($bf,full_tag("SCALEID",5,false,$grade_item->scaleid));
1699 fwrite ($bf,full_tag("OUTCOMEID",5,false,$grade_item->outcomeid));
1700 fwrite ($bf,full_tag("GRADEPASS",5,false,$grade_item->gradepass));
1701 fwrite ($bf,full_tag("MULTFACTOR",5,false,$grade_item->multfactor));
1702 fwrite ($bf,full_tag("PLUSFACTOR",5,false,$grade_item->plusfactor));
1703 fwrite ($bf,full_tag("AGGREGATIONCOEF",5,false,$grade_item->aggregationcoef));
1704 fwrite ($bf,full_tag("DISPLAY",5,false,$grade_item->display));
1705 fwrite ($bf,full_tag("DECIMALS",5,false,$grade_item->decimals));
1706 fwrite ($bf,full_tag("HIDDEN",5,false,$grade_item->hidden));
1707 fwrite ($bf,full_tag("LOCKED",5,false,$grade_item->locked));
1708 fwrite ($bf,full_tag("LOCKTIME",5,false,$grade_item->locktime));
1709 fwrite ($bf,full_tag("NEEDSUPDATE",5,false,$grade_item->needsupdate));
1710 fwrite ($bf,full_tag("TIMECREATED",5,false,$grade_item->timecreated));
1711 fwrite ($bf,full_tag("TIMEMODIFIED",5,false,$grade_item->timemodified));
1713 // back up the other stuff here
1714 // mod grades should only be backed up if selected
1715 if ($grade_item->itemtype == 'mod' && !backup_userdata_selected($preferences,$grade_item->itemmodule,$grade_item->iteminstance)) {
1716 // do not write grades if a mod grade_item is being restored
1717 // but userdata is not selected
1718 } else {
1719 $status = backup_gradebook_grades_info($bf,$preferences,$grade_item->id);
1721 //End grade_item
1722 fwrite ($bf,end_tag("GRADE_ITEM",4,true));
1724 //End grade_items tag
1725 $status = fwrite ($bf,end_tag("GRADE_ITEMS",3,true));
1728 return $status;
1730 //Backup gradebook_item (called from backup_gradebook_info
1732 function backup_gradebook_grade_letters_info($bf, $preferences) {
1733 global $CFG;
1734 $status = true;
1736 $context = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
1737 $grade_letters = get_records_sql("SELECT *
1738 FROM {$CFG->prefix}grade_letters
1739 WHERE contextid = $context->id");
1740 if ($grade_letters) {
1741 //Begin grade_l tag
1742 fwrite ($bf,start_tag("GRADE_LETTERS",3,true));
1743 //Iterate for each letter
1744 foreach ($grade_letters as $grade_letter) {
1745 //Begin grade_letter
1746 fwrite ($bf,start_tag("GRADE_LETTER",4,true));
1747 //Output individual fields
1748 fwrite ($bf,full_tag("ID",5,false,$grade_letter->id));
1749 fwrite ($bf,full_tag("LOWERBOUNDARY",5,false,$grade_letter->lowerboundary));
1750 fwrite ($bf,full_tag("LETTER",5,false,$grade_letter->letter));
1752 //End grade_letter
1753 fwrite ($bf,end_tag("GRADE_LETTER",4,true));
1755 //End grade_categories tag
1756 $status = fwrite ($bf,end_tag("GRADE_LETTERS",3,true));
1759 return $status;
1762 function backup_gradebook_outcomes_info($bf, $preferences) {
1764 global $CFG;
1765 $status = true;
1766 // only back up courses already in the grade_outcomes_courses table
1767 $grade_outcomes = get_records_sql("SELECT go.*
1768 FROM {$CFG->prefix}grade_outcomes go
1769 JOIN {$CFG->prefix}grade_outcomes_courses goc
1770 ON (goc.outcomeid = go.id)
1771 WHERE goc.courseid = $preferences->backup_course");
1773 if (!empty($grade_outcomes)) {
1774 //Begin grade_outcomes tag
1775 fwrite ($bf,start_tag("GRADE_OUTCOMES",3,true));
1776 //Iterate for each outcome
1777 foreach ($grade_outcomes as $grade_outcome) {
1778 //Begin grade_outcome
1779 fwrite ($bf,start_tag("GRADE_OUTCOME",4,true));
1780 //Output individual fields
1782 fwrite ($bf,full_tag("ID",5,false,$grade_outcome->id));
1783 fwrite ($bf,full_tag("COURSEID",5,false,$grade_outcome->courseid));
1784 fwrite ($bf,full_tag("SHORTNAME",5,false,$grade_outcome->shortname));
1785 fwrite ($bf,full_tag("FULLNAME",5,false,$grade_outcome->fullname));
1786 fwrite ($bf,full_tag("SCALEID",5,false,$grade_outcome->scaleid));
1787 fwrite ($bf,full_tag("DESCRIPTION",5,false,$grade_outcome->description));
1788 fwrite ($bf,full_tag("TIMECREATED",5,false,$grade_outcome->timecreated));
1789 fwrite ($bf,full_tag("TIMEMODIFIED",5,false,$grade_outcome->timemodified));
1790 fwrite ($bf,full_tag("USERMODIFIED",5,false,$grade_outcome->usermodified));
1792 //End grade_outcome
1793 fwrite ($bf,end_tag("GRADE_OUTCOME",4,true));
1795 //End grade_outcomes tag
1796 $status = fwrite ($bf,end_tag("GRADE_OUTCOMES",3,true));
1798 return $status;
1801 function backup_gradebook_grades_info($bf,$preferences, $itemid) {
1803 global $CFG;
1805 $status = true;
1807 // find all grades belonging to this item
1808 if ($grades = get_records('grade_grades', 'itemid', $itemid)) {
1809 fwrite ($bf,start_tag("GRADE_GRADES",5,true));
1810 foreach ($grades as $grade) {
1811 /// Grades are only sent to backup if the user is one target user
1812 if (backup_getid($preferences->backup_unique_code, 'user', $grade->userid)) {
1813 fwrite ($bf,start_tag("GRADE",6,true));
1814 fwrite ($bf,full_tag("ID",7,false,$grade->id));
1815 fwrite ($bf,full_tag("USERID",7,false,$grade->userid));
1816 fwrite ($bf,full_tag("RAWGRADE",7,false,$grade->rawgrade));
1817 fwrite ($bf,full_tag("RAWGRADEMAX",7,false,$grade->rawgrademax));
1818 fwrite ($bf,full_tag("RAWGRADEMIN",7,false,$grade->rawgrademin));
1819 fwrite ($bf,full_tag("RAWSCALEID",7,false,$grade->rawscaleid));
1820 fwrite ($bf,full_tag("USERMODIFIED",7,false,$grade->usermodified));
1821 fwrite ($bf,full_tag("FINALGRADE",7,false,$grade->finalgrade));
1822 fwrite ($bf,full_tag("HIDDEN",7,false,$grade->hidden));
1823 fwrite ($bf,full_tag("LOCKED",7,false,$grade->locked));
1824 fwrite ($bf,full_tag("LOCKTIME",7,false,$grade->locktime));
1825 fwrite ($bf,full_tag("EXPORTED",7,false,$grade->exported));
1826 fwrite ($bf,full_tag("OVERRIDDEN",7,false,$grade->overridden));
1827 fwrite ($bf,full_tag("EXCLUDED",7,false,$grade->excluded));
1828 fwrite ($bf,full_tag("FEEDBACK",7,false,$grade->feedback));
1829 fwrite ($bf,full_tag("FEEDBACKFORMAT",7,false,$grade->feedbackformat));
1830 fwrite ($bf,full_tag("INFORMATION",7,false,$grade->information));
1831 fwrite ($bf,full_tag("INFORMATIONFORMAT",7,false,$grade->informationformat));
1832 fwrite ($bf,full_tag("TIMECREATED",7,false,$grade->timecreated));
1833 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$grade->timemodified));
1834 fwrite ($bf,end_tag("GRADE",6,true));
1837 $status = fwrite ($bf,end_tag("GRADE_GRADES",5,true));
1839 return $status;
1842 function backup_gradebook_categories_history_info($bf, $preferences) {
1844 global $CFG;
1845 $status = true;
1847 // find all grade categories history
1848 if ($chs = get_records('grade_categories_history', 'courseid', $preferences->backup_course)) {
1849 fwrite ($bf,start_tag("GRADE_CATEGORIES_HISTORIES",5,true));
1850 foreach ($chs as $ch) {
1851 fwrite ($bf,start_tag("GRADE_CATEGORIES_HISTORY",6,true));
1852 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1853 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1854 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1855 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1856 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1857 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1858 fwrite ($bf,full_tag("PARENT",7,false,$ch->parent));
1859 fwrite ($bf,full_tag("DEPTH",7,false,$ch->depth));
1860 fwrite ($bf,full_tag("PATH",7,false,$ch->path));
1861 fwrite ($bf,full_tag("FULLNAME",7,false,$ch->fullname));
1862 fwrite ($bf,full_tag("AGGRETGATION",7,false,$ch->aggregation));
1863 fwrite ($bf,full_tag("KEEPHIGH",7,false,$ch->keephigh));
1864 fwrite ($bf,full_tag("DROPLOW",7,false,$ch->droplow));
1865 fwrite ($bf,full_tag("AGGREGATEONLYGRADED",7,false,$ch->aggregateonlygraded));
1866 fwrite ($bf,full_tag("AGGREGATEOUTCOMES",7,false,$ch->aggregateoutcomes));
1867 fwrite ($bf,full_tag("AGGREGATESUBCATS",7,false,$ch->aggregatesubcats));
1868 fwrite ($bf,end_tag("GRADE_CATEGORIES_HISTORY",6,true));
1870 $status = fwrite ($bf,end_tag("GRADE_CATEGORIES_HISTORIES",5,true));
1872 return $status;
1875 function backup_gradebook_grades_history_info($bf, $preferences) {
1877 global $CFG;
1878 $status = true;
1880 // find all grade categories history
1881 if ($chs = get_records_sql("SELECT ggh.*
1882 FROM {$CFG->prefix}grade_grades_history ggh
1883 JOIN {$CFG->prefix}grade_items gi
1884 ON gi.id = ggh.itemid
1885 WHERE gi.courseid = $preferences->backup_course")) {
1886 fwrite ($bf,start_tag("GRADE_GRADES_HISTORIES",5,true));
1887 foreach ($chs as $ch) {
1888 /// Grades are only sent to backup if the user is one target user
1889 if (backup_getid($preferences->backup_unique_code, 'user', $ch->userid)) {
1890 fwrite ($bf,start_tag("GRADE_GRADES_HISTORY",6,true));
1891 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1892 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1893 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1894 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1895 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1896 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1897 fwrite ($bf,full_tag("ITEMID",7,false,$ch->itemid));
1898 fwrite ($bf,full_tag("USERID",7,false,$ch->userid));
1899 fwrite ($bf,full_tag("RAWGRADE",7,false,$ch->rawgrade));
1900 fwrite ($bf,full_tag("RAWGRADEMAX",7,false,$ch->rawgrademax));
1901 fwrite ($bf,full_tag("RAWGRADEMIN",7,false,$ch->rawgrademin));
1902 fwrite ($bf,full_tag("RAWSCALEID",7,false,$ch->rawscaleid));
1903 fwrite ($bf,full_tag("USERMODIFIED",7,false,$ch->usermodified));
1904 fwrite ($bf,full_tag("FINALGRADE",7,false,$ch->finalgrade));
1905 fwrite ($bf,full_tag("HIDDEN",7,false,$ch->hidden));
1906 fwrite ($bf,full_tag("LOCKED",7,false,$ch->locked));
1907 fwrite ($bf,full_tag("LOCKTIME",7,false,$ch->locktime));
1908 fwrite ($bf,full_tag("EXPORTED",7,false,$ch->exported));
1909 fwrite ($bf,full_tag("OVERRIDDEN",7,false,$ch->overridden));
1910 fwrite ($bf,full_tag("EXCLUDED",7,false,$ch->excluded));
1911 fwrite ($bf,full_tag("FEEDBACK",7,false,$ch->feedback));
1912 fwrite ($bf,full_tag("FEEDBACKFORMAT",7,false,$ch->feedbackformat));
1913 fwrite ($bf,full_tag("INFORMATION",7,false,$ch->information));
1914 fwrite ($bf,full_tag("INFORMATIONFORMAT",7,false,$ch->informationformat));
1915 fwrite ($bf,end_tag("GRADE_GRADES_HISTORY",6,true));
1918 $status = fwrite ($bf,end_tag("GRADE_GRADES_HISTORIES",5,true));
1920 return $status;
1923 function backup_gradebook_items_history_info($bf, $preferences) {
1925 global $CFG;
1926 $status = true;
1928 // find all grade categories history
1929 if ($chs = get_records('grade_items_history','courseid', $preferences->backup_course)) {
1930 fwrite ($bf,start_tag("GRADE_ITEM_HISTORIES",5,true));
1931 foreach ($chs as $ch) {
1932 fwrite ($bf,start_tag("GRADE_ITEM_HISTORY",6,true));
1933 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1934 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1935 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1936 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1937 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1938 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1939 fwrite ($bf,full_tag("CATEGORYID",7,false,$ch->categoryid));
1940 fwrite ($bf,full_tag("ITEMNAME",7,false,$ch->itemname));
1941 fwrite ($bf,full_tag("ITEMTYPE",7,false,$ch->itemtype));
1942 fwrite ($bf,full_tag("ITEMMODULE",7,false,$ch->itemmodule));
1943 fwrite ($bf,full_tag("ITEMINSTANCE",7,false,$ch->iteminstance));
1944 fwrite ($bf,full_tag("ITEMNUMBER",7,false,$ch->itemnumber));
1945 fwrite ($bf,full_tag("ITEMINFO",7,false,$ch->iteminfo));
1946 fwrite ($bf,full_tag("IDNUMBER",7,false,$ch->idnumber));
1947 fwrite ($bf,full_tag("CALCULATION",7,false,$ch->calculation));
1948 fwrite ($bf,full_tag("GRADETYPE",7,false,$ch->gradetype));
1949 fwrite ($bf,full_tag("GRADEMAX",7,false,$ch->grademax));
1950 fwrite ($bf,full_tag("GRADEMIN",7,false,$ch->grademin));
1951 fwrite ($bf,full_tag("SCALEID",7,false,$ch->scaleid));
1952 fwrite ($bf,full_tag("OUTCOMEID",7,false,$ch->outcomeid));
1953 fwrite ($bf,full_tag("GRADEPASS",7,false,$ch->gradepass));
1954 fwrite ($bf,full_tag("MULTFACTOR",7,false,$ch->multfactor));
1955 fwrite ($bf,full_tag("PLUSFACTOR",7,false,$ch->plusfactor));
1956 fwrite ($bf,full_tag("AGGREGATIONCOEF",7,false,$ch->aggregationcoef));
1957 fwrite ($bf,full_tag("SORTORDER",7,false,$ch->sortorder));
1958 //fwrite ($bf,full_tag("DISPLAY",7,false,$ch->display));
1959 //fwrite ($bf,full_tag("DECIMALS",7,false,$ch->decimals));
1960 fwrite ($bf,full_tag("HIDDEN",7,false,$ch->hidden));
1961 fwrite ($bf,full_tag("LOCKED",7,false,$ch->locked));
1962 fwrite ($bf,full_tag("LOCKTIME",7,false,$ch->locktime));
1963 fwrite ($bf,full_tag("NEEDSUPDATE",7,false,$ch->needsupdate));
1964 fwrite ($bf,end_tag("GRADE_ITEM_HISTORY",6,true));
1966 $status = fwrite ($bf,end_tag("GRADE_ITEM_HISTORIES",5,true));
1969 return $status;
1972 function backup_gradebook_outcomes_history($bf, $preferences) {
1973 global $CFG;
1974 $status = true;
1976 // find all grade categories history
1977 if ($chs = get_records('grade_outcomes_history','courseid', $preferences->backup_course)) {
1978 fwrite ($bf,start_tag("GRADE_OUTCOME_HISTORIES",5,true));
1979 foreach ($chs as $ch) {
1980 fwrite ($bf,start_tag("GRADE_OUTCOME_HISTORY",6,true));
1981 fwrite ($bf,full_tag("ID",7,false,$ch->id));
1982 fwrite ($bf,full_tag("OLDID",7,false,$ch->oldid));
1983 fwrite ($bf,full_tag("ACTION",7,false,$ch->action));
1984 fwrite ($bf,full_tag("SOURCE",7,false,$ch->source));
1985 fwrite ($bf,full_tag("TIMEMODIFIED",7,false,$ch->timemodified));
1986 fwrite ($bf,full_tag("LOGGEDUSER",7,false,$ch->loggeduser));
1987 fwrite ($bf,full_tag("SHORTNAME",7,false,$ch->shortname));
1988 fwrite ($bf,full_tag("FULLNAME",7,false,$ch->fullname));
1989 fwrite ($bf,full_tag("SCALEID",7,false,$ch->scaleid));
1990 fwrite ($bf,full_tag("DESCRIPTION",7,false,$ch->description));
1991 fwrite ($bf,end_tag("GRADE_OUTCOME_HISTORY",6,true));
1993 $status = fwrite ($bf,end_tag("GRADE_OUTCOME_HISTORIES",5,true));
1995 return $status;
1998 //Backup scales info (common and course scales)
1999 function backup_scales_info($bf,$preferences) {
2001 global $CFG;
2003 $status = true;
2005 //Counter, points to current record
2006 $counter = 0;
2008 //Get scales (common and course scales)
2009 $scales = get_records_sql("SELECT id, courseid, userid, name, scale, description, timemodified
2010 FROM {$CFG->prefix}scale
2011 WHERE courseid = 0 OR courseid = $preferences->backup_course");
2013 //Copy only used scales to $backupscales. They will be in backup (unused no). See Bug 1223.
2014 $backupscales = array();
2015 if ($scales) {
2016 foreach ($scales as $scale) {
2017 if (course_scale_used($preferences->backup_course, $scale->id)) {
2018 $backupscales[] = $scale;
2023 //Pring scales header
2024 if ($backupscales) {
2025 //Pring scales header
2026 fwrite ($bf,start_tag("SCALES",2,true));
2027 //Iterate
2028 foreach ($backupscales as $scale) {
2029 //Begin scale tag
2030 fwrite ($bf,start_tag("SCALE",3,true));
2031 //Output scale tag
2032 fwrite ($bf,full_tag("ID",4,false,$scale->id));
2033 fwrite ($bf,full_tag("COURSEID",4,false,$scale->courseid));
2034 fwrite ($bf,full_tag("USERID",4,false,$scale->userid));
2035 fwrite ($bf,full_tag("NAME",4,false,$scale->name));
2036 fwrite ($bf,full_tag("SCALETEXT",4,false,$scale->scale));
2037 fwrite ($bf,full_tag("DESCRIPTION",4,false,$scale->description));
2038 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$scale->timemodified));
2039 //End scale tag
2040 fwrite ($bf,end_tag("SCALE",3,true));
2042 //End scales tag
2043 $status = fwrite ($bf,end_tag("SCALES",2,true));
2045 return $status;
2048 //Backup events info (course events)
2049 function backup_events_info($bf,$preferences) {
2051 global $CFG;
2053 $status = true;
2055 //Counter, points to current record
2056 $counter = 0;
2058 //Get events (course events)
2059 $events = get_records_select("event","courseid='$preferences->backup_course' AND instance='0'","id");
2061 //Pring events header
2062 if ($events) {
2063 //Pring events header
2064 fwrite ($bf,start_tag("EVENTS",2,true));
2065 //Iterate
2066 foreach ($events as $event) {
2067 //Begin event tag
2068 fwrite ($bf,start_tag("EVENT",3,true));
2069 //Output event tag
2070 fwrite ($bf,full_tag("ID",4,false,$event->id));
2071 fwrite ($bf,full_tag("NAME",4,false,$event->name));
2072 fwrite ($bf,full_tag("DESCRIPTION",4,false,$event->description));
2073 fwrite ($bf,full_tag("FORMAT",4,false,$event->format));
2074 fwrite ($bf,full_tag("GROUPID",4,false,$event->groupid));
2075 fwrite ($bf,full_tag("USERID",4,false,$event->userid));
2076 fwrite ($bf,full_tag("REPEATID",4,false,$event->repeatid));
2077 fwrite ($bf,full_tag("EVENTTYPE",4,false,$event->eventtype));
2078 fwrite ($bf,full_tag("MODULENAME",4,false,$event->modulename));
2079 fwrite ($bf,full_tag("TIMESTART",4,false,$event->timestart));
2080 fwrite ($bf,full_tag("TIMEDURATION",4,false,$event->timeduration));
2081 fwrite ($bf,full_tag("VISIBLE",4,false,$event->visible));
2082 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$event->timemodified));
2083 //End event tag
2084 fwrite ($bf,end_tag("EVENT",3,true));
2086 //End events tag
2087 $status = fwrite ($bf,end_tag("EVENTS",2,true));
2089 return $status;
2092 //Backup groups info
2093 function backup_groups_info($bf,$preferences) {
2095 global $CFG;
2097 $status = true;
2098 $status2 = true;
2100 //Get groups
2101 $groups = get_records("groups","courseid",$preferences->backup_course);
2103 //Pring groups header
2104 if ($groups) {
2105 //Pring groups header
2106 fwrite ($bf,start_tag("GROUPS",2,true));
2107 //Iterate
2108 foreach ($groups as $group) {
2109 //Begin group tag
2110 fwrite ($bf,start_tag("GROUP",3,true));
2111 //Output group contents
2112 fwrite ($bf,full_tag("ID",4,false,$group->id));
2113 //fwrite ($bf,full_tag("COURSEID",4,false,$group->courseid));
2114 fwrite ($bf,full_tag("NAME",4,false,$group->name));
2115 fwrite ($bf,full_tag("DESCRIPTION",4,false,$group->description));
2116 fwrite ($bf,full_tag("ENROLMENTKEY",4,false,$group->enrolmentkey));
2117 fwrite ($bf,full_tag("PICTURE",4,false,$group->picture));
2118 fwrite ($bf,full_tag("HIDEPICTURE",4,false,$group->hidepicture));
2119 fwrite ($bf,full_tag("TIMECREATED",4,false,$group->timecreated));
2120 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$group->timemodified));
2122 //Now, backup groups_members, only if users are included
2123 if ($preferences->backup_users != 2) {
2124 $status2 = backup_groups_members_info($bf,$preferences,$group->id);
2127 //End group tag
2128 fwrite ($bf,end_tag("GROUP",3,true));
2130 //End groups tag
2131 $status = fwrite ($bf,end_tag("GROUPS",2,true));
2133 //Now save group_files
2134 if ($status && $status2) {
2135 $status2 = backup_copy_group_files($preferences);
2138 return ($status && $status2);
2141 //Backup groups_members info
2142 function backup_groups_members_info($bf,$preferences,$groupid) {
2144 global $CFG;
2146 $status = true;
2148 //Get groups_members that are being included in backup
2149 $groups_members = get_records_sql("SELECT gm.*
2150 FROM {$CFG->prefix}groups_members gm,
2151 {$CFG->prefix}backup_ids bi
2152 WHERE gm.groupid = $groupid
2153 AND bi.backup_code = $preferences->backup_unique_code
2154 AND bi.table_name = 'user'");
2156 //Pring groups_members header
2157 if ($groups_members) {
2158 //Pring groups_members header
2159 fwrite ($bf,start_tag("MEMBERS",4,true));
2160 //Iterate
2161 foreach ($groups_members as $group_member) {
2162 //Begin group_member tag
2163 fwrite ($bf,start_tag("MEMBER",5,true));
2164 //Output group_member contents
2165 fwrite ($bf,full_tag("GROUPID",6,false,$group_member->groupid));
2166 fwrite ($bf,full_tag("USERID",6,false,$group_member->userid));
2167 fwrite ($bf,full_tag("TIMEADDED",6,false,$group_member->timeadded));
2168 //End group_member tag
2169 fwrite ($bf,end_tag("MEMBER",5,true));
2171 //End groups_members tag
2172 $status = fwrite ($bf,end_tag("MEMBERS",4,true));
2174 return $status;
2177 //Backup groupings info
2178 function backup_groupings_info($bf,$preferences) {
2180 global $CFG;
2182 $status = true;
2184 //Get groups
2185 $groupings = get_records("groupings","courseid",$preferences->backup_course);
2187 //Pring groups header
2188 if ($groupings) {
2189 //Pring groups header
2190 fwrite ($bf,start_tag("GROUPINGS",2,true));
2191 //Iterate
2192 foreach ($groupings as $grouping) {
2193 //Begin group tag
2194 fwrite ($bf,start_tag("GROUPING",3,true));
2195 //Output group contents
2196 fwrite ($bf,full_tag("ID",4,false,$grouping->id));
2197 //fwrite ($bf,full_tag("COURSEID",4,false,$grouping->courseid));
2198 fwrite ($bf,full_tag("NAME",4,false,$grouping->name));
2199 fwrite ($bf,full_tag("DESCRIPTION",4,false,$grouping->description));
2200 fwrite ($bf,full_tag("CONFIGDATA",4,false,$grouping->configdata));
2201 fwrite ($bf,full_tag("TIMECREATED",4,false,$grouping->timecreated));
2202 fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$grouping->timemodified));
2204 //End group tag
2205 fwrite ($bf,end_tag("GROUPING",3,true));
2207 //End groups tag
2208 $status = fwrite ($bf,end_tag("GROUPINGS",2,true));
2210 //(Now save grouping_files)
2212 return $status;
2215 //Backup groupings-groups info
2216 function backup_groupings_groups_info($bf,$preferences) {
2218 global $CFG;
2220 $status = true;
2222 //Get grouping_groups
2223 $courseid = $preferences->backup_course;
2224 $sql = "SELECT gg.* FROM {$CFG->prefix}groupings g, {$CFG->prefix}groupings_groups gg
2225 WHERE g.courseid=$courseid AND g.id=gg.groupingid";
2226 $grouping_groups = get_records_sql($sql);
2228 //Pring grouping_groups header
2229 if ($grouping_groups) {
2230 //Pring grouping_groups header
2231 fwrite ($bf,start_tag("GROUPINGSGROUPS",2,true));
2232 //Iterate
2233 foreach ($grouping_groups as $members) {
2234 //Begin grouping_group tag
2235 fwrite ($bf,start_tag("GROUPINGGROUP",3,true));
2236 //Output group_member contents
2237 fwrite ($bf,full_tag("ID",4,false,$members->id));
2238 fwrite ($bf,full_tag("GROUPINGID",4,false,$members->groupingid));
2239 fwrite ($bf,full_tag("GROUPID",4,false,$members->groupid));
2240 fwrite ($bf,full_tag("TIMEADDED",4,false,$members->timeadded));
2241 //End grouping_group tag
2242 fwrite ($bf,end_tag("GROUPINGGROUP",3,true));
2244 //End grouping_groups tag
2245 $status = fwrite ($bf,end_tag("GROUPINGSGROUPS",2,true));
2247 return $status;
2250 //Start the modules tag
2251 function backup_modules_start ($bf,$preferences) {
2253 return fwrite ($bf,start_tag("MODULES",2,true));
2256 //End the modules tag
2257 function backup_modules_end ($bf,$preferences) {
2259 return fwrite ($bf,end_tag("MODULES",2,true));
2262 //This function makes all the necesary calls to every mod
2263 //to export itself and its files !!!
2264 function backup_module($bf,$preferences,$module) {
2266 global $CFG;
2268 $status = true;
2270 require_once($CFG->dirroot.'/mod/'.$module.'/backuplib.php');
2272 if (isset($preferences->mods[$module]->instances)
2273 && is_array($preferences->mods[$module]->instances)) {
2274 $onemodbackup = $module.'_backup_one_mod';
2275 if (function_exists($onemodbackup)) {
2276 foreach ($preferences->mods[$module]->instances as $instance => $object) {
2277 if (!empty($object->backup)) {
2278 $status = $onemodbackup($bf,$preferences,$instance);
2281 } else {
2282 $status = false;
2284 } else { // whole module.
2285 //First, re-check if necessary functions exists
2286 $modbackup = $module."_backup_mods";
2287 if (function_exists($modbackup)) {
2288 //Call the function
2289 $status = $modbackup($bf,$preferences);
2290 } else {
2291 //Something was wrong. Function should exist.
2292 $status = false;
2296 return $status;
2300 //This function encode things to make backup multi-site fully functional
2301 //It does this conversions:
2302 // - $CFG->wwwroot/file.php/courseid ------------------> $@FILEPHP@$ (slasharguments links)
2303 // - $CFG->wwwroot/file.php?file=/courseid ------------> $@FILEPHP@$ (non-slasharguments links)
2304 // - Every module xxxx_encode_content_links() is executed too
2306 function backup_encode_absolute_links($content) {
2308 global $CFG,$preferences;
2310 /// MDL-14072: Prevent NULLs, empties and numbers to be processed by the
2311 /// heavy interlinking. Just a few cpu cycles saved.
2312 if ($content === NULL) {
2313 return NULL;
2314 } else if ($content === '') {
2315 return '';
2316 } else if (is_numeric($content)) {
2317 return $content;
2320 //Use one static variable to cache all the require_once calls that,
2321 //under PHP5 seems to increase load too much, and we are requiring
2322 //them here thousands of times (one per content). MDL-8700.
2323 //Once fixed by PHP, we'll delete this hack
2325 static $includedfiles;
2326 if (!isset($includedfiles)) {
2327 $includedfiles = array();
2330 //Check if preferences is ok. If it isn't set, we are
2331 //in a scheduled_backup to we are able to get a copy
2332 //from CFG->backup_preferences
2333 if (!isset($preferences)) {
2334 $mypreferences = $CFG->backup_preferences;
2335 } else {
2336 //We are in manual backups so global preferences must exist!!
2337 $mypreferences = $preferences;
2340 //First, we check for every call to file.php inside the course
2341 $search = array($CFG->wwwroot.'/file.php/'.$mypreferences->backup_course,
2342 $CFG->wwwroot.'/file.php?file=/'.$mypreferences->backup_course);
2344 $replace = array('$@FILEPHP@$','$@FILEPHP@$');
2346 $result = str_replace($search,$replace,$content);
2348 foreach ($mypreferences->mods as $name => $info) {
2349 /// We only include the corresponding backuplib.php if it hasn't been included before
2350 /// This will save some load under PHP5. MDL-8700.
2351 /// Once fixed by PHP, we'll delete this hack
2352 if (!in_array($name, $includedfiles)) {
2353 include_once("$CFG->dirroot/mod/$name/backuplib.php");
2354 $includedfiles[] = $name;
2356 //Check if the xxxx_encode_content_links exists
2357 $function_name = $name."_encode_content_links";
2358 if (function_exists($function_name)) {
2359 $result = $function_name($result,$mypreferences);
2363 // For each block, call its encode_content_links method.
2364 // This encodes forexample links to blocks/something/viewphp?id=666
2365 // that are stored in other activities.
2366 static $blockobjects = null;
2367 if (!isset($blockobjects)) {
2368 $blockobjects = array();
2369 if ($blocks = get_records('block', 'visible', 1)) {
2370 foreach ($blocks as $block) {
2371 if ($blockobject = block_instance($block->name)) {
2372 $blockobjects[] = $blockobject;
2378 foreach ($blockobjects as $blockobject) {
2379 $result = $blockobject->encode_content_links($result,$mypreferences);
2382 if ($result != $content) {
2383 debugging('<br /><hr />'.s($content).'<br />changed to<br />'.s($result).'<hr /><br />');
2386 return $result;
2389 //This function copies all the needed files under the "users" directory to the "user_files"
2390 //directory under temp/backup
2391 function backup_copy_user_files ($preferences) {
2393 global $CFG;
2395 $status = true;
2397 //First we check to "user_files" exists and create it as necessary
2398 //in temp/backup/$backup_code dir
2399 $status = check_and_create_user_files_dir($preferences->backup_unique_code);
2401 //Now iterate over directories under "user" to check if that user must be copied to backup
2403 // Method to get a list of userid=>array(basedir => $basedir, userfolder => $userfolder)
2404 $userlist = get_user_directories();
2406 foreach ($userlist as $userid => $userinfo) {
2407 //Look for dir like username in backup_ids
2408 $data = count_records("backup_ids","backup_code",$preferences->backup_unique_code, "table_name","user", "old_id",$userid);
2410 //If exists, copy it
2411 if ($data) {
2412 $parts = explode('/', $userinfo['userfolder']);
2413 $status = true;
2415 if (is_array($parts)) {
2416 $group = $parts[0];
2417 $userid = $parts[1];
2419 // Create group dir first
2420 $status = check_dir_exists("$CFG->dataroot/temp/backup/$preferences->backup_unique_code/user_files/". $group, true);
2423 $status = $status && backup_copy_file($userinfo['basedir'] . '/' . $userinfo['userfolder'],
2424 "$CFG->dataroot/temp/backup/$preferences->backup_unique_code/user_files/{$userinfo['userfolder']}");
2428 return $status;
2431 //This function copies all the needed files under the "groups" directory to the "group_files"
2432 //directory under temp/backup
2433 function backup_copy_group_files ($preferences) {
2435 global $CFG;
2437 $status = true;
2439 //First we check if "group_files" exists and create it as necessary
2440 //in temp/backup/$backup_code dir
2441 $status = check_and_create_group_files_dir($preferences->backup_unique_code);
2443 //Now iterate over directories under "groups" to check if that user must be
2444 //copied to backup
2446 $rootdir = $CFG->dataroot.'/groups';
2447 //Check if directory exists
2448 if (is_dir($rootdir)) {
2449 $list = list_directories ($rootdir);
2450 if ($list) {
2451 //Iterate
2452 foreach ($list as $dir) {
2453 //Look for dir like group in groups table
2454 $data = get_record ('groups', 'courseid', $preferences->backup_course,
2455 'id',$dir);
2456 //If exists, copy it
2457 if ($data) {
2458 $status = backup_copy_file($rootdir."/".$dir,
2459 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/group_files/".$dir);
2464 return $status;
2467 //This function copies all the course files under the course directory (except the moddata
2468 //directory to the "course_files" directory under temp/backup
2469 function backup_copy_course_files ($preferences) {
2471 global $CFG;
2473 $status = true;
2475 //First we check to "course_files" exists and create it as necessary
2476 //in temp/backup/$backup_code dir
2477 $status = check_and_create_course_files_dir($preferences->backup_unique_code);
2479 //Now iterate over files and directories except $CFG->moddata and backupdata to be
2480 //copied to backup
2482 $rootdir = $CFG->dataroot."/".$preferences->backup_course;
2484 $name_moddata = $CFG->moddata;
2485 $name_backupdata = "backupdata";
2486 //Check if directory exists
2487 if (is_dir($rootdir)) {
2488 $list = list_directories_and_files ($rootdir);
2489 if ($list) {
2490 //Iterate
2491 foreach ($list as $dir) {
2492 if ($dir !== $name_moddata and $dir !== $name_backupdata) {
2493 $status = backup_copy_file($rootdir."/".$dir,
2494 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/course_files/".$dir);
2499 return $status;
2502 * This function copies all the site files under the site directory (except the moddata and backupdata
2503 * directories to the "site_files" directory under temp/backup
2505 function backup_copy_site_files ($preferences) {
2507 global $CFG;
2509 $status = true;
2511 if ($preferences->backup_course == SITEID){
2512 return $status;
2515 //First we check to "site_files" exists and create it as necessary
2516 //in temp/backup/$backup_code dir
2517 $status = $status && check_and_create_site_files_dir($preferences->backup_unique_code);
2519 $rootdir = $CFG->dataroot."/".SITEID;
2523 $files = get_records_select('backup_files',
2524 "backup_code = '$preferences->backup_unique_code' AND file_type = 'site'");
2525 if ($files) {
2526 //Iterate
2527 foreach ($files as $fileobj) {
2528 //check for dir structure and create recursively
2529 $file = $fileobj->path;
2530 $status = $status && check_dir_exists(dirname($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/site_files/".$file), true, true);
2531 $status = $status && backup_copy_file($rootdir."/".$file,
2532 $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/site_files/".$file);
2535 return $status;
2537 //This function creates the zip file containing all the backup info
2538 //moodle.xml, moddata, user_files, course_files.
2539 //The zipped file is created in the backup directory and named with
2540 //the "oficial" name of the backup
2541 //It uses "pclzip" if available or system "zip" (unix only)
2542 function backup_zip ($preferences) {
2544 global $CFG;
2546 $status = true;
2548 //Base dir where everything happens
2549 $basedir = cleardoubleslashes($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code);
2550 //Backup zip file name
2551 $name = $preferences->backup_name;
2552 //List of files and directories
2553 $filelist = list_directories_and_files ($basedir);
2555 //Convert them to full paths
2556 $files = array();
2557 foreach ($filelist as $file) {
2558 $files[] = "$basedir/$file";
2561 $status = zip_files($files, "$basedir/$name");
2563 //echo "<br/>Status: ".$status; //Debug
2564 return $status;
2568 //This function copies the final zip to the course dir
2569 function copy_zip_to_course_dir ($preferences) {
2571 global $CFG;
2573 $status = true;
2575 //Define zip location (from)
2576 $from_zip_file = $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/".$preferences->backup_name;
2578 //Initialise $to_zip_file
2579 $to_zip_file="";
2581 //If $preferences->backup_destination isn't empty, then copy to custom directory
2582 if (!empty($preferences->backup_destination)) {
2583 $to_zip_file = $preferences->backup_destination."/".$preferences->backup_name;
2584 } else {
2585 //Define zip destination (course dir)
2586 $to_zip_file = $CFG->dataroot."/".$preferences->backup_course;
2588 //echo "<p>From: ".$from_zip_file."<br />"; //Debug
2590 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2592 //Checks course dir exists
2593 $status = check_dir_exists($to_zip_file,true);
2595 //Define zip destination (backup dir)
2596 $to_zip_file = $to_zip_file."/backupdata";
2598 //echo "<p>Checking: ".$to_zip_file."<br />"; //Debug
2600 //Checks backup dir exists
2601 $status = check_dir_exists($to_zip_file,true);
2603 //Define zip destination (zip file)
2604 $to_zip_file = $to_zip_file."/".$preferences->backup_name;
2607 //echo "<p>To: ".$to_zip_file."<br />"; //Debug
2609 //Copy zip file
2610 if ($status) {
2611 $status = backup_copy_file ($from_zip_file,$to_zip_file);
2614 return $status;
2618 * compatibility function
2619 * with new granular backup
2620 * we need to know
2622 function backup_userdata_selected($preferences,$modname,$modid) {
2623 return ((empty($preferences->mods[$modname]->instances)
2624 && !empty($preferences->mods[$modname]->userinfo))
2625 || (is_array($preferences->mods[$modname]->instances)
2626 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2627 && !empty($preferences->mods[$modname]->instances[$modid]->userinfo)));
2631 function backup_mod_selected($preferences,$modname,$modid) {
2632 return ((empty($preferences->mods[$modname]->instances)
2633 && !empty($preferences->mods[$modname]->backup))
2634 || (is_array($preferences->mods[$modname]->instances)
2635 && array_key_exists($modid,$preferences->mods[$modname]->instances)
2636 && !empty($preferences->mods[$modname]->instances[$modid]->backup)));
2640 * Checks for the required files/functions to backup every mod
2641 * And check if there is data about it
2643 function backup_fetch_prefs_from_request(&$preferences,&$count,$course) {
2644 global $CFG,$SESSION;
2646 // check to see if it's in the session already
2647 if (!empty($SESSION->backupprefs) && array_key_exists($course->id,$SESSION->backupprefs) && !empty($SESSION->backupprefs[$course->id])) {
2648 $sprefs = $SESSION->backupprefs[$course->id];
2649 $preferences = $sprefs;
2650 // refetch backup_name just in case.
2651 $bn = optional_param('backup_name','',PARAM_FILE);
2652 if (!empty($bn)) {
2653 $preferences->backup_name = $bn;
2655 $count = 1;
2656 return true;
2659 if ($allmods = get_records("modules") ) {
2660 foreach ($allmods as $mod) {
2661 $modname = $mod->name;
2662 $modfile = "$CFG->dirroot/mod/$modname/backuplib.php";
2663 $modbackup = $modname."_backup_mods";
2664 $modbackupone = $modname."_backup_one_mod";
2665 $modcheckbackup = $modname."_check_backup_mods";
2666 if (!file_exists($modfile)) {
2667 continue;
2669 include_once($modfile);
2670 if (!function_exists($modbackup) || !function_exists($modcheckbackup)) {
2671 continue;
2673 $var = "exists_".$modname;
2674 $preferences->$var = true;
2675 $count++;
2676 // check that there are instances and we can back them up individually
2677 if (!count_records('course_modules','course',$course->id,'module',$mod->id) || !function_exists($modbackupone)) {
2678 continue;
2680 $var = 'exists_one_'.$modname;
2681 $preferences->$var = true;
2682 $varname = $modname.'_instances';
2683 $preferences->$varname = get_all_instances_in_course($modname, $course, NULL, true);
2684 foreach ($preferences->$varname as $instance) {
2685 $preferences->mods[$modname]->instances[$instance->id]->name = $instance->name;
2686 $var = 'backup_'.$modname.'_instance_'.$instance->id;
2687 $$var = optional_param($var,0);
2688 $preferences->$var = $$var;
2689 $preferences->mods[$modname]->instances[$instance->id]->backup = $$var;
2690 $var = 'backup_user_info_'.$modname.'_instance_'.$instance->id;
2691 $$var = optional_param($var,0);
2692 $preferences->$var = $$var;
2693 $preferences->mods[$modname]->instances[$instance->id]->userinfo = $$var;
2694 $var = 'backup_'.$modname.'_instances';
2695 $preferences->$var = 1; // we need this later to determine what to display in modcheckbackup.
2698 //Check data
2699 //Check module info
2700 $preferences->mods[$modname]->name = $modname;
2702 $var = "backup_".$modname;
2703 $$var = optional_param( $var,0);
2704 $preferences->$var = $$var;
2705 $preferences->mods[$modname]->backup = $$var;
2707 //Check include user info
2708 $var = "backup_user_info_".$modname;
2709 $$var = optional_param( $var,0);
2710 $preferences->$var = $$var;
2711 $preferences->mods[$modname]->userinfo = $$var;
2716 //Check other parameters
2717 $preferences->backup_metacourse = optional_param('backup_metacourse',1,PARAM_INT);
2718 $preferences->backup_users = optional_param('backup_users',1,PARAM_INT);
2719 $preferences->backup_logs = optional_param('backup_logs',0,PARAM_INT);
2720 $preferences->backup_user_files = optional_param('backup_user_files',1,PARAM_INT);
2721 $preferences->backup_course_files = optional_param('backup_course_files',1,PARAM_INT);
2722 $preferences->backup_gradebook_history = optional_param('backup_gradebook_history', 1, PARAM_INT);
2723 $preferences->backup_site_files = optional_param('backup_site_files',1,PARAM_INT);
2724 $preferences->backup_messages = optional_param('backup_messages',1,PARAM_INT);
2725 $preferences->backup_blogs = optional_param('backup_blogs',1,PARAM_INT);
2726 $preferences->backup_course = $course->id;
2727 $preferences->backup_name = required_param('backup_name',PARAM_FILE);
2728 $preferences->backup_unique_code = required_param('backup_unique_code');
2730 $roles = get_records('role', '', '', 'sortorder');
2731 $preferences->backuproleassignments = array();
2732 foreach ($roles as $role) {
2733 if (optional_param('backupassignments_' . $role->shortname, 0, PARAM_INT)) {
2734 $preferences->backuproleassignments[$role->id] = $role;
2738 // put it (back) in the session
2739 $SESSION->backupprefs[$course->id] = $preferences;
2742 /* Finds all related roles used in course, mod and blocks context
2743 * @param object $preferences
2744 * @param object $course
2745 * @return array of role objects
2747 function backup_fetch_roles($preferences) {
2749 global $CFG;
2750 $contexts = array();
2751 $roles = array();
2753 /// adding course context
2754 $coursecontext = get_context_instance(CONTEXT_COURSE, $preferences->backup_course);
2755 $contexts[$coursecontext->id] = $coursecontext;
2757 /// adding mod contexts
2758 $mods = $preferences->mods;
2759 foreach ($mods as $modname => $mod) {
2760 $instances = $mod->instances;
2761 foreach ($instances as $id => $instance) {
2762 // if this type of mod is to be backed up
2763 if ($instance->backup) {
2764 $cm = get_coursemodule_from_instance($modname, $id);
2765 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2766 // put context in array keys
2767 $contexts[$context->id] = $context;
2772 // add all roles assigned at user context
2773 if ($preferences->backup_users) {
2774 if ($users = get_records_sql("SELECT u.old_id, u.table_name,u.info
2775 FROM {$CFG->prefix}backup_ids u
2776 WHERE u.backup_code = '$preferences->backup_unique_code' AND
2777 u.table_name = 'user'")) {
2778 foreach ($users as $user) {
2779 $context = get_context_instance(CONTEXT_USER, $user->old_id);
2780 $contexts[$context->id] = $context;
2786 // add all roles assigned at block context
2787 if ($courseblocks = get_records_sql("SELECT *
2788 FROM {$CFG->prefix}block_instance
2789 WHERE pagetype = '".PAGE_COURSE_VIEW."'
2790 AND pageid = {$preferences->backup_course}")) {
2792 foreach ($courseblocks as $courseblock) {
2794 $context = get_context_instance(CONTEXT_BLOCK, $courseblock->id);
2795 $contexts[$context->id] = $context;
2799 // foreach context, call get_roles_on_exact_context insert into array
2800 foreach ($contexts as $context) {
2801 if ($proles = get_roles_on_exact_context($context)) {
2802 foreach ($proles as $prole) {
2803 $roles[$prole->id] = $prole;
2808 return $roles;
2811 /* function to print xml for overrides */
2812 function write_role_overrides_xml($bf, $context, $startlevel) {
2813 fwrite ($bf, start_tag("ROLES_OVERRIDES", $startlevel, true));
2814 if ($roles = get_roles_with_override_on_context($context)) {
2815 foreach ($roles as $role) {
2816 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2817 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2818 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2819 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2820 fwrite ($bf, start_tag("CAPABILITIES", $startlevel+2, true));
2821 if ($capabilities = get_capabilities_from_role_on_context($role, $context)) {
2822 foreach ($capabilities as $capability) {
2823 fwrite ($bf, start_tag("CAPABILITY", $startlevel+3, true));
2824 fwrite ($bf, full_tag("NAME", $startlevel+4, false, $capability->capability));
2825 fwrite ($bf, full_tag("PERMISSION", $startlevel+4, false, $capability->permission));
2826 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $capability->timemodified));
2827 if (!isset($capability->modifierid)) {
2828 $capability->modifierid = 0;
2830 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $capability->modifierid));
2831 fwrite ($bf, end_tag("CAPABILITY", $startlevel+3, true));
2834 fwrite ($bf, end_tag("CAPABILITIES", $startlevel+2, true));
2835 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2838 fwrite ($bf, end_tag("ROLES_OVERRIDES", $startlevel, true));
2841 /* function to print xml for assignment */
2842 function write_role_assignments_xml($bf, $preferences, $context, $startlevel) {
2843 /// write role_assign code here
2844 fwrite ($bf, start_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2846 if ($roles = get_roles_with_assignment_on_context($context)) {
2847 foreach ($roles as $role) {
2848 /// Skip non-selected roles
2849 if (!isset($preferences->backuproleassignments[$role->id])) {
2850 continue;
2852 fwrite ($bf, start_tag("ROLE", $startlevel+1, true));
2853 fwrite ($bf, full_tag("ID", $startlevel+2, false, $role->id));
2854 fwrite ($bf, full_tag("NAME", $startlevel+2, false, $role->name));
2855 fwrite ($bf, full_tag("SHORTNAME", $startlevel+2, false, $role->shortname));
2856 fwrite ($bf, start_tag("ASSIGNMENTS", $startlevel+2, true));
2857 if ($assignments = get_users_from_role_on_context($role, $context)) {
2858 foreach ($assignments as $assignment) {
2859 /// Role assignments are only sent to backup if the user is one target user
2860 if (backup_getid($preferences->backup_unique_code, 'user', $assignment->userid)) {
2861 fwrite ($bf, start_tag("ASSIGNMENT", $startlevel+3, true));
2862 fwrite ($bf, full_tag("USERID", $startlevel+4, false, $assignment->userid));
2863 fwrite ($bf, full_tag("HIDDEN", $startlevel+4, false, $assignment->hidden));
2864 fwrite ($bf, full_tag("TIMESTART", $startlevel+4, false, $assignment->timestart));
2865 fwrite ($bf, full_tag("TIMEEND", $startlevel+4, false, $assignment->timeend));
2866 fwrite ($bf, full_tag("TIMEMODIFIED", $startlevel+4, false, $assignment->timemodified));
2867 if (!isset($assignment->modifierid)) {
2868 $assignment->modifierid = 0;
2870 fwrite ($bf, full_tag("MODIFIERID", $startlevel+4, false, $assignment->modifierid));
2871 fwrite ($bf, full_tag("ENROL", $startlevel+4, false, $assignment->enrol));
2872 fwrite ($bf, full_tag("SORTORDER", $startlevel+4, false, $assignment->sortorder));
2873 fwrite ($bf, end_tag("ASSIGNMENT", $startlevel+3, true));
2877 fwrite ($bf, end_tag("ASSIGNMENTS", $startlevel+2, true));
2878 fwrite ($bf, end_tag("ROLE", $startlevel+1, true));
2881 fwrite ($bf, end_tag("ROLES_ASSIGNMENTS", $startlevel, true));
2885 function backup_execute(&$preferences, &$errorstr) {
2886 global $CFG;
2887 $status = true;
2889 //Check for temp and backup and backup_unique_code directory
2890 //Create them as needed
2891 if (!defined('BACKUP_SILENTLY')) {
2892 echo "<li>".get_string("creatingtemporarystructures").'</li>';
2895 $status = check_and_create_backup_dir($preferences->backup_unique_code);
2896 //Empty dir
2897 if ($status) {
2898 $status = clear_backup_dir($preferences->backup_unique_code);
2901 //Delete old_entries from backup tables
2902 if (!defined('BACKUP_SILENTLY')) {
2903 echo "<li>".get_string("deletingolddata").'</li>';
2905 $status = backup_delete_old_data();
2906 if (!$status) {
2907 if (!defined('BACKUP_SILENTLY')) {
2908 notify ("An error occurred deleting old backup data");
2910 else {
2911 $errorstr = "An error occurred deleting old backup data";
2912 return false;
2916 //Create the moodle.xml file
2917 if ($status) {
2918 if (!defined('BACKUP_SILENTLY')) {
2919 echo "<li>".get_string("creatingxmlfile");
2920 //Begin a new list to xml contents
2921 echo "<ul>";
2922 echo "<li>".get_string("writingheader").'</li>';
2924 //Obtain the xml file (create and open) and print prolog information
2925 $backup_file = backup_open_xml($preferences->backup_unique_code);
2926 if (!defined('BACKUP_SILENTLY')) {
2927 echo "<li>".get_string("writinggeneralinfo").'</li>';
2929 //Prints general info about backup to file
2930 if ($backup_file) {
2931 if (!$status = backup_general_info($backup_file,$preferences)) {
2932 if (!defined('BACKUP_SILENTLY')) {
2933 notify("An error occurred while backing up general info");
2935 else {
2936 $errorstr = "An error occurred while backing up general info";
2937 return false;
2941 if (!defined('BACKUP_SILENTLY')) {
2942 echo "<li>".get_string("writingcoursedata");
2943 //Start new ul (for course)
2944 echo "<ul>";
2945 echo "<li>".get_string("courseinfo").'</li>';
2947 //Prints course start (tag and general info)
2948 if ($status) {
2949 if (!$status = backup_course_start($backup_file,$preferences)) {
2950 if (!defined('BACKUP_SILENTLY')) {
2951 notify("An error occurred while backing up course start");
2953 else {
2954 $errorstr = "An error occurred while backing up course start";
2955 return false;
2959 //Metacourse information
2960 if ($status && $preferences->backup_metacourse) {
2961 if (!defined('BACKUP_SILENTLY')) {
2962 echo "<li>".get_string("metacourse").'</li>';
2964 if (!$status = backup_course_metacourse($backup_file,$preferences)) {
2965 if (!defined('BACKUP_SILENTLY')) {
2966 notify("An error occurred while backing up metacourse info");
2968 else {
2969 $errorstr = "An error occurred while backing up metacourse info";
2970 return false;
2974 if (!defined('BACKUP_SILENTLY')) {
2975 echo "<li>".get_string("blocks").'</li>';
2977 //Blocks information
2978 if ($status) {
2979 if (!$status = backup_course_blocks($backup_file,$preferences)) {
2980 if (!defined('BACKUP_SILENTLY')) {
2981 notify("An error occurred while backing up course blocks");
2983 else {
2984 $errorstr = "An error occurred while backing up course blocks";
2985 return false;
2989 if (!defined('BACKUP_SILENTLY')) {
2990 echo "<li>".get_string("sections").'</li>';
2992 //Section info
2993 if ($status) {
2994 if (!$status = backup_course_sections($backup_file,$preferences)) {
2995 if (!defined('BACKUP_SILENTLY')) {
2996 notify("An error occurred while backing up course sections");
2998 else {
2999 $errorstr = "An error occurred while backing up course sections";
3000 return false;
3005 //End course contents (close ul)
3006 if (!defined('BACKUP_SILENTLY')) {
3007 echo "</ul></li>";
3010 //User info
3011 if ($status) {
3012 if (!defined('BACKUP_SILENTLY')) {
3013 echo "<li>".get_string("writinguserinfo").'</li>';
3015 if (!$status = backup_user_info($backup_file,$preferences)) {
3016 if (!defined('BACKUP_SILENTLY')) {
3017 notify("An error occurred while backing up user info");
3019 else {
3020 $errorstr = "An error occurred while backing up user info";
3021 return false;
3026 //If we have selected to backup messages and we are
3027 //doing a SITE backup, let's do it
3028 if ($status && $preferences->backup_messages && $preferences->backup_course == SITEID) {
3029 if (!defined('BACKUP_SILENTLY')) {
3030 echo "<li>".get_string("writingmessagesinfo").'</li>';
3032 if (!$status = backup_messages($backup_file,$preferences)) {
3033 if (!defined('BACKUP_SILENTLY')) {
3034 notify("An error occurred while backing up messages");
3036 else {
3037 $errorstr = "An error occurred while backing up messages";
3038 return false;
3043 //If we have selected to backup blogs and we are
3044 //doing a SITE backup, let's do it
3045 if ($status && $preferences->backup_blogs && $preferences->backup_course == SITEID) {
3046 if (!defined('BACKUP_SILENTLY')) {
3047 echo "<li>".get_string("writingblogsinfo").'</li>';
3049 if (!$status = backup_blogs($backup_file,$preferences)) {
3050 if (!defined('BACKUP_SILENTLY')) {
3051 notify("An error occurred while backing up blogs");
3053 else {
3054 $errorstr = "An error occurred while backing up blogs";
3055 return false;
3060 //If we have selected to backup quizzes or other modules that use questions
3061 //we've already added ids of categories and questions to backup to backup_ids table
3062 if ($status) {
3063 if (!defined('BACKUP_SILENTLY')) {
3064 echo "<li>".get_string("writingcategoriesandquestions").'</li>';
3066 require_once($CFG->dirroot.'/question/backuplib.php');
3067 if (!$status = backup_question_categories($backup_file, $preferences)) {
3068 if (!defined('BACKUP_SILENTLY')) {
3069 notify("An error occurred while backing up quiz categories");
3071 else {
3072 $errorstr = "An error occurred while backing up quiz categories";
3073 return false;
3078 //Print logs if selected
3079 if ($status) {
3080 if ($preferences->backup_logs) {
3081 if (!defined('BACKUP_SILENTLY')) {
3082 echo "<li>".get_string("writingloginfo").'</li>';
3084 if (!$status = backup_log_info($backup_file,$preferences)) {
3085 if (!defined('BACKUP_SILENTLY')) {
3086 notify("An error occurred while backing up log info");
3088 else {
3089 $errorstr = "An error occurred while backing up log info";
3090 return false;
3096 //Print scales info
3097 if ($status) {
3098 if (!defined('BACKUP_SILENTLY')) {
3099 echo "<li>".get_string("writingscalesinfo").'</li>';
3101 if (!$status = backup_scales_info($backup_file,$preferences)) {
3102 if (!defined('BACKUP_SILENTLY')) {
3103 notify("An error occurred while backing up scales");
3105 else {
3106 $errorstr = "An error occurred while backing up scales";
3107 return false;
3112 //Print groups info
3113 if ($status) {
3114 if (!defined('BACKUP_SILENTLY')) {
3115 echo "<li>".get_string("writinggroupsinfo").'</li>';
3117 if (!$status = backup_groups_info($backup_file,$preferences)) {
3118 if (!defined('BACKUP_SILENTLY')) {
3119 notify("An error occurred while backing up groups");
3121 else {
3122 $errostr = "An error occurred while backing up groups";
3123 return false;
3128 //Print groupings info
3129 if ($status) {
3130 if (!defined('BACKUP_SILENTLY')) {
3131 echo "<li>".get_string("writinggroupingsinfo").'</li>';
3133 if (!$status = backup_groupings_info($backup_file,$preferences)) {
3134 if (!defined('BACKUP_SILENTLY')) {
3135 notify("An error occurred while backing up groupings");
3137 else {
3138 $errorstr = "An error occurred while backing up groupings";
3139 return false;
3144 //Print groupings_groups info
3145 if ($status) {
3146 if (!defined('BACKUP_SILENTLY')) {
3147 echo "<li>".get_string("writinggroupingsgroupsinfo").'</li>';
3149 if (!$status = backup_groupings_groups_info($backup_file,$preferences)) {
3150 if (!defined('BACKUP_SILENTLY')) {
3151 notify("An error occurred while backing up groupings groups");
3153 else {
3154 $errorstr = "An error occurred while backing up groupings groups";
3155 return false;
3160 //Print events info
3161 if ($status) {
3162 if (!defined('BACKUP_SILENTLY')) {
3163 echo "<li>".get_string("writingeventsinfo").'</li>';
3165 if (!$status = backup_events_info($backup_file,$preferences)) {
3166 if (!defined('BACKUP_SILENTLY')) {
3167 notify("An error occurred while backing up events");
3169 else {
3170 $errorstr = "An error occurred while backing up events";
3171 return false;
3176 //Print gradebook info
3177 if ($status) {
3178 if (!defined('BACKUP_SILENTLY')) {
3179 echo "<li>".get_string("writinggradebookinfo").'</li>';
3181 if (!$status = backup_gradebook_info($backup_file,$preferences)) {
3182 if (!defined('BACKUP_SILENTLY')) {
3183 notify("An error occurred while backing up gradebook");
3185 else {
3186 $errorstr = "An error occurred while backing up gradebook";
3187 return false;
3192 //Module info, this unique function makes all the work!!
3193 //db export and module fileis copy
3194 if ($status) {
3195 $mods_to_backup = false;
3196 //Check if we have any mod to backup
3197 foreach ($preferences->mods as $module) {
3198 if ($module->backup) {
3199 $mods_to_backup = true;
3202 //If we have to backup some module
3203 if ($mods_to_backup) {
3204 if (!defined('BACKUP_SILENTLY')) {
3205 echo "<li>".get_string("writingmoduleinfo");
3207 //Start modules tag
3208 if (!$status = backup_modules_start ($backup_file,$preferences)) {
3209 if (!defined('BACKUP_SILENTLY')) {
3210 notify("An error occurred while backing up module info");
3212 else {
3213 $errorstr = "An error occurred while backing up module info";
3214 return false;
3217 //Open ul for module list
3218 if (!defined('BACKUP_SILENTLY')) {
3219 echo "<ul>";
3221 //Iterate over modules and call backup
3222 foreach ($preferences->mods as $module) {
3223 if ($module->backup and $status) {
3224 if (!defined('BACKUP_SILENTLY')) {
3225 echo "<li>".get_string("modulenameplural",$module->name).'</li>';
3227 if (!$status = backup_module($backup_file,$preferences,$module->name)) {
3228 if (!defined('BACKUP_SILENTLY')) {
3229 notify("An error occurred while backing up '$module->name'");
3231 else {
3232 $errorstr = "An error occurred while backing up '$module->name'";
3233 return false;
3238 //Close ul for module list
3239 if (!defined('BACKUP_SILENTLY')) {
3240 echo "</ul></li>";
3242 //Close modules tag
3243 if (!$status = backup_modules_end ($backup_file,$preferences)) {
3244 if (!defined('BACKUP_SILENTLY')) {
3245 notify("An error occurred while finishing the module backups");
3247 else {
3248 $errorstr = "An error occurred while finishing the module backups";
3249 return false;
3255 //Backup course format data, if any.
3256 if (!defined('BACKUP_SILENTLY')) {
3257 echo '<li>'.get_string("courseformatdata").'</li>';
3259 if($status) {
3260 if (!$status = backup_format_data($backup_file,$preferences)) {
3261 if (!defined('BACKUP_SILENTLY')) {
3262 notify("An error occurred while backing up the course format data");
3264 else {
3265 $errorstr = "An error occurred while backing up the course format data";
3266 return false;
3271 //Prints course end
3272 if ($status) {
3273 if (!$status = backup_course_end($backup_file,$preferences)) {
3274 if (!defined('BACKUP_SILENTLY')) {
3275 notify("An error occurred while closing the course backup");
3277 else {
3278 $errorstr = "An error occurred while closing the course backup";
3279 return false;
3283 //Close the xml file and xml data
3284 if ($backup_file) {
3285 backup_close_xml($backup_file);
3288 //End xml contents (close ul)
3289 if (!defined('BACKUP_SILENTLY')) {
3290 echo "</ul></li>";
3294 //Now, if selected, copy user files
3295 if ($status) {
3296 if ($preferences->backup_user_files) {
3297 if (!defined('BACKUP_SILENTLY')) {
3298 echo "<li>".get_string("copyinguserfiles").'</li>';
3300 if (!$status = backup_copy_user_files ($preferences)) {
3301 if (!defined('BACKUP_SILENTLY')) {
3302 notify("An error occurred while copying user files");
3304 else {
3305 $errorstr = "An error occurred while copying user files";
3306 return false;
3312 //Now, if selected, copy course files
3313 if ($status) {
3314 if ($preferences->backup_course_files) {
3315 if (!defined('BACKUP_SILENTLY')) {
3316 echo "<li>".get_string("copyingcoursefiles").'</li>';
3318 if (!$status = backup_copy_course_files ($preferences)) {
3319 if (!defined('BACKUP_SILENTLY')) {
3320 notify("An error occurred while copying course files");
3322 else {
3323 $errorstr = "An error occurred while copying course files";
3324 return false;
3329 //Now, if selected, copy site files
3330 if ($status) {
3331 if ($preferences->backup_site_files) {
3332 if (!defined('BACKUP_SILENTLY')) {
3333 echo "<li>".get_string("copyingsitefiles").'</li>';
3335 if (!$status = backup_copy_site_files ($preferences)) {
3336 if (!defined('BACKUP_SILENTLY')) {
3337 notify("An error occurred while copying site files");
3339 else {
3340 $errorstr = "An error occurred while copying site files";
3341 return false;
3346 //Now, zip all the backup directory contents
3347 if ($status) {
3348 if (!defined('BACKUP_SILENTLY')) {
3349 echo "<li>".get_string("zippingbackup").'</li>';
3351 if (!$status = backup_zip ($preferences)) {
3352 if (!defined('BACKUP_SILENTLY')) {
3353 notify("An error occurred while zipping the backup");
3355 else {
3356 $errorstr = "An error occurred while zipping the backup";
3357 return false;
3362 //Now, copy the zip file to course directory
3363 if ($status) {
3364 if (!defined('BACKUP_SILENTLY')) {
3365 echo "<li>".get_string("copyingzipfile").'</li>';
3367 if (!$status = copy_zip_to_course_dir ($preferences)) {
3368 if (!defined('BACKUP_SILENTLY')) {
3369 notify("An error occurred while copying the zip file to the course directory");
3371 else {
3372 $errorstr = "An error occurred while copying the zip file to the course directory";
3373 return false;
3378 //Now, clean temporary data (db and filesystem)
3379 if ($status) {
3380 if (!defined('BACKUP_SILENTLY')) {
3381 echo "<li>".get_string("cleaningtempdata").'</li>';
3383 if (!$status = clean_temp_data ($preferences)) {
3384 if (!defined('BACKUP_SILENTLY')) {
3385 notify("An error occurred while cleaning up temporary data");
3387 else {
3388 $errorstr = "An error occurred while cleaning up temporary data";
3389 return false;
3394 return $status;
3398 * This function calculates the "backup" part of the file name
3399 * from lang files. Used both in manual and scheduled backups
3401 * @param object $course course object
3402 * @return string "backup" part of the filename
3404 function backup_get_backup_string($course) {
3406 /// Calculate the backup word
3407 /// Take off some characters in the filename !!
3408 $takeoff = array(" ", ":", "/", "\\", "|");
3409 $backup_word = str_replace($takeoff,"_",moodle_strtolower(get_string("backupfilename")));
3410 /// If non-translated, use "backup"
3411 if (substr($backup_word,0,1) == "[") {
3412 $backup_word= "backup";
3415 return $backup_word;
3419 * This function generates the default zipfile name for a backup
3420 * based on the course shortname
3422 * @param object $course course object
3423 * @return string filename (excluding path information)
3425 function backup_get_zipfile_name($course) {
3427 //Calculate the backup word
3428 $backup_word = backup_get_backup_string($course);
3430 //Calculate the date format string
3431 $backup_date_format = str_replace(" ","_",get_string("backupnameformat"));
3432 //If non-translated, use "%Y%m%d-%H%M"
3433 if (substr($backup_date_format,0,1) == "[") {
3434 $backup_date_format = "%%Y%%m%%d-%%H%%M";
3437 //Calculate the shortname
3438 $backup_shortname = clean_filename($course->shortname);
3439 if (empty($backup_shortname) or $backup_shortname == '_' ) {
3440 $backup_shortname = $course->id;
3443 //Calculate the final backup filename
3444 //The backup word
3445 $backup_name = $backup_word."-";
3446 //The shortname
3447 $backup_name .= moodle_strtolower($backup_shortname)."-";
3448 //The date format
3449 $backup_name .= userdate(time(),$backup_date_format,99,false);
3450 //The extension
3451 $backup_name .= ".zip";
3452 //And finally, clean everything
3453 $backup_name = clean_filename($backup_name);
3455 return $backup_name;
3459 * This function generates the common file substring for a course
3460 * used to keep n copies by the scheduled backup
3462 * @param object $course course object
3463 * @return string common part of filename in backups of this course
3465 function backup_get_keep_name($course) {
3467 //Calculate the backup word
3468 $backup_word = backup_get_backup_string($course);
3470 //Calculate the shortname
3471 $backup_shortname = clean_filename($course->shortname);
3472 if (empty($backup_shortname) or $backup_shortname == '_' ) {
3473 $backup_shortname = $course->id;
3476 $keep_name = $backup_word . "-" . moodle_strtolower($backup_shortname)."-";
3477 $keep_name = clean_filename($keep_name);
3479 return $keep_name;
3482 * This function adds on the standard items to the preferences
3483 * Like moodle version and backup version
3485 * @param object $preferences existing preferences object.
3486 * (passed by reference)
3488 function backup_add_static_preferences(&$preferences) {
3489 global $CFG;
3490 $preferences->moodle_version = $CFG->version;
3491 $preferences->moodle_release = $CFG->release;
3492 $preferences->backup_version = $CFG->backup_version;
3493 $preferences->backup_release = $CFG->backup_release;